sqlite3.c 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192
  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. int fdatasync(fd)
  23047. {
  23048. fsync(fd);
  23049. }
  23050. #endif
  23051. /*
  23052. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  23053. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  23054. ** only available on Mac OS X. But that could change.
  23055. */
  23056. #ifdef F_FULLFSYNC
  23057. # define HAVE_FULLFSYNC 0
  23058. #endif
  23059. /*
  23060. ** The fsync() system call does not work as advertised on many
  23061. ** unix systems. The following procedure is an attempt to make
  23062. ** it work better.
  23063. **
  23064. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  23065. ** for testing when we want to run through the test suite quickly.
  23066. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  23067. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  23068. ** or power failure will likely corrupt the database file.
  23069. **
  23070. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  23071. ** The idea behind dataOnly is that it should only write the file content
  23072. ** to disk, not the inode. We only set dataOnly if the file size is
  23073. ** unchanged since the file size is part of the inode. However,
  23074. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  23075. ** file size has changed. The only real difference between fdatasync()
  23076. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  23077. ** inode if the mtime or owner or other inode attributes have changed.
  23078. ** We only care about the file size, not the other file attributes, so
  23079. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  23080. ** So, we always use fdatasync() if it is available, regardless of
  23081. ** the value of the dataOnly flag.
  23082. */
  23083. static int full_fsync(int fd, int fullSync, int dataOnly){
  23084. int rc;
  23085. /* The following "ifdef/elif/else/" block has the same structure as
  23086. ** the one below. It is replicated here solely to avoid cluttering
  23087. ** up the real code with the UNUSED_PARAMETER() macros.
  23088. */
  23089. #ifdef SQLITE_NO_SYNC
  23090. UNUSED_PARAMETER(fd);
  23091. UNUSED_PARAMETER(fullSync);
  23092. UNUSED_PARAMETER(dataOnly);
  23093. #elif HAVE_FULLFSYNC
  23094. UNUSED_PARAMETER(dataOnly);
  23095. #else
  23096. UNUSED_PARAMETER(fullSync);
  23097. UNUSED_PARAMETER(dataOnly);
  23098. #endif
  23099. /* Record the number of times that we do a normal fsync() and
  23100. ** FULLSYNC. This is used during testing to verify that this procedure
  23101. ** gets called with the correct arguments.
  23102. */
  23103. #ifdef SQLITE_TEST
  23104. if( fullSync ) sqlite3_fullsync_count++;
  23105. sqlite3_sync_count++;
  23106. #endif
  23107. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  23108. ** no-op
  23109. */
  23110. #ifdef SQLITE_NO_SYNC
  23111. rc = SQLITE_OK;
  23112. #elif HAVE_FULLFSYNC
  23113. #error "rtthread not support FULLFSYNC"
  23114. #else
  23115. rc = fdatasync(fd);
  23116. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  23117. return rc;
  23118. }
  23119. /*
  23120. ** Make sure all writes to a particular file are committed to disk.
  23121. **
  23122. ** If dataOnly==0 then both the file itself and its metadata (file
  23123. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  23124. ** file data is synced.
  23125. **
  23126. ** Under Rtthread, also make sure that the directory entry for the file
  23127. ** has been created by fsync-ing the directory that contains the file.
  23128. ** If we do not do this and we encounter a power failure, the directory
  23129. ** entry for the journal might not exist after we reboot. The next
  23130. ** SQLite to access the file will not know that the journal exists (because
  23131. ** the directory entry for the journal was never created) and the transaction
  23132. ** will not roll back - possibly leading to database corruption.
  23133. */
  23134. static int rtthreadSync(sqlite3_file *id, int flags){
  23135. int rc;
  23136. rtthreadFile *pFile = (rtthreadFile*)id;
  23137. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  23138. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  23139. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  23140. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  23141. || (flags&0x0F)==SQLITE_SYNC_FULL
  23142. );
  23143. /* Rtthread cannot, but some systems may return SQLITE_FULL from here. This
  23144. ** line is to test that doing so does not cause any problems.
  23145. */
  23146. SimulateDiskfullError( return SQLITE_FULL );
  23147. assert( pFile );
  23148. OSTRACE(("SYNC %-3d\n", pFile->h));
  23149. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  23150. SimulateIOError( rc=1 );
  23151. if( rc ){
  23152. pFile->lastErrno = errno;
  23153. return rtthreadLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  23154. }
  23155. /* Also fsync the directory containing the file if the DIRSYNC flag
  23156. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  23157. ** are unable to fsync a directory, so ignore errors on the fsync.
  23158. */
  23159. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  23160. int dirfd;
  23161. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  23162. HAVE_FULLFSYNC, isFullsync));
  23163. rc = osOpenDirectory(pFile->zPath, &dirfd);
  23164. if( rc==SQLITE_OK && dirfd>=0 ){
  23165. full_fsync(dirfd, 0, 0);
  23166. robust_close(pFile, dirfd, __LINE__);
  23167. }else if( rc==SQLITE_CANTOPEN ){
  23168. rc = SQLITE_OK;
  23169. }
  23170. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  23171. }
  23172. return rc;
  23173. }
  23174. /*
  23175. ** Truncate an open file to a specified size
  23176. */
  23177. static int rtthreadTruncate(sqlite3_file *id, i64 nByte){
  23178. rtthreadFile *pFile = (rtthreadFile *)id;
  23179. int rc;
  23180. assert( pFile );
  23181. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  23182. /* If the user has configured a chunk-size for this file, truncate the
  23183. ** file so that it consists of an integer number of chunks (i.e. the
  23184. ** actual file size after the operation may be larger than the requested
  23185. ** size).
  23186. */
  23187. if( pFile->szChunk>0 ){
  23188. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  23189. }
  23190. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  23191. if( rc ){
  23192. pFile->lastErrno = errno;
  23193. return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  23194. }else{
  23195. #ifdef SQLITE_DEBUG
  23196. /* If we are doing a normal write to a database file (as opposed to
  23197. ** doing a hot-journal rollback or a write to some file other than a
  23198. ** normal database file) and we truncate the file to zero length,
  23199. ** that effectively updates the change counter. This might happen
  23200. ** when restoring a database using the backup API from a zero-length
  23201. ** source.
  23202. */
  23203. if( pFile->inNormalWrite && nByte==0 ){
  23204. pFile->transCntrChng = 1;
  23205. }
  23206. #endif
  23207. return SQLITE_OK;
  23208. }
  23209. }
  23210. /*
  23211. ** Determine the current size of a file in bytes
  23212. */
  23213. static int rtthreadFileSize(sqlite3_file *id, i64 *pSize){
  23214. int rc;
  23215. struct stat buf;
  23216. assert( id );
  23217. rc = osFstat(((rtthreadFile*)id)->h, &buf);
  23218. SimulateIOError( rc=1 );
  23219. if( rc!=0 ){
  23220. ((rtthreadFile*)id)->lastErrno = errno;
  23221. return SQLITE_IOERR_FSTAT;
  23222. }
  23223. *pSize = buf.st_size;
  23224. /* When opening a zero-size database, the findInodeInfo() procedure
  23225. ** writes a single byte into that file in order to work around a bug
  23226. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  23227. ** layers, we need to report this file size as zero even though it is
  23228. ** really 1. Ticket #3260.
  23229. */
  23230. if( *pSize==1 ) *pSize = 0;
  23231. return SQLITE_OK;
  23232. }
  23233. /*
  23234. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  23235. ** file-control operation. Enlarge the database to nBytes in size
  23236. ** (rounded up to the next chunk-size). If the database is already
  23237. ** nBytes or larger, this routine is a no-op.
  23238. */
  23239. static int fcntlSizeHint(rtthreadFile *pFile, i64 nByte){
  23240. if( pFile->szChunk>0 ){
  23241. i64 nSize; /* Required file size */
  23242. struct stat buf; /* Used to hold return values of fstat() */
  23243. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  23244. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  23245. if( nSize>(i64)buf.st_size ){
  23246. /* If the OS does not have posix_fallocate(), fake it. First use
  23247. ** ftruncate() to set the file size, then write a single byte to
  23248. ** the last byte in each block within the extended region. This
  23249. ** is the same technique used by glibc to implement posix_fallocate()
  23250. ** on systems that do not have a real fallocate() system call.
  23251. */
  23252. int nBlk = buf.st_blksize; /* File-system block size */
  23253. i64 iWrite; /* Next offset to write to */
  23254. if( robust_ftruncate(pFile->h, nSize) ){
  23255. pFile->lastErrno = errno;
  23256. return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  23257. }
  23258. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  23259. while( iWrite<nSize ){
  23260. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  23261. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  23262. iWrite += nBlk;
  23263. }
  23264. }
  23265. }
  23266. return SQLITE_OK;
  23267. }
  23268. /*
  23269. ** If *pArg is inititially negative then this is a query. Set *pArg to
  23270. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  23271. **
  23272. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  23273. */
  23274. static void rtthreadModeBit(rtthreadFile *pFile, unsigned char mask, int *pArg){
  23275. if( *pArg<0 ){
  23276. *pArg = (pFile->ctrlFlags & mask)!=0;
  23277. }else if( (*pArg)==0 ){
  23278. pFile->ctrlFlags &= ~mask;
  23279. }else{
  23280. pFile->ctrlFlags |= mask;
  23281. }
  23282. }
  23283. /* Forward declaration */
  23284. static int rtthreadGetTempname(int nBuf, char *zBuf);
  23285. /*
  23286. ** Information and control of an open file handle.
  23287. */
  23288. static int rtthreadFileControl(sqlite3_file *id, int op, void *pArg){
  23289. rtthreadFile *pFile = (rtthreadFile*)id;
  23290. switch( op ){
  23291. case SQLITE_FCNTL_LOCKSTATE: {
  23292. *(int*)pArg = pFile->eFileLock;
  23293. return SQLITE_OK;
  23294. }
  23295. case SQLITE_LAST_ERRNO: {
  23296. *(int*)pArg = pFile->lastErrno;
  23297. return SQLITE_OK;
  23298. }
  23299. case SQLITE_FCNTL_CHUNK_SIZE: {
  23300. pFile->szChunk = *(int *)pArg;
  23301. return SQLITE_OK;
  23302. }
  23303. case SQLITE_FCNTL_SIZE_HINT: {
  23304. int rc;
  23305. SimulateIOErrorBenign(1);
  23306. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  23307. SimulateIOErrorBenign(0);
  23308. return rc;
  23309. }
  23310. case SQLITE_FCNTL_PERSIST_WAL: {
  23311. rtthreadModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  23312. return SQLITE_OK;
  23313. }
  23314. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  23315. rtthreadModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  23316. return SQLITE_OK;
  23317. }
  23318. case SQLITE_FCNTL_VFSNAME: {
  23319. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  23320. return SQLITE_OK;
  23321. }
  23322. case SQLITE_FCNTL_TEMPFILENAME: {
  23323. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  23324. if( zTFile ){
  23325. rtthreadGetTempname(pFile->pVfs->mxPathname, zTFile);
  23326. *(char**)pArg = zTFile;
  23327. }
  23328. return SQLITE_OK;
  23329. }
  23330. #ifdef SQLITE_DEBUG
  23331. /* The pager calls this method to signal that it has done
  23332. ** a rollback and that the database is therefore unchanged and
  23333. ** it hence it is OK for the transaction change counter to be
  23334. ** unchanged.
  23335. */
  23336. case SQLITE_FCNTL_DB_UNCHANGED: {
  23337. ((rtthreadFile*)id)->dbUpdate = 0;
  23338. return SQLITE_OK;
  23339. }
  23340. #endif
  23341. }
  23342. return SQLITE_NOTFOUND;
  23343. }
  23344. /*
  23345. ** Return the sector size in bytes of the underlying block device for
  23346. ** the specified file. This is almost always 512 bytes, but may be
  23347. ** larger for some devices.
  23348. **
  23349. ** SQLite code assumes this function cannot fail. It also assumes that
  23350. ** if two files are created in the same file-system directory (i.e.
  23351. ** a database and its journal file) that the sector size will be the
  23352. ** same for both.
  23353. */
  23354. static int rtthreadSectorSize(sqlite3_file *NotUsed){
  23355. UNUSED_PARAMETER(NotUsed);
  23356. return SQLITE_DEFAULT_SECTOR_SIZE;
  23357. }
  23358. /*
  23359. ** Return the device characteristics for the file.
  23360. **
  23361. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  23362. ** However, that choice is contraversial since technically the underlying
  23363. ** file system does not always provide powersafe overwrites. (In other
  23364. ** words, after a power-loss event, parts of the file that were never
  23365. ** written might end up being altered.) However, non-PSOW behavior is very,
  23366. ** very rare. And asserting PSOW makes a large reduction in the amount
  23367. ** of required I/O for journaling, since a lot of padding is eliminated.
  23368. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  23369. ** available to turn it off and URI query parameter available to turn it off.
  23370. */
  23371. static int rtthreadDeviceCharacteristics(sqlite3_file *id){
  23372. rtthreadFile *p = (rtthreadFile*)id;
  23373. int rc = 0;
  23374. if( p->ctrlFlags & UNIXFILE_PSOW ){
  23375. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  23376. }
  23377. return rc;
  23378. }
  23379. #ifndef SQLITE_OMIT_WAL
  23380. # error "WAL mode requires not support from the rt-thread, compile\
  23381. with SQLITE_OMIT_WAL."
  23382. #else
  23383. # define rtthreadShmMap 0
  23384. # define rtthreadShmLock 0
  23385. # define rtthreadShmBarrier 0
  23386. # define rtthreadShmUnmap 0
  23387. #endif /* #ifndef SQLITE_OMIT_WAL */
  23388. #if SQLITE_MAX_MMAP_SIZE>0
  23389. #error "rtthread not spportt mmap"
  23390. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  23391. /*
  23392. ** If possible, return a pointer to a mapping of file fd starting at offset
  23393. ** iOff. The mapping must be valid for at least nAmt bytes.
  23394. **
  23395. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  23396. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  23397. ** Finally, if an error does occur, return an SQLite error code. The final
  23398. ** value of *pp is undefined in this case.
  23399. **
  23400. ** If this function does return a pointer, the caller must eventually
  23401. ** release the reference by calling unixUnfetch().
  23402. */
  23403. static int rtthreadFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  23404. *pp = 0;
  23405. return SQLITE_OK;
  23406. }
  23407. /*
  23408. ** If the third argument is non-NULL, then this function releases a
  23409. ** reference obtained by an earlier call to unixFetch(). The second
  23410. ** argument passed to this function must be the same as the corresponding
  23411. ** argument that was passed to the unixFetch() invocation.
  23412. **
  23413. ** Or, if the third argument is NULL, then this function is being called
  23414. ** to inform the VFS layer that, according to POSIX, any existing mapping
  23415. ** may now be invalid and should be unmapped.
  23416. */
  23417. static int rtthreadUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  23418. rtthreadFile *pFd = (rtthreadFile *)fd; /* The underlying database file */
  23419. UNUSED_PARAMETER(iOff);
  23420. return SQLITE_OK;
  23421. }
  23422. /*
  23423. ** Here ends the implementation of all sqlite3_file methods.
  23424. **
  23425. ********************** End sqlite3_file Methods *******************************
  23426. ******************************************************************************/
  23427. /*
  23428. ** This division contains definitions of sqlite3_io_methods objects that
  23429. ** implement various file locking strategies. It also contains definitions
  23430. ** of "finder" functions. A finder-function is used to locate the appropriate
  23431. ** sqlite3_io_methods object for a particular database file. The pAppData
  23432. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  23433. ** the correct finder-function for that VFS.
  23434. **
  23435. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  23436. ** object. The only interesting finder-function is autolockIoFinder, which
  23437. ** looks at the filesystem type and tries to guess the best locking
  23438. ** strategy from that.
  23439. **
  23440. ** For finder-funtion F, two objects are created:
  23441. **
  23442. ** (1) The real finder-function named "FImpt()".
  23443. **
  23444. ** (2) A constant pointer to this function named just "F".
  23445. **
  23446. **
  23447. ** A pointer to the F pointer is used as the pAppData value for VFS
  23448. ** objects. We have to do this instead of letting pAppData point
  23449. ** directly at the finder-function since C90 rules prevent a void*
  23450. ** from be cast into a function pointer.
  23451. **
  23452. **
  23453. ** Each instance of this macro generates two objects:
  23454. **
  23455. ** * A constant sqlite3_io_methods object call METHOD that has locking
  23456. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  23457. **
  23458. ** * An I/O method finder function called FINDER that returns a pointer
  23459. ** to the METHOD object in the previous bullet.
  23460. */
  23461. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  23462. static const sqlite3_io_methods METHOD = { \
  23463. VERSION, /* iVersion */ \
  23464. CLOSE, /* xClose */ \
  23465. rtthreadRead, /* xRead */ \
  23466. rtthreadWrite, /* xWrite */ \
  23467. rtthreadTruncate, /* xTruncate */ \
  23468. rtthreadSync, /* xSync */ \
  23469. rtthreadFileSize, /* xFileSize */ \
  23470. LOCK, /* xLock */ \
  23471. UNLOCK, /* xUnlock */ \
  23472. CKLOCK, /* xCheckReservedLock */ \
  23473. rtthreadFileControl, /* xFileControl */ \
  23474. rtthreadSectorSize, /* xSectorSize */ \
  23475. rtthreadDeviceCharacteristics, /* xDeviceCapabilities */ \
  23476. rtthreadShmMap, /* xShmMap */ \
  23477. rtthreadShmLock, /* xShmLock */ \
  23478. rtthreadShmBarrier, /* xShmBarrier */ \
  23479. rtthreadShmUnmap, /* xShmUnmap */ \
  23480. rtthreadFetch, /* xFetch */ \
  23481. rtthreadUnfetch, /* xUnfetch */ \
  23482. }; \
  23483. static const sqlite3_io_methods *FINDER##Impl(const char *z, rtthreadFile *p){ \
  23484. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  23485. return &METHOD; \
  23486. } \
  23487. static const sqlite3_io_methods *(*const FINDER)(const char*,rtthreadFile *p) \
  23488. = FINDER##Impl;
  23489. /*
  23490. ** Here are all of the sqlite3_io_methods objects for each of the
  23491. ** locking strategies. Functions that return pointers to these methods
  23492. ** are also created.
  23493. */
  23494. IOMETHODS(
  23495. nolockIoFinder, /* Finder function name */
  23496. nolockIoMethods, /* sqlite3_io_methods object name */
  23497. 1, /* shared memory is disabled */
  23498. nolockClose, /* xClose method */
  23499. nolockLock, /* xLock method */
  23500. nolockUnlock, /* xUnlock method */
  23501. nolockCheckReservedLock /* xCheckReservedLock method */
  23502. )
  23503. IOMETHODS(
  23504. dotlockIoFinder, /* Finder function name */
  23505. dotlockIoMethods, /* sqlite3_io_methods object name */
  23506. 1, /* shared memory is disabled */
  23507. dotlockClose, /* xClose method */
  23508. dotlockLock, /* xLock method */
  23509. dotlockUnlock, /* xUnlock method */
  23510. dotlockCheckReservedLock /* xCheckReservedLock method */
  23511. )
  23512. #if SQLITE_ENABLE_LOCKING_STYLE
  23513. IOMETHODS(
  23514. flockIoFinder, /* Finder function name */
  23515. flockIoMethods, /* sqlite3_io_methods object name */
  23516. 1, /* shared memory is disabled */
  23517. flockClose, /* xClose method */
  23518. flockLock, /* xLock method */
  23519. flockUnlock, /* xUnlock method */
  23520. flockCheckReservedLock /* xCheckReservedLock method */
  23521. )
  23522. #endif
  23523. /*
  23524. ** An abstract type for a pointer to a IO method finder function:
  23525. */
  23526. typedef const sqlite3_io_methods *(*finder_type)(const char*,rtthreadFile*);
  23527. /****************************************************************************
  23528. **************************** sqlite3_vfs methods ****************************
  23529. **
  23530. ** This division contains the implementation of methods on the
  23531. ** sqlite3_vfs object.
  23532. */
  23533. /*
  23534. ** Initialize the contents of the rtthreadFile structure pointed to by pId.
  23535. */
  23536. static int fillInRtthreadFile(
  23537. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23538. int h, /* Open file descriptor of file being opened */
  23539. sqlite3_file *pId, /* Write to the rtthreadFile structure here */
  23540. const char *zFilename, /* Name of the file being opened */
  23541. int ctrlFlags /* Zero or more UNIXFILE_* values */
  23542. ){
  23543. const sqlite3_io_methods *pLockingStyle;
  23544. rtthreadFile *pNew = (rtthreadFile *)pId;
  23545. int rc = SQLITE_OK;
  23546. assert( pNew->pInode==NULL );
  23547. /* Usually the path zFilename should not be a relative pathname. The
  23548. ** exception is when opening the proxy "conch" file in builds that
  23549. ** include the special Apple locking styles.
  23550. */
  23551. assert( zFilename==0 || zFilename[0]=='/' );
  23552. /* No locking occurs in temporary files */
  23553. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  23554. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  23555. pNew->h = h;
  23556. pNew->pVfs = pVfs;
  23557. pNew->zPath = zFilename;
  23558. pNew->ctrlFlags = (u8)ctrlFlags;
  23559. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  23560. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  23561. pNew->ctrlFlags |= UNIXFILE_PSOW;
  23562. }
  23563. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  23564. pNew->ctrlFlags |= UNIXFILE_EXCL;
  23565. }
  23566. if( ctrlFlags & UNIXFILE_NOLOCK ){
  23567. pLockingStyle = &nolockIoMethods;
  23568. }else{
  23569. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  23570. #if SQLITE_ENABLE_LOCKING_STYLE
  23571. /* Cache zFilename in the locking context (AFP and dotlock override) for
  23572. ** proxyLock activation is possible (remote proxy is based on db name)
  23573. ** zFilename remains valid until file is closed, to support */
  23574. pNew->lockingContext = (void*)zFilename;
  23575. #endif
  23576. }
  23577. if( pLockingStyle == &dotlockIoMethods ){
  23578. /* Dotfile locking uses the file path so it needs to be included in
  23579. ** the dotlockLockingContext
  23580. */
  23581. char *zLockFile;
  23582. int nFilename;
  23583. assert( zFilename!=0 );
  23584. nFilename = (int)strlen(zFilename) + 6;
  23585. zLockFile = (char *)sqlite3_malloc(nFilename);
  23586. if( zLockFile==0 ){
  23587. rc = SQLITE_NOMEM;
  23588. }else{
  23589. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  23590. }
  23591. pNew->lockingContext = zLockFile;
  23592. }
  23593. pNew->lastErrno = 0;
  23594. if( rc!=SQLITE_OK ){
  23595. if( h>=0 ) robust_close(pNew, h, __LINE__);
  23596. }else{
  23597. pNew->pMethod = pLockingStyle;
  23598. OpenCounter(+1);
  23599. verifyDbFile(pNew);
  23600. }
  23601. return rc;
  23602. }
  23603. /*
  23604. ** Return the name of a directory in which to put temporary files.
  23605. ** If no suitable temporary file directory can be found, return NULL.
  23606. */
  23607. static const char* rtthreadTempFileDir(void){
  23608. static const char *azDirs[] = {
  23609. 0,
  23610. "/sql",
  23611. "/sql/tmp"
  23612. "/tmp",
  23613. 0 /* List terminator */
  23614. };
  23615. unsigned int i;
  23616. struct stat buf;
  23617. const char *zDir = 0;
  23618. azDirs[0] = sqlite3_temp_directory;
  23619. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  23620. if( zDir==0 ) continue;
  23621. if( osStat(zDir, &buf) ) continue;
  23622. if( !S_ISDIR(buf.st_mode) ) continue;
  23623. break;
  23624. }
  23625. return zDir;
  23626. }
  23627. /*
  23628. ** Create a temporary file name in zBuf. zBuf must be allocated
  23629. ** by the calling process and must be big enough to hold at least
  23630. ** pVfs->mxPathname bytes.
  23631. */
  23632. static int rtthreadGetTempname(int nBuf, char *zBuf){
  23633. static const unsigned char zChars[] =
  23634. "abcdefghijklmnopqrstuvwxyz"
  23635. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  23636. "0123456789";
  23637. unsigned int i, j;
  23638. const char *zDir;
  23639. /* It's odd to simulate an io-error here, but really this is just
  23640. ** using the io-error infrastructure to test that SQLite handles this
  23641. ** function failing.
  23642. */
  23643. SimulateIOError( return SQLITE_IOERR );
  23644. zDir = rtthreadTempFileDir();
  23645. if( zDir==0 ) zDir = ".";
  23646. /* Check that the output buffer is large enough for the temporary file
  23647. ** name. If it is not, return SQLITE_ERROR.
  23648. */
  23649. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  23650. return SQLITE_ERROR;
  23651. }
  23652. do{
  23653. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  23654. j = (int)strlen(zBuf);
  23655. sqlite3_randomness(15, &zBuf[j]);
  23656. for(i=0; i<15; i++, j++){
  23657. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  23658. }
  23659. zBuf[j] = 0;
  23660. zBuf[j+1] = 0;
  23661. }while( osAccess(zBuf,0)==0 );
  23662. return SQLITE_OK;
  23663. }
  23664. /*
  23665. ** Open the file zPath.
  23666. **
  23667. ** Previously, the SQLite OS layer used three functions in place of this
  23668. ** one:
  23669. **
  23670. ** sqlite3OsOpenReadWrite();
  23671. ** sqlite3OsOpenReadOnly();
  23672. ** sqlite3OsOpenExclusive();
  23673. **
  23674. ** These calls correspond to the following combinations of flags:
  23675. **
  23676. ** ReadWrite() -> (READWRITE | CREATE)
  23677. ** ReadOnly() -> (READONLY)
  23678. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  23679. **
  23680. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  23681. ** true, the file was configured to be automatically deleted when the
  23682. ** file handle closed. To achieve the same effect using this new
  23683. ** interface, add the DELETEONCLOSE flag to those specified above for
  23684. ** OpenExclusive().
  23685. */
  23686. static int rtthreadOpen(
  23687. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  23688. const char *zPath, /* Pathname of file to be opened */
  23689. sqlite3_file *pFile, /* The file descriptor to be filled in */
  23690. int flags, /* Input flags to control the opening */
  23691. int *pOutFlags /* Output flags returned to SQLite core */
  23692. ){
  23693. rtthreadFile *p = (rtthreadFile *)pFile;
  23694. int fd = -1; /* File descriptor returned by open() */
  23695. int openFlags = 0; /* Flags to pass to open() */
  23696. int eType = flags&0xFFFFFF00; /* Type of file to open */
  23697. int noLock; /* True to omit locking primitives */
  23698. int rc = SQLITE_OK; /* Function Return Code */
  23699. int ctrlFlags = 0; /* UNIXFILE_* flags */
  23700. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  23701. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  23702. int isCreate = (flags & SQLITE_OPEN_CREATE);
  23703. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  23704. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  23705. #if SQLITE_ENABLE_LOCKING_STYLE
  23706. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  23707. #endif
  23708. /* If creating a master or main-file journal, this function will open
  23709. ** a file-descriptor on the directory too. The first time unixSync()
  23710. ** is called the directory file descriptor will be fsync()ed and close()d.
  23711. */
  23712. int syncDir = (isCreate && (
  23713. eType==SQLITE_OPEN_MASTER_JOURNAL
  23714. || eType==SQLITE_OPEN_MAIN_JOURNAL
  23715. || eType==SQLITE_OPEN_WAL
  23716. ));
  23717. /* If argument zPath is a NULL pointer, this function is required to open
  23718. ** a temporary file. Use this buffer to store the file name in.
  23719. */
  23720. char zTmpname[MAX_PATHNAME+2];
  23721. const char *zName = zPath;
  23722. /* Check the following statements are true:
  23723. **
  23724. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  23725. ** (b) if CREATE is set, then READWRITE must also be set, and
  23726. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  23727. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  23728. */
  23729. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  23730. assert(isCreate==0 || isReadWrite);
  23731. assert(isExclusive==0 || isCreate);
  23732. assert(isDelete==0 || isCreate);
  23733. /* The main DB, main journal, WAL file and master journal are never
  23734. ** automatically deleted. Nor are they ever temporary files. */
  23735. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  23736. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  23737. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  23738. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  23739. /* Assert that the upper layer has set one of the "file-type" flags. */
  23740. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  23741. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  23742. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  23743. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  23744. );
  23745. memset(p, 0, sizeof(rtthreadFile));
  23746. if( !zName ){
  23747. /* If zName is NULL, the upper layer is requesting a temp file. */
  23748. assert(isDelete && !syncDir);
  23749. rc = rtthreadGetTempname(MAX_PATHNAME+2, zTmpname);
  23750. if( rc!=SQLITE_OK ){
  23751. return rc;
  23752. }
  23753. zName = zTmpname;
  23754. /* Generated temporary filenames are always double-zero terminated
  23755. ** for use by sqlite3_uri_parameter(). */
  23756. assert( zName[strlen(zName)+1]==0 );
  23757. }
  23758. /* Determine the value of the flags parameter passed to POSIX function
  23759. ** open(). These must be calculated even if open() is not called, as
  23760. ** they may be stored as part of the file handle and used by the
  23761. ** 'conch file' locking functions later on. */
  23762. if( isReadonly ) openFlags |= O_RDONLY;
  23763. if( isReadWrite ) openFlags |= O_RDWR;
  23764. if( isCreate ) openFlags |= O_CREAT;
  23765. if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/);
  23766. openFlags |= (0/*O_LARGEFILE*/|O_BINARY);
  23767. if( fd<0 ){
  23768. mode_t openMode = 0; /* Permissions to create file with */
  23769. fd = robust_open(zName, openFlags, openMode);
  23770. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  23771. if( fd<0 && errno!=DFS_STATUS_EISDIR && isReadWrite && !isExclusive ){
  23772. /* Failed to open the file for read/write access. Try read-only. */
  23773. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  23774. openFlags &= ~(O_RDWR|O_CREAT);
  23775. flags |= SQLITE_OPEN_READONLY;
  23776. openFlags |= O_RDONLY;
  23777. isReadonly = 1;
  23778. fd = robust_open(zName, openFlags, openMode);
  23779. }
  23780. if( fd<0 ){
  23781. rc = rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  23782. goto open_finished;
  23783. }
  23784. }
  23785. assert( fd>=0 );
  23786. if( pOutFlags ){
  23787. *pOutFlags = flags;
  23788. }
  23789. if( isDelete ){
  23790. osUnlink(zName);
  23791. }
  23792. #if SQLITE_ENABLE_LOCKING_STYLE
  23793. else{
  23794. p->openFlags = openFlags;
  23795. }
  23796. #endif
  23797. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  23798. /* Set up appropriate ctrlFlags */
  23799. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  23800. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  23801. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  23802. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  23803. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  23804. rc = fillInRtthreadFile(pVfs, fd, pFile, zPath, ctrlFlags);
  23805. open_finished:
  23806. return rc;
  23807. }
  23808. /*
  23809. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  23810. ** the directory after deleting the file.
  23811. */
  23812. static int rtthreadDelete(
  23813. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  23814. const char *zPath, /* Name of file to be deleted */
  23815. int dirSync /* If true, fsync() directory after deleting file */
  23816. ){
  23817. int rc = SQLITE_OK;
  23818. UNUSED_PARAMETER(NotUsed);
  23819. SimulateIOError(return SQLITE_IOERR_DELETE);
  23820. if( osUnlink(zPath)==(-1) ){
  23821. if( errno==DFS_STATUS_ENOENT ){
  23822. rc = SQLITE_IOERR_DELETE_NOENT;
  23823. }else{
  23824. rc = rtthreadLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  23825. }
  23826. return rc;
  23827. }
  23828. #ifndef SQLITE_DISABLE_DIRSYNC
  23829. if( (dirSync & 1)!=0 ){
  23830. int fd;
  23831. rc = osOpenDirectory(zPath, &fd);
  23832. if( rc==SQLITE_OK ){
  23833. robust_close(0, fd, __LINE__);
  23834. }else if( rc==SQLITE_CANTOPEN ){
  23835. rc = SQLITE_OK;
  23836. }
  23837. }
  23838. #endif
  23839. return rc;
  23840. }
  23841. /*
  23842. ** Test the existence of or access permissions of file zPath. The
  23843. ** test performed depends on the value of flags:
  23844. **
  23845. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  23846. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  23847. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  23848. **
  23849. ** Otherwise return 0.
  23850. */
  23851. #ifndef F_OK
  23852. # define F_OK 0
  23853. #endif
  23854. #ifndef R_OK
  23855. # define R_OK 4
  23856. #endif
  23857. #ifndef W_OK
  23858. # define W_OK 2
  23859. #endif
  23860. static int rtthreadAccess(
  23861. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  23862. const char *zPath, /* Path of the file to examine */
  23863. int flags, /* What do we want to learn about the zPath file? */
  23864. int *pResOut /* Write result boolean here */
  23865. ){
  23866. int amode = 0;
  23867. UNUSED_PARAMETER(NotUsed);
  23868. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  23869. switch( flags ){
  23870. case SQLITE_ACCESS_EXISTS:
  23871. amode = F_OK;
  23872. break;
  23873. case SQLITE_ACCESS_READWRITE:
  23874. amode = W_OK|R_OK;
  23875. break;
  23876. case SQLITE_ACCESS_READ:
  23877. amode = R_OK;
  23878. break;
  23879. default:
  23880. assert(!"Invalid flags argument");
  23881. }
  23882. *pResOut = (osAccess(zPath, amode)==0);
  23883. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  23884. struct stat buf;
  23885. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  23886. *pResOut = 0;
  23887. }
  23888. }
  23889. return SQLITE_OK;
  23890. }
  23891. /*
  23892. ** Turn a relative pathname into a full pathname. The relative path
  23893. ** is stored as a nul-terminated string in the buffer pointed to by
  23894. ** zPath.
  23895. **
  23896. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  23897. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  23898. ** this buffer before returning.
  23899. */
  23900. static int rtthreadFullPathname(
  23901. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23902. const char *zPath, /* Possibly relative input path */
  23903. int nOut, /* Size of output buffer in bytes */
  23904. char *zOut /* Output buffer */
  23905. ){
  23906. /* It's odd to simulate an io-error here, but really this is just
  23907. ** using the io-error infrastructure to test that SQLite handles this
  23908. ** function failing. This function could fail if, for example, the
  23909. ** current working directory has been unlinked.
  23910. */
  23911. SimulateIOError( return SQLITE_ERROR );
  23912. assert( pVfs->mxPathname==MAX_PATHNAME );
  23913. UNUSED_PARAMETER(pVfs);
  23914. zOut[nOut-1] = '\0';
  23915. if( zPath[0]=='/' ){
  23916. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  23917. }else{
  23918. int nCwd;
  23919. if( osGetcwd(zOut, nOut-1)==0 ){
  23920. return rtthreadLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  23921. }
  23922. nCwd = (int)strlen(zOut);
  23923. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  23924. }
  23925. return SQLITE_OK;
  23926. }
  23927. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  23928. # error "rtthread not support load extension, compile with SQLITE_OMIT_WAL."
  23929. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  23930. #define rtthreadDlOpen 0
  23931. #define rtthreadDlError 0
  23932. #define rtthreadDlSym 0
  23933. #define rtthreadDlClose 0
  23934. #endif
  23935. /*
  23936. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  23937. */
  23938. static int rtthreadRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  23939. UNUSED_PARAMETER(NotUsed);
  23940. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  23941. /* We have to initialize zBuf to prevent valgrind from reporting
  23942. ** errors. The reports issued by valgrind are incorrect - we would
  23943. ** prefer that the randomness be increased by making use of the
  23944. ** uninitialized space in zBuf - but valgrind errors tend to worry
  23945. ** some users. Rather than argue, it seems easier just to initialize
  23946. ** the whole array and silence valgrind, even if that means less randomness
  23947. ** in the random seed.
  23948. **
  23949. ** When testing, initializing zBuf[] to zero is all we do. That means
  23950. ** that we always use the same random number sequence. This makes the
  23951. ** tests repeatable.
  23952. */
  23953. memset(zBuf, 0, nBuf);
  23954. {
  23955. int i;
  23956. char tick8, tick16;
  23957. tick8 = (char)rt_tick_get();
  23958. tick16 = (char)(rt_tick_get() >> 8);
  23959. for (i=0; i<nBuf; i++)
  23960. {
  23961. zBuf[i] = (char)(i ^ tick8 ^ tick16);
  23962. tick8 = zBuf[i];
  23963. tick16 = ~(tick8 ^ tick16);
  23964. }
  23965. }
  23966. return nBuf;
  23967. }
  23968. /*
  23969. ** Sleep for a little while. Return the amount of time slept.
  23970. ** The argument is the number of microseconds we want to sleep.
  23971. ** The return value is the number of microseconds of sleep actually
  23972. ** requested from the underlying operating system, a number which
  23973. ** might be greater than or equal to the argument, but not less
  23974. ** than the argument.
  23975. */
  23976. static int rtthreadSleep(sqlite3_vfs *NotUsed, int microseconds){
  23977. int seconds = (microseconds+999999)/1000000;
  23978. osSleep(seconds * 1000);
  23979. UNUSED_PARAMETER(NotUsed);
  23980. return seconds*1000000;
  23981. }
  23982. /*
  23983. ** The following variable, if set to a non-zero value, is interpreted as
  23984. ** the number of seconds since 1970 and is used to set the result of
  23985. ** sqlite3OsCurrentTime() during testing.
  23986. */
  23987. #ifdef SQLITE_TEST
  23988. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  23989. #endif
  23990. #ifndef NO_GETTOD
  23991. #define NO_GETTOD 1
  23992. #endif
  23993. /*
  23994. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  23995. ** the current time and date as a Julian Day number times 86_400_000. In
  23996. ** other words, write into *piNow the number of milliseconds since the Julian
  23997. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  23998. ** proleptic Gregorian calendar.
  23999. **
  24000. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  24001. ** cannot be found.
  24002. */
  24003. static int rtthreadCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  24004. static const sqlite3_int64 rtthreadEpoch = 24405875*(sqlite3_int64)8640000;
  24005. int rc = SQLITE_OK;
  24006. #if defined(NO_GETTOD)
  24007. time_t t;
  24008. time(&t);
  24009. *piNow = ((sqlite3_int64)t)*1000 + rtthreadEpoch;
  24010. #else
  24011. struct timeval sNow;
  24012. if( gettimeofday(&sNow, 0)==0 ){
  24013. *piNow = rtthreadEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  24014. }else{
  24015. rc = SQLITE_ERROR;
  24016. }
  24017. #endif
  24018. #ifdef SQLITE_TEST
  24019. if( sqlite3_current_time ){
  24020. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + rtthreadEpoch;
  24021. }
  24022. #endif
  24023. UNUSED_PARAMETER(NotUsed);
  24024. return rc;
  24025. }
  24026. /*
  24027. ** Find the current time (in Universal Coordinated Time). Write the
  24028. ** current time and date as a Julian Day number into *prNow and
  24029. ** return 0. Return 1 if the time and date cannot be found.
  24030. */
  24031. static int rtthreadCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  24032. sqlite3_int64 i = 0;
  24033. int rc;
  24034. UNUSED_PARAMETER(NotUsed);
  24035. rc = rtthreadCurrentTimeInt64(0, &i);
  24036. *prNow = i/86400000.0;
  24037. return rc;
  24038. }
  24039. /*
  24040. ** We added the xGetLastError() method with the intention of providing
  24041. ** better low-level error messages when operating-system problems come up
  24042. ** during SQLite operation. But so far, none of that has been implemented
  24043. ** in the core. So this routine is never called. For now, it is merely
  24044. ** a place-holder.
  24045. */
  24046. static int rtthreadGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  24047. UNUSED_PARAMETER(NotUsed);
  24048. UNUSED_PARAMETER(NotUsed2);
  24049. UNUSED_PARAMETER(NotUsed3);
  24050. return 0;
  24051. }
  24052. /*
  24053. ************************ End of sqlite3_vfs methods ***************************
  24054. ******************************************************************************/
  24055. /*
  24056. ** Initialize the operating system interface.
  24057. **
  24058. ** This routine registers all VFS implementations for unix-like operating
  24059. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  24060. ** should be the only routines in this file that are visible from other
  24061. ** files.
  24062. **
  24063. ** This routine is called once during SQLite initialization and by a
  24064. ** single thread. The memory allocation and mutex subsystems have not
  24065. ** necessarily been initialized when this routine is called, and so they
  24066. ** should not be used.
  24067. */
  24068. /*
  24069. ** The following macro defines an initializer for an sqlite3_vfs object.
  24070. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  24071. ** to the "finder" function. (pAppData is a pointer to a pointer because
  24072. ** silly C90 rules prohibit a void* from being cast to a function pointer
  24073. ** and so we have to go through the intermediate pointer to avoid problems
  24074. ** when compiling with -pedantic-errors on GCC.)
  24075. **
  24076. ** The FINDER parameter to this macro is the name of the pointer to the
  24077. ** finder-function. The finder-function returns a pointer to the
  24078. ** sqlite_io_methods object that implements the desired locking
  24079. ** behaviors. See the division above that contains the IOMETHODS
  24080. ** macro for addition information on finder-functions.
  24081. **
  24082. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  24083. ** object. But the "autolockIoFinder" available on MacOSX does a little
  24084. ** more than that; it looks at the filesystem type that hosts the
  24085. ** database file and tries to choose an locking method appropriate for
  24086. ** that filesystem time.
  24087. */
  24088. #define UNIXVFS(VFSNAME, FINDER) { \
  24089. 3, /* iVersion */ \
  24090. sizeof(rtthreadFile), /* szOsFile */ \
  24091. MAX_PATHNAME, /* mxPathname */ \
  24092. 0, /* pNext */ \
  24093. VFSNAME, /* zName */ \
  24094. (void*)&FINDER, /* pAppData */ \
  24095. rtthreadOpen, /* xOpen */ \
  24096. rtthreadDelete, /* xDelete */ \
  24097. rtthreadAccess, /* xAccess */ \
  24098. rtthreadFullPathname, /* xFullPathname */ \
  24099. rtthreadDlOpen, /* xDlOpen */ \
  24100. rtthreadDlError, /* xDlError */ \
  24101. rtthreadDlSym, /* xDlSym */ \
  24102. rtthreadDlClose, /* xDlClose */ \
  24103. rtthreadRandomness, /* xRandomness */ \
  24104. rtthreadSleep, /* xSleep */ \
  24105. rtthreadCurrentTime, /* xCurrentTime */ \
  24106. rtthreadGetLastError, /* xGetLastError */ \
  24107. rtthreadCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  24108. rtthreadSetSystemCall, /* xSetSystemCall */ \
  24109. rtthreadGetSystemCall, /* xGetSystemCall */ \
  24110. rtthreadNextSystemCall, /* xNextSystemCall */ \
  24111. }
  24112. SQLITE_API int sqlite3_os_init(void){
  24113. /*
  24114. ** All default VFSes for unix are contained in the following array.
  24115. **
  24116. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  24117. ** by the SQLite core when the VFS is registered. So the following
  24118. ** array cannot be const.
  24119. */
  24120. static sqlite3_vfs aVfs[] = {
  24121. UNIXVFS("unix-none", nolockIoFinder ),
  24122. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  24123. #if SQLITE_ENABLE_LOCKING_STYLE
  24124. UNIXVFS("unix-flock", flockIoFinder ),
  24125. #endif
  24126. };
  24127. unsigned int i; /* Loop counter */
  24128. /* Double-check that the aSyscall[] array has been constructed
  24129. ** correctly. See ticket [bb3a86e890c8e96ab] */
  24130. assert( ArraySize(aSyscall)==24 );
  24131. /* Register all VFSes defined in the aVfs[] array */
  24132. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  24133. sqlite3_vfs_register(&aVfs[i], i==0);
  24134. }
  24135. return SQLITE_OK;
  24136. }
  24137. /*
  24138. ** Shutdown the operating system interface.
  24139. **
  24140. ** Some operating systems might need to do some cleanup in this routine,
  24141. ** to release dynamically allocated objects. But not on unix.
  24142. ** This routine is a no-op for unix.
  24143. */
  24144. SQLITE_API int sqlite3_os_end(void){
  24145. return SQLITE_OK;
  24146. }
  24147. #endif /* SQLITE_OS_RTTHREAD */
  24148. /************** End of os_rtthread.c *****************************************/
  24149. /************** Begin file bitvec.c ******************************************/
  24150. /*
  24151. ** 2008 February 16
  24152. **
  24153. ** The author disclaims copyright to this source code. In place of
  24154. ** a legal notice, here is a blessing:
  24155. **
  24156. ** May you do good and not evil.
  24157. ** May you find forgiveness for yourself and forgive others.
  24158. ** May you share freely, never taking more than you give.
  24159. **
  24160. *************************************************************************
  24161. ** This file implements an object that represents a fixed-length
  24162. ** bitmap. Bits are numbered starting with 1.
  24163. **
  24164. ** A bitmap is used to record which pages of a database file have been
  24165. ** journalled during a transaction, or which pages have the "dont-write"
  24166. ** property. Usually only a few pages are meet either condition.
  24167. ** So the bitmap is usually sparse and has low cardinality.
  24168. ** But sometimes (for example when during a DROP of a large table) most
  24169. ** or all of the pages in a database can get journalled. In those cases,
  24170. ** the bitmap becomes dense with high cardinality. The algorithm needs
  24171. ** to handle both cases well.
  24172. **
  24173. ** The size of the bitmap is fixed when the object is created.
  24174. **
  24175. ** All bits are clear when the bitmap is created. Individual bits
  24176. ** may be set or cleared one at a time.
  24177. **
  24178. ** Test operations are about 100 times more common that set operations.
  24179. ** Clear operations are exceedingly rare. There are usually between
  24180. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  24181. ** sometimes grow into tens of thousands or larger. The size of the
  24182. ** Bitvec object is the number of pages in the database file at the
  24183. ** start of a transaction, and is thus usually less than a few thousand,
  24184. ** but can be as large as 2 billion for a really big database.
  24185. */
  24186. /* Size of the Bitvec structure in bytes. */
  24187. #define BITVEC_SZ 512
  24188. /* Round the union size down to the nearest pointer boundary, since that's how
  24189. ** it will be aligned within the Bitvec struct. */
  24190. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  24191. /* Type of the array "element" for the bitmap representation.
  24192. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  24193. ** Setting this to the "natural word" size of your CPU may improve
  24194. ** performance. */
  24195. #define BITVEC_TELEM u8
  24196. /* Size, in bits, of the bitmap element. */
  24197. #define BITVEC_SZELEM 8
  24198. /* Number of elements in a bitmap array. */
  24199. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  24200. /* Number of bits in the bitmap array. */
  24201. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  24202. /* Number of u32 values in hash table. */
  24203. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  24204. /* Maximum number of entries in hash table before
  24205. ** sub-dividing and re-hashing. */
  24206. #define BITVEC_MXHASH (BITVEC_NINT/2)
  24207. /* Hashing function for the aHash representation.
  24208. ** Empirical testing showed that the *37 multiplier
  24209. ** (an arbitrary prime)in the hash function provided
  24210. ** no fewer collisions than the no-op *1. */
  24211. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  24212. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  24213. /*
  24214. ** A bitmap is an instance of the following structure.
  24215. **
  24216. ** This bitmap records the existence of zero or more bits
  24217. ** with values between 1 and iSize, inclusive.
  24218. **
  24219. ** There are three possible representations of the bitmap.
  24220. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  24221. ** bitmap. The least significant bit is bit 1.
  24222. **
  24223. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  24224. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  24225. **
  24226. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  24227. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  24228. ** handles up to iDivisor separate values of i. apSub[0] holds
  24229. ** values between 1 and iDivisor. apSub[1] holds values between
  24230. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  24231. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  24232. ** to hold deal with values between 1 and iDivisor.
  24233. */
  24234. struct Bitvec {
  24235. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  24236. u32 nSet; /* Number of bits that are set - only valid for aHash
  24237. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  24238. ** this would be 125. */
  24239. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  24240. /* Should >=0 for apSub element. */
  24241. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  24242. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  24243. union {
  24244. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  24245. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  24246. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  24247. } u;
  24248. };
  24249. /*
  24250. ** Create a new bitmap object able to handle bits between 0 and iSize,
  24251. ** inclusive. Return a pointer to the new object. Return NULL if
  24252. ** malloc fails.
  24253. */
  24254. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  24255. Bitvec *p;
  24256. assert( sizeof(*p)==BITVEC_SZ );
  24257. p = sqlite3MallocZero( sizeof(*p) );
  24258. if( p ){
  24259. p->iSize = iSize;
  24260. }
  24261. return p;
  24262. }
  24263. /*
  24264. ** Check to see if the i-th bit is set. Return true or false.
  24265. ** If p is NULL (if the bitmap has not been created) or if
  24266. ** i is out of range, then return false.
  24267. */
  24268. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  24269. if( p==0 ) return 0;
  24270. if( i>p->iSize || i==0 ) return 0;
  24271. i--;
  24272. while( p->iDivisor ){
  24273. u32 bin = i/p->iDivisor;
  24274. i = i%p->iDivisor;
  24275. p = p->u.apSub[bin];
  24276. if (!p) {
  24277. return 0;
  24278. }
  24279. }
  24280. if( p->iSize<=BITVEC_NBIT ){
  24281. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  24282. } else{
  24283. u32 h = BITVEC_HASH(i++);
  24284. while( p->u.aHash[h] ){
  24285. if( p->u.aHash[h]==i ) return 1;
  24286. h = (h+1) % BITVEC_NINT;
  24287. }
  24288. return 0;
  24289. }
  24290. }
  24291. /*
  24292. ** Set the i-th bit. Return 0 on success and an error code if
  24293. ** anything goes wrong.
  24294. **
  24295. ** This routine might cause sub-bitmaps to be allocated. Failing
  24296. ** to get the memory needed to hold the sub-bitmap is the only
  24297. ** that can go wrong with an insert, assuming p and i are valid.
  24298. **
  24299. ** The calling function must ensure that p is a valid Bitvec object
  24300. ** and that the value for "i" is within range of the Bitvec object.
  24301. ** Otherwise the behavior is undefined.
  24302. */
  24303. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  24304. u32 h;
  24305. if( p==0 ) return SQLITE_OK;
  24306. assert( i>0 );
  24307. assert( i<=p->iSize );
  24308. i--;
  24309. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  24310. u32 bin = i/p->iDivisor;
  24311. i = i%p->iDivisor;
  24312. if( p->u.apSub[bin]==0 ){
  24313. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  24314. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  24315. }
  24316. p = p->u.apSub[bin];
  24317. }
  24318. if( p->iSize<=BITVEC_NBIT ){
  24319. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  24320. return SQLITE_OK;
  24321. }
  24322. h = BITVEC_HASH(i++);
  24323. /* if there wasn't a hash collision, and this doesn't */
  24324. /* completely fill the hash, then just add it without */
  24325. /* worring about sub-dividing and re-hashing. */
  24326. if( !p->u.aHash[h] ){
  24327. if (p->nSet<(BITVEC_NINT-1)) {
  24328. goto bitvec_set_end;
  24329. } else {
  24330. goto bitvec_set_rehash;
  24331. }
  24332. }
  24333. /* there was a collision, check to see if it's already */
  24334. /* in hash, if not, try to find a spot for it */
  24335. do {
  24336. if( p->u.aHash[h]==i ) return SQLITE_OK;
  24337. h++;
  24338. if( h>=BITVEC_NINT ) h = 0;
  24339. } while( p->u.aHash[h] );
  24340. /* we didn't find it in the hash. h points to the first */
  24341. /* available free spot. check to see if this is going to */
  24342. /* make our hash too "full". */
  24343. bitvec_set_rehash:
  24344. if( p->nSet>=BITVEC_MXHASH ){
  24345. unsigned int j;
  24346. int rc;
  24347. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  24348. if( aiValues==0 ){
  24349. return SQLITE_NOMEM;
  24350. }else{
  24351. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  24352. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  24353. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  24354. rc = sqlite3BitvecSet(p, i);
  24355. for(j=0; j<BITVEC_NINT; j++){
  24356. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  24357. }
  24358. sqlite3StackFree(0, aiValues);
  24359. return rc;
  24360. }
  24361. }
  24362. bitvec_set_end:
  24363. p->nSet++;
  24364. p->u.aHash[h] = i;
  24365. return SQLITE_OK;
  24366. }
  24367. /*
  24368. ** Clear the i-th bit.
  24369. **
  24370. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  24371. ** that BitvecClear can use to rebuilt its hash table.
  24372. */
  24373. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  24374. if( p==0 ) return;
  24375. assert( i>0 );
  24376. i--;
  24377. while( p->iDivisor ){
  24378. u32 bin = i/p->iDivisor;
  24379. i = i%p->iDivisor;
  24380. p = p->u.apSub[bin];
  24381. if (!p) {
  24382. return;
  24383. }
  24384. }
  24385. if( p->iSize<=BITVEC_NBIT ){
  24386. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  24387. }else{
  24388. unsigned int j;
  24389. u32 *aiValues = pBuf;
  24390. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  24391. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  24392. p->nSet = 0;
  24393. for(j=0; j<BITVEC_NINT; j++){
  24394. if( aiValues[j] && aiValues[j]!=(i+1) ){
  24395. u32 h = BITVEC_HASH(aiValues[j]-1);
  24396. p->nSet++;
  24397. while( p->u.aHash[h] ){
  24398. h++;
  24399. if( h>=BITVEC_NINT ) h = 0;
  24400. }
  24401. p->u.aHash[h] = aiValues[j];
  24402. }
  24403. }
  24404. }
  24405. }
  24406. /*
  24407. ** Destroy a bitmap object. Reclaim all memory used.
  24408. */
  24409. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  24410. if( p==0 ) return;
  24411. if( p->iDivisor ){
  24412. unsigned int i;
  24413. for(i=0; i<BITVEC_NPTR; i++){
  24414. sqlite3BitvecDestroy(p->u.apSub[i]);
  24415. }
  24416. }
  24417. sqlite3_free(p);
  24418. }
  24419. /*
  24420. ** Return the value of the iSize parameter specified when Bitvec *p
  24421. ** was created.
  24422. */
  24423. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  24424. return p->iSize;
  24425. }
  24426. #ifndef SQLITE_OMIT_BUILTIN_TEST
  24427. /*
  24428. ** Let V[] be an array of unsigned characters sufficient to hold
  24429. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  24430. ** Then the following macros can be used to set, clear, or test
  24431. ** individual bits within V.
  24432. */
  24433. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  24434. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  24435. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  24436. /*
  24437. ** This routine runs an extensive test of the Bitvec code.
  24438. **
  24439. ** The input is an array of integers that acts as a program
  24440. ** to test the Bitvec. The integers are opcodes followed
  24441. ** by 0, 1, or 3 operands, depending on the opcode. Another
  24442. ** opcode follows immediately after the last operand.
  24443. **
  24444. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  24445. ** "halt" opcode and causes the test to end.
  24446. **
  24447. ** 0 Halt and return the number of errors
  24448. ** 1 N S X Set N bits beginning with S and incrementing by X
  24449. ** 2 N S X Clear N bits beginning with S and incrementing by X
  24450. ** 3 N Set N randomly chosen bits
  24451. ** 4 N Clear N randomly chosen bits
  24452. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  24453. **
  24454. ** The opcodes 1 through 4 perform set and clear operations are performed
  24455. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  24456. ** Opcode 5 works on the linear array only, not on the Bitvec.
  24457. ** Opcode 5 is used to deliberately induce a fault in order to
  24458. ** confirm that error detection works.
  24459. **
  24460. ** At the conclusion of the test the linear array is compared
  24461. ** against the Bitvec object. If there are any differences,
  24462. ** an error is returned. If they are the same, zero is returned.
  24463. **
  24464. ** If a memory allocation error occurs, return -1.
  24465. */
  24466. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  24467. Bitvec *pBitvec = 0;
  24468. unsigned char *pV = 0;
  24469. int rc = -1;
  24470. int i, nx, pc, op;
  24471. void *pTmpSpace;
  24472. /* Allocate the Bitvec to be tested and a linear array of
  24473. ** bits to act as the reference */
  24474. pBitvec = sqlite3BitvecCreate( sz );
  24475. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  24476. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  24477. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  24478. /* NULL pBitvec tests */
  24479. sqlite3BitvecSet(0, 1);
  24480. sqlite3BitvecClear(0, 1, pTmpSpace);
  24481. /* Run the program */
  24482. pc = 0;
  24483. while( (op = aOp[pc])!=0 ){
  24484. switch( op ){
  24485. case 1:
  24486. case 2:
  24487. case 5: {
  24488. nx = 4;
  24489. i = aOp[pc+2] - 1;
  24490. aOp[pc+2] += aOp[pc+3];
  24491. break;
  24492. }
  24493. case 3:
  24494. case 4:
  24495. default: {
  24496. nx = 2;
  24497. sqlite3_randomness(sizeof(i), &i);
  24498. break;
  24499. }
  24500. }
  24501. if( (--aOp[pc+1]) > 0 ) nx = 0;
  24502. pc += nx;
  24503. i = (i & 0x7fffffff)%sz;
  24504. if( (op & 1)!=0 ){
  24505. SETBIT(pV, (i+1));
  24506. if( op!=5 ){
  24507. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  24508. }
  24509. }else{
  24510. CLEARBIT(pV, (i+1));
  24511. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  24512. }
  24513. }
  24514. /* Test to make sure the linear array exactly matches the
  24515. ** Bitvec object. Start with the assumption that they do
  24516. ** match (rc==0). Change rc to non-zero if a discrepancy
  24517. ** is found.
  24518. */
  24519. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  24520. + sqlite3BitvecTest(pBitvec, 0)
  24521. + (sqlite3BitvecSize(pBitvec) - sz);
  24522. for(i=1; i<=sz; i++){
  24523. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  24524. rc = i;
  24525. break;
  24526. }
  24527. }
  24528. /* Free allocated structure */
  24529. bitvec_end:
  24530. sqlite3_free(pTmpSpace);
  24531. sqlite3_free(pV);
  24532. sqlite3BitvecDestroy(pBitvec);
  24533. return rc;
  24534. }
  24535. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  24536. /************** End of bitvec.c **********************************************/
  24537. /************** Begin file pcache.c ******************************************/
  24538. /*
  24539. ** 2008 August 05
  24540. **
  24541. ** The author disclaims copyright to this source code. In place of
  24542. ** a legal notice, here is a blessing:
  24543. **
  24544. ** May you do good and not evil.
  24545. ** May you find forgiveness for yourself and forgive others.
  24546. ** May you share freely, never taking more than you give.
  24547. **
  24548. *************************************************************************
  24549. ** This file implements that page cache.
  24550. */
  24551. /*
  24552. ** A complete page cache is an instance of this structure.
  24553. */
  24554. struct PCache {
  24555. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  24556. PgHdr *pSynced; /* Last synced page in dirty page list */
  24557. int nRef; /* Number of referenced pages */
  24558. int szCache; /* Configured cache size */
  24559. int szPage; /* Size of every page in this cache */
  24560. int szExtra; /* Size of extra space for each page */
  24561. int bPurgeable; /* True if pages are on backing store */
  24562. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  24563. void *pStress; /* Argument to xStress */
  24564. sqlite3_pcache *pCache; /* Pluggable cache module */
  24565. PgHdr *pPage1; /* Reference to page 1 */
  24566. };
  24567. /*
  24568. ** Some of the assert() macros in this code are too expensive to run
  24569. ** even during normal debugging. Use them only rarely on long-running
  24570. ** tests. Enable the expensive asserts using the
  24571. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  24572. */
  24573. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  24574. # define expensive_assert(X) assert(X)
  24575. #else
  24576. # define expensive_assert(X)
  24577. #endif
  24578. /********************************** Linked List Management ********************/
  24579. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  24580. /*
  24581. ** Check that the pCache->pSynced variable is set correctly. If it
  24582. ** is not, either fail an assert or return zero. Otherwise, return
  24583. ** non-zero. This is only used in debugging builds, as follows:
  24584. **
  24585. ** expensive_assert( pcacheCheckSynced(pCache) );
  24586. */
  24587. static int pcacheCheckSynced(PCache *pCache){
  24588. PgHdr *p;
  24589. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  24590. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  24591. }
  24592. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  24593. }
  24594. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  24595. /*
  24596. ** Remove page pPage from the list of dirty pages.
  24597. */
  24598. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  24599. PCache *p = pPage->pCache;
  24600. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  24601. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  24602. /* Update the PCache1.pSynced variable if necessary. */
  24603. if( p->pSynced==pPage ){
  24604. PgHdr *pSynced = pPage->pDirtyPrev;
  24605. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  24606. pSynced = pSynced->pDirtyPrev;
  24607. }
  24608. p->pSynced = pSynced;
  24609. }
  24610. if( pPage->pDirtyNext ){
  24611. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  24612. }else{
  24613. assert( pPage==p->pDirtyTail );
  24614. p->pDirtyTail = pPage->pDirtyPrev;
  24615. }
  24616. if( pPage->pDirtyPrev ){
  24617. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  24618. }else{
  24619. assert( pPage==p->pDirty );
  24620. p->pDirty = pPage->pDirtyNext;
  24621. }
  24622. pPage->pDirtyNext = 0;
  24623. pPage->pDirtyPrev = 0;
  24624. expensive_assert( pcacheCheckSynced(p) );
  24625. }
  24626. /*
  24627. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  24628. ** pPage).
  24629. */
  24630. static void pcacheAddToDirtyList(PgHdr *pPage){
  24631. PCache *p = pPage->pCache;
  24632. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  24633. pPage->pDirtyNext = p->pDirty;
  24634. if( pPage->pDirtyNext ){
  24635. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  24636. pPage->pDirtyNext->pDirtyPrev = pPage;
  24637. }
  24638. p->pDirty = pPage;
  24639. if( !p->pDirtyTail ){
  24640. p->pDirtyTail = pPage;
  24641. }
  24642. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  24643. p->pSynced = pPage;
  24644. }
  24645. expensive_assert( pcacheCheckSynced(p) );
  24646. }
  24647. /*
  24648. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  24649. ** being used for an in-memory database, this function is a no-op.
  24650. */
  24651. static void pcacheUnpin(PgHdr *p){
  24652. PCache *pCache = p->pCache;
  24653. if( pCache->bPurgeable ){
  24654. if( p->pgno==1 ){
  24655. pCache->pPage1 = 0;
  24656. }
  24657. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  24658. }
  24659. }
  24660. /*************************************************** General Interfaces ******
  24661. **
  24662. ** Initialize and shutdown the page cache subsystem. Neither of these
  24663. ** functions are threadsafe.
  24664. */
  24665. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  24666. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  24667. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  24668. ** built-in default page cache is used instead of the application defined
  24669. ** page cache. */
  24670. sqlite3PCacheSetDefault();
  24671. }
  24672. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  24673. }
  24674. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  24675. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  24676. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  24677. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  24678. }
  24679. }
  24680. /*
  24681. ** Return the size in bytes of a PCache object.
  24682. */
  24683. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  24684. /*
  24685. ** Create a new PCache object. Storage space to hold the object
  24686. ** has already been allocated and is passed in as the p pointer.
  24687. ** The caller discovers how much space needs to be allocated by
  24688. ** calling sqlite3PcacheSize().
  24689. */
  24690. SQLITE_PRIVATE void sqlite3PcacheOpen(
  24691. int szPage, /* Size of every page */
  24692. int szExtra, /* Extra space associated with each page */
  24693. int bPurgeable, /* True if pages are on backing store */
  24694. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  24695. void *pStress, /* Argument to xStress */
  24696. PCache *p /* Preallocated space for the PCache */
  24697. ){
  24698. memset(p, 0, sizeof(PCache));
  24699. p->szPage = szPage;
  24700. p->szExtra = szExtra;
  24701. p->bPurgeable = bPurgeable;
  24702. p->xStress = xStress;
  24703. p->pStress = pStress;
  24704. p->szCache = 100;
  24705. }
  24706. /*
  24707. ** Change the page size for PCache object. The caller must ensure that there
  24708. ** are no outstanding page references when this function is called.
  24709. */
  24710. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  24711. assert( pCache->nRef==0 && pCache->pDirty==0 );
  24712. if( pCache->pCache ){
  24713. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  24714. pCache->pCache = 0;
  24715. pCache->pPage1 = 0;
  24716. }
  24717. pCache->szPage = szPage;
  24718. }
  24719. /*
  24720. ** Compute the number of pages of cache requested.
  24721. */
  24722. static int numberOfCachePages(PCache *p){
  24723. if( p->szCache>=0 ){
  24724. return p->szCache;
  24725. }else{
  24726. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  24727. }
  24728. }
  24729. /*
  24730. ** Try to obtain a page from the cache.
  24731. */
  24732. SQLITE_PRIVATE int sqlite3PcacheFetch(
  24733. PCache *pCache, /* Obtain the page from this cache */
  24734. Pgno pgno, /* Page number to obtain */
  24735. int createFlag, /* If true, create page if it does not exist already */
  24736. PgHdr **ppPage /* Write the page here */
  24737. ){
  24738. sqlite3_pcache_page *pPage = 0;
  24739. PgHdr *pPgHdr = 0;
  24740. int eCreate;
  24741. assert( pCache!=0 );
  24742. assert( createFlag==1 || createFlag==0 );
  24743. assert( pgno>0 );
  24744. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  24745. ** allocate it now.
  24746. */
  24747. if( !pCache->pCache && createFlag ){
  24748. sqlite3_pcache *p;
  24749. p = sqlite3GlobalConfig.pcache2.xCreate(
  24750. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  24751. );
  24752. if( !p ){
  24753. return SQLITE_NOMEM;
  24754. }
  24755. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  24756. pCache->pCache = p;
  24757. }
  24758. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  24759. if( pCache->pCache ){
  24760. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  24761. }
  24762. if( !pPage && eCreate==1 ){
  24763. PgHdr *pPg;
  24764. /* Find a dirty page to write-out and recycle. First try to find a
  24765. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  24766. ** cleared), but if that is not possible settle for any other
  24767. ** unreferenced dirty page.
  24768. */
  24769. expensive_assert( pcacheCheckSynced(pCache) );
  24770. for(pPg=pCache->pSynced;
  24771. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  24772. pPg=pPg->pDirtyPrev
  24773. );
  24774. pCache->pSynced = pPg;
  24775. if( !pPg ){
  24776. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  24777. }
  24778. if( pPg ){
  24779. int rc;
  24780. #ifdef SQLITE_LOG_CACHE_SPILL
  24781. sqlite3_log(SQLITE_FULL,
  24782. "spill page %d making room for %d - cache used: %d/%d",
  24783. pPg->pgno, pgno,
  24784. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  24785. numberOfCachePages(pCache));
  24786. #endif
  24787. rc = pCache->xStress(pCache->pStress, pPg);
  24788. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  24789. return rc;
  24790. }
  24791. }
  24792. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  24793. }
  24794. if( pPage ){
  24795. pPgHdr = (PgHdr *)pPage->pExtra;
  24796. if( !pPgHdr->pPage ){
  24797. memset(pPgHdr, 0, sizeof(PgHdr));
  24798. pPgHdr->pPage = pPage;
  24799. pPgHdr->pData = pPage->pBuf;
  24800. pPgHdr->pExtra = (void *)&pPgHdr[1];
  24801. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  24802. pPgHdr->pCache = pCache;
  24803. pPgHdr->pgno = pgno;
  24804. }
  24805. assert( pPgHdr->pCache==pCache );
  24806. assert( pPgHdr->pgno==pgno );
  24807. assert( pPgHdr->pData==pPage->pBuf );
  24808. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  24809. if( 0==pPgHdr->nRef ){
  24810. pCache->nRef++;
  24811. }
  24812. pPgHdr->nRef++;
  24813. if( pgno==1 ){
  24814. pCache->pPage1 = pPgHdr;
  24815. }
  24816. }
  24817. *ppPage = pPgHdr;
  24818. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  24819. }
  24820. /*
  24821. ** Decrement the reference count on a page. If the page is clean and the
  24822. ** reference count drops to 0, then it is made elible for recycling.
  24823. */
  24824. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  24825. assert( p->nRef>0 );
  24826. p->nRef--;
  24827. if( p->nRef==0 ){
  24828. PCache *pCache = p->pCache;
  24829. pCache->nRef--;
  24830. if( (p->flags&PGHDR_DIRTY)==0 ){
  24831. pcacheUnpin(p);
  24832. }else{
  24833. /* Move the page to the head of the dirty list. */
  24834. pcacheRemoveFromDirtyList(p);
  24835. pcacheAddToDirtyList(p);
  24836. }
  24837. }
  24838. }
  24839. /*
  24840. ** Increase the reference count of a supplied page by 1.
  24841. */
  24842. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  24843. assert(p->nRef>0);
  24844. p->nRef++;
  24845. }
  24846. /*
  24847. ** Drop a page from the cache. There must be exactly one reference to the
  24848. ** page. This function deletes that reference, so after it returns the
  24849. ** page pointed to by p is invalid.
  24850. */
  24851. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  24852. PCache *pCache;
  24853. assert( p->nRef==1 );
  24854. if( p->flags&PGHDR_DIRTY ){
  24855. pcacheRemoveFromDirtyList(p);
  24856. }
  24857. pCache = p->pCache;
  24858. pCache->nRef--;
  24859. if( p->pgno==1 ){
  24860. pCache->pPage1 = 0;
  24861. }
  24862. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  24863. }
  24864. /*
  24865. ** Make sure the page is marked as dirty. If it isn't dirty already,
  24866. ** make it so.
  24867. */
  24868. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  24869. p->flags &= ~PGHDR_DONT_WRITE;
  24870. assert( p->nRef>0 );
  24871. if( 0==(p->flags & PGHDR_DIRTY) ){
  24872. p->flags |= PGHDR_DIRTY;
  24873. pcacheAddToDirtyList( p);
  24874. }
  24875. }
  24876. /*
  24877. ** Make sure the page is marked as clean. If it isn't clean already,
  24878. ** make it so.
  24879. */
  24880. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  24881. if( (p->flags & PGHDR_DIRTY) ){
  24882. pcacheRemoveFromDirtyList(p);
  24883. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  24884. if( p->nRef==0 ){
  24885. pcacheUnpin(p);
  24886. }
  24887. }
  24888. }
  24889. /*
  24890. ** Make every page in the cache clean.
  24891. */
  24892. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  24893. PgHdr *p;
  24894. while( (p = pCache->pDirty)!=0 ){
  24895. sqlite3PcacheMakeClean(p);
  24896. }
  24897. }
  24898. /*
  24899. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  24900. */
  24901. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  24902. PgHdr *p;
  24903. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  24904. p->flags &= ~PGHDR_NEED_SYNC;
  24905. }
  24906. pCache->pSynced = pCache->pDirtyTail;
  24907. }
  24908. /*
  24909. ** Change the page number of page p to newPgno.
  24910. */
  24911. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  24912. PCache *pCache = p->pCache;
  24913. assert( p->nRef>0 );
  24914. assert( newPgno>0 );
  24915. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  24916. p->pgno = newPgno;
  24917. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  24918. pcacheRemoveFromDirtyList(p);
  24919. pcacheAddToDirtyList(p);
  24920. }
  24921. }
  24922. /*
  24923. ** Drop every cache entry whose page number is greater than "pgno". The
  24924. ** caller must ensure that there are no outstanding references to any pages
  24925. ** other than page 1 with a page number greater than pgno.
  24926. **
  24927. ** If there is a reference to page 1 and the pgno parameter passed to this
  24928. ** function is 0, then the data area associated with page 1 is zeroed, but
  24929. ** the page object is not dropped.
  24930. */
  24931. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  24932. if( pCache->pCache ){
  24933. PgHdr *p;
  24934. PgHdr *pNext;
  24935. for(p=pCache->pDirty; p; p=pNext){
  24936. pNext = p->pDirtyNext;
  24937. /* This routine never gets call with a positive pgno except right
  24938. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  24939. ** it must be that pgno==0.
  24940. */
  24941. assert( p->pgno>0 );
  24942. if( ALWAYS(p->pgno>pgno) ){
  24943. assert( p->flags&PGHDR_DIRTY );
  24944. sqlite3PcacheMakeClean(p);
  24945. }
  24946. }
  24947. if( pgno==0 && pCache->pPage1 ){
  24948. memset(pCache->pPage1->pData, 0, pCache->szPage);
  24949. pgno = 1;
  24950. }
  24951. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  24952. }
  24953. }
  24954. /*
  24955. ** Close a cache.
  24956. */
  24957. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  24958. if( pCache->pCache ){
  24959. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  24960. }
  24961. }
  24962. /*
  24963. ** Discard the contents of the cache.
  24964. */
  24965. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  24966. sqlite3PcacheTruncate(pCache, 0);
  24967. }
  24968. /*
  24969. ** Merge two lists of pages connected by pDirty and in pgno order.
  24970. ** Do not both fixing the pDirtyPrev pointers.
  24971. */
  24972. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  24973. PgHdr result, *pTail;
  24974. pTail = &result;
  24975. while( pA && pB ){
  24976. if( pA->pgno<pB->pgno ){
  24977. pTail->pDirty = pA;
  24978. pTail = pA;
  24979. pA = pA->pDirty;
  24980. }else{
  24981. pTail->pDirty = pB;
  24982. pTail = pB;
  24983. pB = pB->pDirty;
  24984. }
  24985. }
  24986. if( pA ){
  24987. pTail->pDirty = pA;
  24988. }else if( pB ){
  24989. pTail->pDirty = pB;
  24990. }else{
  24991. pTail->pDirty = 0;
  24992. }
  24993. return result.pDirty;
  24994. }
  24995. /*
  24996. ** Sort the list of pages in accending order by pgno. Pages are
  24997. ** connected by pDirty pointers. The pDirtyPrev pointers are
  24998. ** corrupted by this sort.
  24999. **
  25000. ** Since there cannot be more than 2^31 distinct pages in a database,
  25001. ** there cannot be more than 31 buckets required by the merge sorter.
  25002. ** One extra bucket is added to catch overflow in case something
  25003. ** ever changes to make the previous sentence incorrect.
  25004. */
  25005. #define N_SORT_BUCKET 32
  25006. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  25007. PgHdr *a[N_SORT_BUCKET], *p;
  25008. int i;
  25009. memset(a, 0, sizeof(a));
  25010. while( pIn ){
  25011. p = pIn;
  25012. pIn = p->pDirty;
  25013. p->pDirty = 0;
  25014. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  25015. if( a[i]==0 ){
  25016. a[i] = p;
  25017. break;
  25018. }else{
  25019. p = pcacheMergeDirtyList(a[i], p);
  25020. a[i] = 0;
  25021. }
  25022. }
  25023. if( NEVER(i==N_SORT_BUCKET-1) ){
  25024. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  25025. ** the input list. But that is impossible.
  25026. */
  25027. a[i] = pcacheMergeDirtyList(a[i], p);
  25028. }
  25029. }
  25030. p = a[0];
  25031. for(i=1; i<N_SORT_BUCKET; i++){
  25032. p = pcacheMergeDirtyList(p, a[i]);
  25033. }
  25034. return p;
  25035. }
  25036. /*
  25037. ** Return a list of all dirty pages in the cache, sorted by page number.
  25038. */
  25039. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  25040. PgHdr *p;
  25041. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  25042. p->pDirty = p->pDirtyNext;
  25043. }
  25044. return pcacheSortDirtyList(pCache->pDirty);
  25045. }
  25046. /*
  25047. ** Return the total number of referenced pages held by the cache.
  25048. */
  25049. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  25050. return pCache->nRef;
  25051. }
  25052. /*
  25053. ** Return the number of references to the page supplied as an argument.
  25054. */
  25055. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  25056. return p->nRef;
  25057. }
  25058. /*
  25059. ** Return the total number of pages in the cache.
  25060. */
  25061. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  25062. int nPage = 0;
  25063. if( pCache->pCache ){
  25064. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  25065. }
  25066. return nPage;
  25067. }
  25068. #ifdef SQLITE_TEST
  25069. /*
  25070. ** Get the suggested cache-size value.
  25071. */
  25072. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  25073. return numberOfCachePages(pCache);
  25074. }
  25075. #endif
  25076. /*
  25077. ** Set the suggested cache-size value.
  25078. */
  25079. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  25080. pCache->szCache = mxPage;
  25081. if( pCache->pCache ){
  25082. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  25083. numberOfCachePages(pCache));
  25084. }
  25085. }
  25086. /*
  25087. ** Free up as much memory as possible from the page cache.
  25088. */
  25089. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  25090. if( pCache->pCache ){
  25091. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  25092. }
  25093. }
  25094. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  25095. /*
  25096. ** For all dirty pages currently in the cache, invoke the specified
  25097. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  25098. ** defined.
  25099. */
  25100. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  25101. PgHdr *pDirty;
  25102. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  25103. xIter(pDirty);
  25104. }
  25105. }
  25106. #endif
  25107. /************** End of pcache.c **********************************************/
  25108. /************** Begin file pcache1.c *****************************************/
  25109. /*
  25110. ** 2008 November 05
  25111. **
  25112. ** The author disclaims copyright to this source code. In place of
  25113. ** a legal notice, here is a blessing:
  25114. **
  25115. ** May you do good and not evil.
  25116. ** May you find forgiveness for yourself and forgive others.
  25117. ** May you share freely, never taking more than you give.
  25118. **
  25119. *************************************************************************
  25120. **
  25121. ** This file implements the default page cache implementation (the
  25122. ** sqlite3_pcache interface). It also contains part of the implementation
  25123. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  25124. ** If the default page cache implementation is overriden, then neither of
  25125. ** these two features are available.
  25126. */
  25127. typedef struct PCache1 PCache1;
  25128. typedef struct PgHdr1 PgHdr1;
  25129. typedef struct PgFreeslot PgFreeslot;
  25130. typedef struct PGroup PGroup;
  25131. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  25132. ** of one or more PCaches that are able to recycle each others unpinned
  25133. ** pages when they are under memory pressure. A PGroup is an instance of
  25134. ** the following object.
  25135. **
  25136. ** This page cache implementation works in one of two modes:
  25137. **
  25138. ** (1) Every PCache is the sole member of its own PGroup. There is
  25139. ** one PGroup per PCache.
  25140. **
  25141. ** (2) There is a single global PGroup that all PCaches are a member
  25142. ** of.
  25143. **
  25144. ** Mode 1 uses more memory (since PCache instances are not able to rob
  25145. ** unused pages from other PCaches) but it also operates without a mutex,
  25146. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  25147. ** threadsafe, but recycles pages more efficiently.
  25148. **
  25149. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  25150. ** PGroup which is the pcache1.grp global variable and its mutex is
  25151. ** SQLITE_MUTEX_STATIC_LRU.
  25152. */
  25153. struct PGroup {
  25154. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  25155. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  25156. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  25157. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  25158. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  25159. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  25160. };
  25161. /* Each page cache is an instance of the following object. Every
  25162. ** open database file (including each in-memory database and each
  25163. ** temporary or transient database) has a single page cache which
  25164. ** is an instance of this object.
  25165. **
  25166. ** Pointers to structures of this type are cast and returned as
  25167. ** opaque sqlite3_pcache* handles.
  25168. */
  25169. struct PCache1 {
  25170. /* Cache configuration parameters. Page size (szPage) and the purgeable
  25171. ** flag (bPurgeable) are set when the cache is created. nMax may be
  25172. ** modified at any time by a call to the pcache1Cachesize() method.
  25173. ** The PGroup mutex must be held when accessing nMax.
  25174. */
  25175. PGroup *pGroup; /* PGroup this cache belongs to */
  25176. int szPage; /* Size of allocated pages in bytes */
  25177. int szExtra; /* Size of extra space in bytes */
  25178. int bPurgeable; /* True if cache is purgeable */
  25179. unsigned int nMin; /* Minimum number of pages reserved */
  25180. unsigned int nMax; /* Configured "cache_size" value */
  25181. unsigned int n90pct; /* nMax*9/10 */
  25182. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  25183. /* Hash table of all pages. The following variables may only be accessed
  25184. ** when the accessor is holding the PGroup mutex.
  25185. */
  25186. unsigned int nRecyclable; /* Number of pages in the LRU list */
  25187. unsigned int nPage; /* Total number of pages in apHash */
  25188. unsigned int nHash; /* Number of slots in apHash[] */
  25189. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  25190. };
  25191. /*
  25192. ** Each cache entry is represented by an instance of the following
  25193. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  25194. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  25195. ** in memory.
  25196. */
  25197. struct PgHdr1 {
  25198. sqlite3_pcache_page page;
  25199. unsigned int iKey; /* Key value (page number) */
  25200. PgHdr1 *pNext; /* Next in hash table chain */
  25201. PCache1 *pCache; /* Cache that currently owns this page */
  25202. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  25203. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  25204. };
  25205. /*
  25206. ** Free slots in the allocator used to divide up the buffer provided using
  25207. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  25208. */
  25209. struct PgFreeslot {
  25210. PgFreeslot *pNext; /* Next free slot */
  25211. };
  25212. /*
  25213. ** Global data used by this cache.
  25214. */
  25215. static SQLITE_WSD struct PCacheGlobal {
  25216. PGroup grp; /* The global PGroup for mode (2) */
  25217. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  25218. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  25219. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  25220. ** The nFreeSlot and pFree values do require mutex protection.
  25221. */
  25222. int isInit; /* True if initialized */
  25223. int szSlot; /* Size of each free slot */
  25224. int nSlot; /* The number of pcache slots */
  25225. int nReserve; /* Try to keep nFreeSlot above this */
  25226. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  25227. /* Above requires no mutex. Use mutex below for variable that follow. */
  25228. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  25229. PgFreeslot *pFree; /* Free page blocks */
  25230. int nFreeSlot; /* Number of unused pcache slots */
  25231. /* The following value requires a mutex to change. We skip the mutex on
  25232. ** reading because (1) most platforms read a 32-bit integer atomically and
  25233. ** (2) even if an incorrect value is read, no great harm is done since this
  25234. ** is really just an optimization. */
  25235. int bUnderPressure; /* True if low on PAGECACHE memory */
  25236. } pcache1_g;
  25237. /*
  25238. ** All code in this file should access the global structure above via the
  25239. ** alias "pcache1". This ensures that the WSD emulation is used when
  25240. ** compiling for systems that do not support real WSD.
  25241. */
  25242. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  25243. /*
  25244. ** Macros to enter and leave the PCache LRU mutex.
  25245. */
  25246. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  25247. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  25248. /******************************************************************************/
  25249. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  25250. /*
  25251. ** This function is called during initialization if a static buffer is
  25252. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  25253. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  25254. ** enough to contain 'n' buffers of 'sz' bytes each.
  25255. **
  25256. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  25257. ** to be serialized already. There is no need for further mutexing.
  25258. */
  25259. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  25260. if( pcache1.isInit ){
  25261. PgFreeslot *p;
  25262. sz = ROUNDDOWN8(sz);
  25263. pcache1.szSlot = sz;
  25264. pcache1.nSlot = pcache1.nFreeSlot = n;
  25265. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  25266. pcache1.pStart = pBuf;
  25267. pcache1.pFree = 0;
  25268. pcache1.bUnderPressure = 0;
  25269. while( n-- ){
  25270. p = (PgFreeslot*)pBuf;
  25271. p->pNext = pcache1.pFree;
  25272. pcache1.pFree = p;
  25273. pBuf = (void*)&((char*)pBuf)[sz];
  25274. }
  25275. pcache1.pEnd = pBuf;
  25276. }
  25277. }
  25278. /*
  25279. ** Malloc function used within this file to allocate space from the buffer
  25280. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  25281. ** such buffer exists or there is no space left in it, this function falls
  25282. ** back to sqlite3Malloc().
  25283. **
  25284. ** Multiple threads can run this routine at the same time. Global variables
  25285. ** in pcache1 need to be protected via mutex.
  25286. */
  25287. static void *pcache1Alloc(int nByte){
  25288. void *p = 0;
  25289. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  25290. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  25291. if( nByte<=pcache1.szSlot ){
  25292. sqlite3_mutex_enter(pcache1.mutex);
  25293. p = (PgHdr1 *)pcache1.pFree;
  25294. if( p ){
  25295. pcache1.pFree = pcache1.pFree->pNext;
  25296. pcache1.nFreeSlot--;
  25297. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  25298. assert( pcache1.nFreeSlot>=0 );
  25299. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  25300. }
  25301. sqlite3_mutex_leave(pcache1.mutex);
  25302. }
  25303. if( p==0 ){
  25304. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  25305. ** it from sqlite3Malloc instead.
  25306. */
  25307. p = sqlite3Malloc(nByte);
  25308. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  25309. if( p ){
  25310. int sz = sqlite3MallocSize(p);
  25311. sqlite3_mutex_enter(pcache1.mutex);
  25312. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  25313. sqlite3_mutex_leave(pcache1.mutex);
  25314. }
  25315. #endif
  25316. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  25317. }
  25318. return p;
  25319. }
  25320. /*
  25321. ** Free an allocated buffer obtained from pcache1Alloc().
  25322. */
  25323. static int pcache1Free(void *p){
  25324. int nFreed = 0;
  25325. if( p==0 ) return 0;
  25326. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  25327. PgFreeslot *pSlot;
  25328. sqlite3_mutex_enter(pcache1.mutex);
  25329. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  25330. pSlot = (PgFreeslot*)p;
  25331. pSlot->pNext = pcache1.pFree;
  25332. pcache1.pFree = pSlot;
  25333. pcache1.nFreeSlot++;
  25334. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  25335. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  25336. sqlite3_mutex_leave(pcache1.mutex);
  25337. }else{
  25338. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  25339. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25340. nFreed = sqlite3MallocSize(p);
  25341. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  25342. sqlite3_mutex_enter(pcache1.mutex);
  25343. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  25344. sqlite3_mutex_leave(pcache1.mutex);
  25345. #endif
  25346. sqlite3_free(p);
  25347. }
  25348. return nFreed;
  25349. }
  25350. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25351. /*
  25352. ** Return the size of a pcache allocation
  25353. */
  25354. static int pcache1MemSize(void *p){
  25355. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  25356. return pcache1.szSlot;
  25357. }else{
  25358. int iSize;
  25359. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  25360. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25361. iSize = sqlite3MallocSize(p);
  25362. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  25363. return iSize;
  25364. }
  25365. }
  25366. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  25367. /*
  25368. ** Allocate a new page object initially associated with cache pCache.
  25369. */
  25370. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  25371. PgHdr1 *p = 0;
  25372. void *pPg;
  25373. /* The group mutex must be released before pcache1Alloc() is called. This
  25374. ** is because it may call sqlite3_release_memory(), which assumes that
  25375. ** this mutex is not held. */
  25376. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25377. pcache1LeaveMutex(pCache->pGroup);
  25378. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  25379. pPg = pcache1Alloc(pCache->szPage);
  25380. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  25381. if( !pPg || !p ){
  25382. pcache1Free(pPg);
  25383. sqlite3_free(p);
  25384. pPg = 0;
  25385. }
  25386. #else
  25387. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  25388. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  25389. #endif
  25390. pcache1EnterMutex(pCache->pGroup);
  25391. if( pPg ){
  25392. p->page.pBuf = pPg;
  25393. p->page.pExtra = &p[1];
  25394. if( pCache->bPurgeable ){
  25395. pCache->pGroup->nCurrentPage++;
  25396. }
  25397. return p;
  25398. }
  25399. return 0;
  25400. }
  25401. /*
  25402. ** Free a page object allocated by pcache1AllocPage().
  25403. **
  25404. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  25405. ** that the current implementation happens to never call this routine
  25406. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  25407. */
  25408. static void pcache1FreePage(PgHdr1 *p){
  25409. if( ALWAYS(p) ){
  25410. PCache1 *pCache = p->pCache;
  25411. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  25412. pcache1Free(p->page.pBuf);
  25413. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  25414. sqlite3_free(p);
  25415. #endif
  25416. if( pCache->bPurgeable ){
  25417. pCache->pGroup->nCurrentPage--;
  25418. }
  25419. }
  25420. }
  25421. /*
  25422. ** Malloc function used by SQLite to obtain space from the buffer configured
  25423. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  25424. ** exists, this function falls back to sqlite3Malloc().
  25425. */
  25426. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  25427. return pcache1Alloc(sz);
  25428. }
  25429. /*
  25430. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  25431. */
  25432. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  25433. pcache1Free(p);
  25434. }
  25435. /*
  25436. ** Return true if it desirable to avoid allocating a new page cache
  25437. ** entry.
  25438. **
  25439. ** If memory was allocated specifically to the page cache using
  25440. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  25441. ** it is desirable to avoid allocating a new page cache entry because
  25442. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  25443. ** for all page cache needs and we should not need to spill the
  25444. ** allocation onto the heap.
  25445. **
  25446. ** Or, the heap is used for all page cache memory but the heap is
  25447. ** under memory pressure, then again it is desirable to avoid
  25448. ** allocating a new page cache entry in order to avoid stressing
  25449. ** the heap even further.
  25450. */
  25451. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  25452. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  25453. return pcache1.bUnderPressure;
  25454. }else{
  25455. return sqlite3HeapNearlyFull();
  25456. }
  25457. }
  25458. /******************************************************************************/
  25459. /******** General Implementation Functions ************************************/
  25460. /*
  25461. ** This function is used to resize the hash table used by the cache passed
  25462. ** as the first argument.
  25463. **
  25464. ** The PCache mutex must be held when this function is called.
  25465. */
  25466. static int pcache1ResizeHash(PCache1 *p){
  25467. PgHdr1 **apNew;
  25468. unsigned int nNew;
  25469. unsigned int i;
  25470. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  25471. nNew = p->nHash*2;
  25472. if( nNew<256 ){
  25473. nNew = 256;
  25474. }
  25475. pcache1LeaveMutex(p->pGroup);
  25476. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  25477. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  25478. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  25479. pcache1EnterMutex(p->pGroup);
  25480. if( apNew ){
  25481. for(i=0; i<p->nHash; i++){
  25482. PgHdr1 *pPage;
  25483. PgHdr1 *pNext = p->apHash[i];
  25484. while( (pPage = pNext)!=0 ){
  25485. unsigned int h = pPage->iKey % nNew;
  25486. pNext = pPage->pNext;
  25487. pPage->pNext = apNew[h];
  25488. apNew[h] = pPage;
  25489. }
  25490. }
  25491. sqlite3_free(p->apHash);
  25492. p->apHash = apNew;
  25493. p->nHash = nNew;
  25494. }
  25495. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  25496. }
  25497. /*
  25498. ** This function is used internally to remove the page pPage from the
  25499. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  25500. ** LRU list, then this function is a no-op.
  25501. **
  25502. ** The PGroup mutex must be held when this function is called.
  25503. **
  25504. ** If pPage is NULL then this routine is a no-op.
  25505. */
  25506. static void pcache1PinPage(PgHdr1 *pPage){
  25507. PCache1 *pCache;
  25508. PGroup *pGroup;
  25509. if( pPage==0 ) return;
  25510. pCache = pPage->pCache;
  25511. pGroup = pCache->pGroup;
  25512. assert( sqlite3_mutex_held(pGroup->mutex) );
  25513. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  25514. if( pPage->pLruPrev ){
  25515. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  25516. }
  25517. if( pPage->pLruNext ){
  25518. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  25519. }
  25520. if( pGroup->pLruHead==pPage ){
  25521. pGroup->pLruHead = pPage->pLruNext;
  25522. }
  25523. if( pGroup->pLruTail==pPage ){
  25524. pGroup->pLruTail = pPage->pLruPrev;
  25525. }
  25526. pPage->pLruNext = 0;
  25527. pPage->pLruPrev = 0;
  25528. pPage->pCache->nRecyclable--;
  25529. }
  25530. }
  25531. /*
  25532. ** Remove the page supplied as an argument from the hash table
  25533. ** (PCache1.apHash structure) that it is currently stored in.
  25534. **
  25535. ** The PGroup mutex must be held when this function is called.
  25536. */
  25537. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  25538. unsigned int h;
  25539. PCache1 *pCache = pPage->pCache;
  25540. PgHdr1 **pp;
  25541. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25542. h = pPage->iKey % pCache->nHash;
  25543. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  25544. *pp = (*pp)->pNext;
  25545. pCache->nPage--;
  25546. }
  25547. /*
  25548. ** If there are currently more than nMaxPage pages allocated, try
  25549. ** to recycle pages to reduce the number allocated to nMaxPage.
  25550. */
  25551. static void pcache1EnforceMaxPage(PGroup *pGroup){
  25552. assert( sqlite3_mutex_held(pGroup->mutex) );
  25553. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  25554. PgHdr1 *p = pGroup->pLruTail;
  25555. assert( p->pCache->pGroup==pGroup );
  25556. pcache1PinPage(p);
  25557. pcache1RemoveFromHash(p);
  25558. pcache1FreePage(p);
  25559. }
  25560. }
  25561. /*
  25562. ** Discard all pages from cache pCache with a page number (key value)
  25563. ** greater than or equal to iLimit. Any pinned pages that meet this
  25564. ** criteria are unpinned before they are discarded.
  25565. **
  25566. ** The PCache mutex must be held when this function is called.
  25567. */
  25568. static void pcache1TruncateUnsafe(
  25569. PCache1 *pCache, /* The cache to truncate */
  25570. unsigned int iLimit /* Drop pages with this pgno or larger */
  25571. ){
  25572. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  25573. unsigned int h;
  25574. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25575. for(h=0; h<pCache->nHash; h++){
  25576. PgHdr1 **pp = &pCache->apHash[h];
  25577. PgHdr1 *pPage;
  25578. while( (pPage = *pp)!=0 ){
  25579. if( pPage->iKey>=iLimit ){
  25580. pCache->nPage--;
  25581. *pp = pPage->pNext;
  25582. pcache1PinPage(pPage);
  25583. pcache1FreePage(pPage);
  25584. }else{
  25585. pp = &pPage->pNext;
  25586. TESTONLY( nPage++; )
  25587. }
  25588. }
  25589. }
  25590. assert( pCache->nPage==nPage );
  25591. }
  25592. /******************************************************************************/
  25593. /******** sqlite3_pcache Methods **********************************************/
  25594. /*
  25595. ** Implementation of the sqlite3_pcache.xInit method.
  25596. */
  25597. static int pcache1Init(void *NotUsed){
  25598. UNUSED_PARAMETER(NotUsed);
  25599. assert( pcache1.isInit==0 );
  25600. memset(&pcache1, 0, sizeof(pcache1));
  25601. if( sqlite3GlobalConfig.bCoreMutex ){
  25602. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  25603. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  25604. }
  25605. pcache1.grp.mxPinned = 10;
  25606. pcache1.isInit = 1;
  25607. return SQLITE_OK;
  25608. }
  25609. /*
  25610. ** Implementation of the sqlite3_pcache.xShutdown method.
  25611. ** Note that the static mutex allocated in xInit does
  25612. ** not need to be freed.
  25613. */
  25614. static void pcache1Shutdown(void *NotUsed){
  25615. UNUSED_PARAMETER(NotUsed);
  25616. assert( pcache1.isInit!=0 );
  25617. memset(&pcache1, 0, sizeof(pcache1));
  25618. }
  25619. /*
  25620. ** Implementation of the sqlite3_pcache.xCreate method.
  25621. **
  25622. ** Allocate a new cache.
  25623. */
  25624. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  25625. PCache1 *pCache; /* The newly created page cache */
  25626. PGroup *pGroup; /* The group the new page cache will belong to */
  25627. int sz; /* Bytes of memory required to allocate the new cache */
  25628. /*
  25629. ** The separateCache variable is true if each PCache has its own private
  25630. ** PGroup. In other words, separateCache is true for mode (1) where no
  25631. ** mutexing is required.
  25632. **
  25633. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  25634. **
  25635. ** * Always use a unified cache in single-threaded applications
  25636. **
  25637. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  25638. ** use separate caches (mode-1)
  25639. */
  25640. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  25641. const int separateCache = 0;
  25642. #else
  25643. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  25644. #endif
  25645. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  25646. assert( szExtra < 300 );
  25647. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  25648. pCache = (PCache1 *)sqlite3MallocZero(sz);
  25649. if( pCache ){
  25650. if( separateCache ){
  25651. pGroup = (PGroup*)&pCache[1];
  25652. pGroup->mxPinned = 10;
  25653. }else{
  25654. pGroup = &pcache1.grp;
  25655. }
  25656. pCache->pGroup = pGroup;
  25657. pCache->szPage = szPage;
  25658. pCache->szExtra = szExtra;
  25659. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  25660. if( bPurgeable ){
  25661. pCache->nMin = 10;
  25662. pcache1EnterMutex(pGroup);
  25663. pGroup->nMinPage += pCache->nMin;
  25664. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25665. pcache1LeaveMutex(pGroup);
  25666. }
  25667. }
  25668. return (sqlite3_pcache *)pCache;
  25669. }
  25670. /*
  25671. ** Implementation of the sqlite3_pcache.xCachesize method.
  25672. **
  25673. ** Configure the cache_size limit for a cache.
  25674. */
  25675. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  25676. PCache1 *pCache = (PCache1 *)p;
  25677. if( pCache->bPurgeable ){
  25678. PGroup *pGroup = pCache->pGroup;
  25679. pcache1EnterMutex(pGroup);
  25680. pGroup->nMaxPage += (nMax - pCache->nMax);
  25681. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25682. pCache->nMax = nMax;
  25683. pCache->n90pct = pCache->nMax*9/10;
  25684. pcache1EnforceMaxPage(pGroup);
  25685. pcache1LeaveMutex(pGroup);
  25686. }
  25687. }
  25688. /*
  25689. ** Implementation of the sqlite3_pcache.xShrink method.
  25690. **
  25691. ** Free up as much memory as possible.
  25692. */
  25693. static void pcache1Shrink(sqlite3_pcache *p){
  25694. PCache1 *pCache = (PCache1*)p;
  25695. if( pCache->bPurgeable ){
  25696. PGroup *pGroup = pCache->pGroup;
  25697. int savedMaxPage;
  25698. pcache1EnterMutex(pGroup);
  25699. savedMaxPage = pGroup->nMaxPage;
  25700. pGroup->nMaxPage = 0;
  25701. pcache1EnforceMaxPage(pGroup);
  25702. pGroup->nMaxPage = savedMaxPage;
  25703. pcache1LeaveMutex(pGroup);
  25704. }
  25705. }
  25706. /*
  25707. ** Implementation of the sqlite3_pcache.xPagecount method.
  25708. */
  25709. static int pcache1Pagecount(sqlite3_pcache *p){
  25710. int n;
  25711. PCache1 *pCache = (PCache1*)p;
  25712. pcache1EnterMutex(pCache->pGroup);
  25713. n = pCache->nPage;
  25714. pcache1LeaveMutex(pCache->pGroup);
  25715. return n;
  25716. }
  25717. /*
  25718. ** Implementation of the sqlite3_pcache.xFetch method.
  25719. **
  25720. ** Fetch a page by key value.
  25721. **
  25722. ** Whether or not a new page may be allocated by this function depends on
  25723. ** the value of the createFlag argument. 0 means do not allocate a new
  25724. ** page. 1 means allocate a new page if space is easily available. 2
  25725. ** means to try really hard to allocate a new page.
  25726. **
  25727. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  25728. ** database) there is really no difference between createFlag 1 and 2. So
  25729. ** the calling function (pcache.c) will never have a createFlag of 1 on
  25730. ** a non-purgeable cache.
  25731. **
  25732. ** There are three different approaches to obtaining space for a page,
  25733. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  25734. **
  25735. ** 1. Regardless of the value of createFlag, the cache is searched for a
  25736. ** copy of the requested page. If one is found, it is returned.
  25737. **
  25738. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  25739. ** returned.
  25740. **
  25741. ** 3. If createFlag is 1, and the page is not already in the cache, then
  25742. ** return NULL (do not allocate a new page) if any of the following
  25743. ** conditions are true:
  25744. **
  25745. ** (a) the number of pages pinned by the cache is greater than
  25746. ** PCache1.nMax, or
  25747. **
  25748. ** (b) the number of pages pinned by the cache is greater than
  25749. ** the sum of nMax for all purgeable caches, less the sum of
  25750. ** nMin for all other purgeable caches, or
  25751. **
  25752. ** 4. If none of the first three conditions apply and the cache is marked
  25753. ** as purgeable, and if one of the following is true:
  25754. **
  25755. ** (a) The number of pages allocated for the cache is already
  25756. ** PCache1.nMax, or
  25757. **
  25758. ** (b) The number of pages allocated for all purgeable caches is
  25759. ** already equal to or greater than the sum of nMax for all
  25760. ** purgeable caches,
  25761. **
  25762. ** (c) The system is under memory pressure and wants to avoid
  25763. ** unnecessary pages cache entry allocations
  25764. **
  25765. ** then attempt to recycle a page from the LRU list. If it is the right
  25766. ** size, return the recycled buffer. Otherwise, free the buffer and
  25767. ** proceed to step 5.
  25768. **
  25769. ** 5. Otherwise, allocate and return a new page buffer.
  25770. */
  25771. static sqlite3_pcache_page *pcache1Fetch(
  25772. sqlite3_pcache *p,
  25773. unsigned int iKey,
  25774. int createFlag
  25775. ){
  25776. unsigned int nPinned;
  25777. PCache1 *pCache = (PCache1 *)p;
  25778. PGroup *pGroup;
  25779. PgHdr1 *pPage = 0;
  25780. assert( pCache->bPurgeable || createFlag!=1 );
  25781. assert( pCache->bPurgeable || pCache->nMin==0 );
  25782. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  25783. assert( pCache->nMin==0 || pCache->bPurgeable );
  25784. pcache1EnterMutex(pGroup = pCache->pGroup);
  25785. /* Step 1: Search the hash table for an existing entry. */
  25786. if( pCache->nHash>0 ){
  25787. unsigned int h = iKey % pCache->nHash;
  25788. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  25789. }
  25790. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  25791. if( pPage || createFlag==0 ){
  25792. pcache1PinPage(pPage);
  25793. goto fetch_out;
  25794. }
  25795. /* The pGroup local variable will normally be initialized by the
  25796. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  25797. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  25798. ** local variable here. Delaying the initialization of pGroup is an
  25799. ** optimization: The common case is to exit the module before reaching
  25800. ** this point.
  25801. */
  25802. #ifdef SQLITE_MUTEX_OMIT
  25803. pGroup = pCache->pGroup;
  25804. #endif
  25805. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  25806. assert( pCache->nPage >= pCache->nRecyclable );
  25807. nPinned = pCache->nPage - pCache->nRecyclable;
  25808. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  25809. assert( pCache->n90pct == pCache->nMax*9/10 );
  25810. if( createFlag==1 && (
  25811. nPinned>=pGroup->mxPinned
  25812. || nPinned>=pCache->n90pct
  25813. || pcache1UnderMemoryPressure(pCache)
  25814. )){
  25815. goto fetch_out;
  25816. }
  25817. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  25818. goto fetch_out;
  25819. }
  25820. assert( pCache->nHash>0 && pCache->apHash );
  25821. /* Step 4. Try to recycle a page. */
  25822. if( pCache->bPurgeable && pGroup->pLruTail && (
  25823. (pCache->nPage+1>=pCache->nMax)
  25824. || pGroup->nCurrentPage>=pGroup->nMaxPage
  25825. || pcache1UnderMemoryPressure(pCache)
  25826. )){
  25827. PCache1 *pOther;
  25828. pPage = pGroup->pLruTail;
  25829. pcache1RemoveFromHash(pPage);
  25830. pcache1PinPage(pPage);
  25831. pOther = pPage->pCache;
  25832. /* We want to verify that szPage and szExtra are the same for pOther
  25833. ** and pCache. Assert that we can verify this by comparing sums. */
  25834. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  25835. assert( pCache->szExtra<512 );
  25836. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  25837. assert( pOther->szExtra<512 );
  25838. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  25839. pcache1FreePage(pPage);
  25840. pPage = 0;
  25841. }else{
  25842. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  25843. }
  25844. }
  25845. /* Step 5. If a usable page buffer has still not been found,
  25846. ** attempt to allocate a new one.
  25847. */
  25848. if( !pPage ){
  25849. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  25850. pPage = pcache1AllocPage(pCache);
  25851. if( createFlag==1 ) sqlite3EndBenignMalloc();
  25852. }
  25853. if( pPage ){
  25854. unsigned int h = iKey % pCache->nHash;
  25855. pCache->nPage++;
  25856. pPage->iKey = iKey;
  25857. pPage->pNext = pCache->apHash[h];
  25858. pPage->pCache = pCache;
  25859. pPage->pLruPrev = 0;
  25860. pPage->pLruNext = 0;
  25861. *(void **)pPage->page.pExtra = 0;
  25862. pCache->apHash[h] = pPage;
  25863. }
  25864. fetch_out:
  25865. if( pPage && iKey>pCache->iMaxKey ){
  25866. pCache->iMaxKey = iKey;
  25867. }
  25868. pcache1LeaveMutex(pGroup);
  25869. return &pPage->page;
  25870. }
  25871. /*
  25872. ** Implementation of the sqlite3_pcache.xUnpin method.
  25873. **
  25874. ** Mark a page as unpinned (eligible for asynchronous recycling).
  25875. */
  25876. static void pcache1Unpin(
  25877. sqlite3_pcache *p,
  25878. sqlite3_pcache_page *pPg,
  25879. int reuseUnlikely
  25880. ){
  25881. PCache1 *pCache = (PCache1 *)p;
  25882. PgHdr1 *pPage = (PgHdr1 *)pPg;
  25883. PGroup *pGroup = pCache->pGroup;
  25884. assert( pPage->pCache==pCache );
  25885. pcache1EnterMutex(pGroup);
  25886. /* It is an error to call this function if the page is already
  25887. ** part of the PGroup LRU list.
  25888. */
  25889. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  25890. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  25891. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  25892. pcache1RemoveFromHash(pPage);
  25893. pcache1FreePage(pPage);
  25894. }else{
  25895. /* Add the page to the PGroup LRU list. */
  25896. if( pGroup->pLruHead ){
  25897. pGroup->pLruHead->pLruPrev = pPage;
  25898. pPage->pLruNext = pGroup->pLruHead;
  25899. pGroup->pLruHead = pPage;
  25900. }else{
  25901. pGroup->pLruTail = pPage;
  25902. pGroup->pLruHead = pPage;
  25903. }
  25904. pCache->nRecyclable++;
  25905. }
  25906. pcache1LeaveMutex(pCache->pGroup);
  25907. }
  25908. /*
  25909. ** Implementation of the sqlite3_pcache.xRekey method.
  25910. */
  25911. static void pcache1Rekey(
  25912. sqlite3_pcache *p,
  25913. sqlite3_pcache_page *pPg,
  25914. unsigned int iOld,
  25915. unsigned int iNew
  25916. ){
  25917. PCache1 *pCache = (PCache1 *)p;
  25918. PgHdr1 *pPage = (PgHdr1 *)pPg;
  25919. PgHdr1 **pp;
  25920. unsigned int h;
  25921. assert( pPage->iKey==iOld );
  25922. assert( pPage->pCache==pCache );
  25923. pcache1EnterMutex(pCache->pGroup);
  25924. h = iOld%pCache->nHash;
  25925. pp = &pCache->apHash[h];
  25926. while( (*pp)!=pPage ){
  25927. pp = &(*pp)->pNext;
  25928. }
  25929. *pp = pPage->pNext;
  25930. h = iNew%pCache->nHash;
  25931. pPage->iKey = iNew;
  25932. pPage->pNext = pCache->apHash[h];
  25933. pCache->apHash[h] = pPage;
  25934. if( iNew>pCache->iMaxKey ){
  25935. pCache->iMaxKey = iNew;
  25936. }
  25937. pcache1LeaveMutex(pCache->pGroup);
  25938. }
  25939. /*
  25940. ** Implementation of the sqlite3_pcache.xTruncate method.
  25941. **
  25942. ** Discard all unpinned pages in the cache with a page number equal to
  25943. ** or greater than parameter iLimit. Any pinned pages with a page number
  25944. ** equal to or greater than iLimit are implicitly unpinned.
  25945. */
  25946. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  25947. PCache1 *pCache = (PCache1 *)p;
  25948. pcache1EnterMutex(pCache->pGroup);
  25949. if( iLimit<=pCache->iMaxKey ){
  25950. pcache1TruncateUnsafe(pCache, iLimit);
  25951. pCache->iMaxKey = iLimit-1;
  25952. }
  25953. pcache1LeaveMutex(pCache->pGroup);
  25954. }
  25955. /*
  25956. ** Implementation of the sqlite3_pcache.xDestroy method.
  25957. **
  25958. ** Destroy a cache allocated using pcache1Create().
  25959. */
  25960. static void pcache1Destroy(sqlite3_pcache *p){
  25961. PCache1 *pCache = (PCache1 *)p;
  25962. PGroup *pGroup = pCache->pGroup;
  25963. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  25964. pcache1EnterMutex(pGroup);
  25965. pcache1TruncateUnsafe(pCache, 0);
  25966. assert( pGroup->nMaxPage >= pCache->nMax );
  25967. pGroup->nMaxPage -= pCache->nMax;
  25968. assert( pGroup->nMinPage >= pCache->nMin );
  25969. pGroup->nMinPage -= pCache->nMin;
  25970. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25971. pcache1EnforceMaxPage(pGroup);
  25972. pcache1LeaveMutex(pGroup);
  25973. sqlite3_free(pCache->apHash);
  25974. sqlite3_free(pCache);
  25975. }
  25976. /*
  25977. ** This function is called during initialization (sqlite3_initialize()) to
  25978. ** install the default pluggable cache module, assuming the user has not
  25979. ** already provided an alternative.
  25980. */
  25981. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  25982. static const sqlite3_pcache_methods2 defaultMethods = {
  25983. 1, /* iVersion */
  25984. 0, /* pArg */
  25985. pcache1Init, /* xInit */
  25986. pcache1Shutdown, /* xShutdown */
  25987. pcache1Create, /* xCreate */
  25988. pcache1Cachesize, /* xCachesize */
  25989. pcache1Pagecount, /* xPagecount */
  25990. pcache1Fetch, /* xFetch */
  25991. pcache1Unpin, /* xUnpin */
  25992. pcache1Rekey, /* xRekey */
  25993. pcache1Truncate, /* xTruncate */
  25994. pcache1Destroy, /* xDestroy */
  25995. pcache1Shrink /* xShrink */
  25996. };
  25997. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  25998. }
  25999. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  26000. /*
  26001. ** This function is called to free superfluous dynamically allocated memory
  26002. ** held by the pager system. Memory in use by any SQLite pager allocated
  26003. ** by the current thread may be sqlite3_free()ed.
  26004. **
  26005. ** nReq is the number of bytes of memory required. Once this much has
  26006. ** been released, the function returns. The return value is the total number
  26007. ** of bytes of memory released.
  26008. */
  26009. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  26010. int nFree = 0;
  26011. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  26012. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  26013. if( pcache1.pStart==0 ){
  26014. PgHdr1 *p;
  26015. pcache1EnterMutex(&pcache1.grp);
  26016. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  26017. nFree += pcache1MemSize(p->page.pBuf);
  26018. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  26019. nFree += sqlite3MemSize(p);
  26020. #endif
  26021. pcache1PinPage(p);
  26022. pcache1RemoveFromHash(p);
  26023. pcache1FreePage(p);
  26024. }
  26025. pcache1LeaveMutex(&pcache1.grp);
  26026. }
  26027. return nFree;
  26028. }
  26029. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  26030. #ifdef SQLITE_TEST
  26031. /*
  26032. ** This function is used by test procedures to inspect the internal state
  26033. ** of the global cache.
  26034. */
  26035. SQLITE_PRIVATE void sqlite3PcacheStats(
  26036. int *pnCurrent, /* OUT: Total number of pages cached */
  26037. int *pnMax, /* OUT: Global maximum cache size */
  26038. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  26039. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  26040. ){
  26041. PgHdr1 *p;
  26042. int nRecyclable = 0;
  26043. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  26044. nRecyclable++;
  26045. }
  26046. *pnCurrent = pcache1.grp.nCurrentPage;
  26047. *pnMax = (int)pcache1.grp.nMaxPage;
  26048. *pnMin = (int)pcache1.grp.nMinPage;
  26049. *pnRecyclable = nRecyclable;
  26050. }
  26051. #endif
  26052. /************** End of pcache1.c *********************************************/
  26053. /************** Begin file rowset.c ******************************************/
  26054. /*
  26055. ** 2008 December 3
  26056. **
  26057. ** The author disclaims copyright to this source code. In place of
  26058. ** a legal notice, here is a blessing:
  26059. **
  26060. ** May you do good and not evil.
  26061. ** May you find forgiveness for yourself and forgive others.
  26062. ** May you share freely, never taking more than you give.
  26063. **
  26064. *************************************************************************
  26065. **
  26066. ** This module implements an object we call a "RowSet".
  26067. **
  26068. ** The RowSet object is a collection of rowids. Rowids
  26069. ** are inserted into the RowSet in an arbitrary order. Inserts
  26070. ** can be intermixed with tests to see if a given rowid has been
  26071. ** previously inserted into the RowSet.
  26072. **
  26073. ** After all inserts are finished, it is possible to extract the
  26074. ** elements of the RowSet in sorted order. Once this extraction
  26075. ** process has started, no new elements may be inserted.
  26076. **
  26077. ** Hence, the primitive operations for a RowSet are:
  26078. **
  26079. ** CREATE
  26080. ** INSERT
  26081. ** TEST
  26082. ** SMALLEST
  26083. ** DESTROY
  26084. **
  26085. ** The CREATE and DESTROY primitives are the constructor and destructor,
  26086. ** obviously. The INSERT primitive adds a new element to the RowSet.
  26087. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  26088. ** extracts the least value from the RowSet.
  26089. **
  26090. ** The INSERT primitive might allocate additional memory. Memory is
  26091. ** allocated in chunks so most INSERTs do no allocation. There is an
  26092. ** upper bound on the size of allocated memory. No memory is freed
  26093. ** until DESTROY.
  26094. **
  26095. ** The TEST primitive includes a "batch" number. The TEST primitive
  26096. ** will only see elements that were inserted before the last change
  26097. ** in the batch number. In other words, if an INSERT occurs between
  26098. ** two TESTs where the TESTs have the same batch nubmer, then the
  26099. ** value added by the INSERT will not be visible to the second TEST.
  26100. ** The initial batch number is zero, so if the very first TEST contains
  26101. ** a non-zero batch number, it will see all prior INSERTs.
  26102. **
  26103. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  26104. ** that is attempted.
  26105. **
  26106. ** The cost of an INSERT is roughly constant. (Sometime new memory
  26107. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  26108. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  26109. ** The cost of a TEST using the same batch number is O(logN). The cost
  26110. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  26111. ** primitives are constant time. The cost of DESTROY is O(N).
  26112. **
  26113. ** There is an added cost of O(N) when switching between TEST and
  26114. ** SMALLEST primitives.
  26115. */
  26116. /*
  26117. ** Target size for allocation chunks.
  26118. */
  26119. #define ROWSET_ALLOCATION_SIZE 1024
  26120. /*
  26121. ** The number of rowset entries per allocation chunk.
  26122. */
  26123. #define ROWSET_ENTRY_PER_CHUNK \
  26124. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  26125. /*
  26126. ** Each entry in a RowSet is an instance of the following object.
  26127. **
  26128. ** This same object is reused to store a linked list of trees of RowSetEntry
  26129. ** objects. In that alternative use, pRight points to the next entry
  26130. ** in the list, pLeft points to the tree, and v is unused. The
  26131. ** RowSet.pForest value points to the head of this forest list.
  26132. */
  26133. struct RowSetEntry {
  26134. i64 v; /* ROWID value for this entry */
  26135. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  26136. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  26137. };
  26138. /*
  26139. ** RowSetEntry objects are allocated in large chunks (instances of the
  26140. ** following structure) to reduce memory allocation overhead. The
  26141. ** chunks are kept on a linked list so that they can be deallocated
  26142. ** when the RowSet is destroyed.
  26143. */
  26144. struct RowSetChunk {
  26145. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  26146. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  26147. };
  26148. /*
  26149. ** A RowSet in an instance of the following structure.
  26150. **
  26151. ** A typedef of this structure if found in sqliteInt.h.
  26152. */
  26153. struct RowSet {
  26154. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  26155. sqlite3 *db; /* The database connection */
  26156. struct RowSetEntry *pEntry; /* List of entries using pRight */
  26157. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  26158. struct RowSetEntry *pFresh; /* Source of new entry objects */
  26159. struct RowSetEntry *pForest; /* List of binary trees of entries */
  26160. u16 nFresh; /* Number of objects on pFresh */
  26161. u8 rsFlags; /* Various flags */
  26162. u8 iBatch; /* Current insert batch */
  26163. };
  26164. /*
  26165. ** Allowed values for RowSet.rsFlags
  26166. */
  26167. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  26168. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  26169. /*
  26170. ** Turn bulk memory into a RowSet object. N bytes of memory
  26171. ** are available at pSpace. The db pointer is used as a memory context
  26172. ** for any subsequent allocations that need to occur.
  26173. ** Return a pointer to the new RowSet object.
  26174. **
  26175. ** It must be the case that N is sufficient to make a Rowset. If not
  26176. ** an assertion fault occurs.
  26177. **
  26178. ** If N is larger than the minimum, use the surplus as an initial
  26179. ** allocation of entries available to be filled.
  26180. */
  26181. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  26182. RowSet *p;
  26183. assert( N >= ROUND8(sizeof(*p)) );
  26184. p = pSpace;
  26185. p->pChunk = 0;
  26186. p->db = db;
  26187. p->pEntry = 0;
  26188. p->pLast = 0;
  26189. p->pForest = 0;
  26190. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  26191. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  26192. p->rsFlags = ROWSET_SORTED;
  26193. p->iBatch = 0;
  26194. return p;
  26195. }
  26196. /*
  26197. ** Deallocate all chunks from a RowSet. This frees all memory that
  26198. ** the RowSet has allocated over its lifetime. This routine is
  26199. ** the destructor for the RowSet.
  26200. */
  26201. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  26202. struct RowSetChunk *pChunk, *pNextChunk;
  26203. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  26204. pNextChunk = pChunk->pNextChunk;
  26205. sqlite3DbFree(p->db, pChunk);
  26206. }
  26207. p->pChunk = 0;
  26208. p->nFresh = 0;
  26209. p->pEntry = 0;
  26210. p->pLast = 0;
  26211. p->pForest = 0;
  26212. p->rsFlags = ROWSET_SORTED;
  26213. }
  26214. /*
  26215. ** Allocate a new RowSetEntry object that is associated with the
  26216. ** given RowSet. Return a pointer to the new and completely uninitialized
  26217. ** objected.
  26218. **
  26219. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  26220. ** routine returns NULL.
  26221. */
  26222. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  26223. assert( p!=0 );
  26224. if( p->nFresh==0 ){
  26225. struct RowSetChunk *pNew;
  26226. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  26227. if( pNew==0 ){
  26228. return 0;
  26229. }
  26230. pNew->pNextChunk = p->pChunk;
  26231. p->pChunk = pNew;
  26232. p->pFresh = pNew->aEntry;
  26233. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  26234. }
  26235. p->nFresh--;
  26236. return p->pFresh++;
  26237. }
  26238. /*
  26239. ** Insert a new value into a RowSet.
  26240. **
  26241. ** The mallocFailed flag of the database connection is set if a
  26242. ** memory allocation fails.
  26243. */
  26244. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  26245. struct RowSetEntry *pEntry; /* The new entry */
  26246. struct RowSetEntry *pLast; /* The last prior entry */
  26247. /* This routine is never called after sqlite3RowSetNext() */
  26248. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  26249. pEntry = rowSetEntryAlloc(p);
  26250. if( pEntry==0 ) return;
  26251. pEntry->v = rowid;
  26252. pEntry->pRight = 0;
  26253. pLast = p->pLast;
  26254. if( pLast ){
  26255. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  26256. p->rsFlags &= ~ROWSET_SORTED;
  26257. }
  26258. pLast->pRight = pEntry;
  26259. }else{
  26260. p->pEntry = pEntry;
  26261. }
  26262. p->pLast = pEntry;
  26263. }
  26264. /*
  26265. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  26266. **
  26267. ** The input lists are connected via pRight pointers and are
  26268. ** assumed to each already be in sorted order.
  26269. */
  26270. static struct RowSetEntry *rowSetEntryMerge(
  26271. struct RowSetEntry *pA, /* First sorted list to be merged */
  26272. struct RowSetEntry *pB /* Second sorted list to be merged */
  26273. ){
  26274. struct RowSetEntry head;
  26275. struct RowSetEntry *pTail;
  26276. pTail = &head;
  26277. while( pA && pB ){
  26278. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  26279. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  26280. if( pA->v<pB->v ){
  26281. pTail->pRight = pA;
  26282. pA = pA->pRight;
  26283. pTail = pTail->pRight;
  26284. }else if( pB->v<pA->v ){
  26285. pTail->pRight = pB;
  26286. pB = pB->pRight;
  26287. pTail = pTail->pRight;
  26288. }else{
  26289. pA = pA->pRight;
  26290. }
  26291. }
  26292. if( pA ){
  26293. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  26294. pTail->pRight = pA;
  26295. }else{
  26296. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  26297. pTail->pRight = pB;
  26298. }
  26299. return head.pRight;
  26300. }
  26301. /*
  26302. ** Sort all elements on the list of RowSetEntry objects into order of
  26303. ** increasing v.
  26304. */
  26305. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  26306. unsigned int i;
  26307. struct RowSetEntry *pNext, *aBucket[40];
  26308. memset(aBucket, 0, sizeof(aBucket));
  26309. while( pIn ){
  26310. pNext = pIn->pRight;
  26311. pIn->pRight = 0;
  26312. for(i=0; aBucket[i]; i++){
  26313. pIn = rowSetEntryMerge(aBucket[i], pIn);
  26314. aBucket[i] = 0;
  26315. }
  26316. aBucket[i] = pIn;
  26317. pIn = pNext;
  26318. }
  26319. pIn = 0;
  26320. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  26321. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  26322. }
  26323. return pIn;
  26324. }
  26325. /*
  26326. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  26327. ** Convert this tree into a linked list connected by the pRight pointers
  26328. ** and return pointers to the first and last elements of the new list.
  26329. */
  26330. static void rowSetTreeToList(
  26331. struct RowSetEntry *pIn, /* Root of the input tree */
  26332. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  26333. struct RowSetEntry **ppLast /* Write tail of the output list here */
  26334. ){
  26335. assert( pIn!=0 );
  26336. if( pIn->pLeft ){
  26337. struct RowSetEntry *p;
  26338. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  26339. p->pRight = pIn;
  26340. }else{
  26341. *ppFirst = pIn;
  26342. }
  26343. if( pIn->pRight ){
  26344. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  26345. }else{
  26346. *ppLast = pIn;
  26347. }
  26348. assert( (*ppLast)->pRight==0 );
  26349. }
  26350. /*
  26351. ** Convert a sorted list of elements (connected by pRight) into a binary
  26352. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  26353. ** node taken from the head of *ppList. A depth of 2 means a tree with
  26354. ** three nodes. And so forth.
  26355. **
  26356. ** Use as many entries from the input list as required and update the
  26357. ** *ppList to point to the unused elements of the list. If the input
  26358. ** list contains too few elements, then construct an incomplete tree
  26359. ** and leave *ppList set to NULL.
  26360. **
  26361. ** Return a pointer to the root of the constructed binary tree.
  26362. */
  26363. static struct RowSetEntry *rowSetNDeepTree(
  26364. struct RowSetEntry **ppList,
  26365. int iDepth
  26366. ){
  26367. struct RowSetEntry *p; /* Root of the new tree */
  26368. struct RowSetEntry *pLeft; /* Left subtree */
  26369. if( *ppList==0 ){
  26370. return 0;
  26371. }
  26372. if( iDepth==1 ){
  26373. p = *ppList;
  26374. *ppList = p->pRight;
  26375. p->pLeft = p->pRight = 0;
  26376. return p;
  26377. }
  26378. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  26379. p = *ppList;
  26380. if( p==0 ){
  26381. return pLeft;
  26382. }
  26383. p->pLeft = pLeft;
  26384. *ppList = p->pRight;
  26385. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  26386. return p;
  26387. }
  26388. /*
  26389. ** Convert a sorted list of elements into a binary tree. Make the tree
  26390. ** as deep as it needs to be in order to contain the entire list.
  26391. */
  26392. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  26393. int iDepth; /* Depth of the tree so far */
  26394. struct RowSetEntry *p; /* Current tree root */
  26395. struct RowSetEntry *pLeft; /* Left subtree */
  26396. assert( pList!=0 );
  26397. p = pList;
  26398. pList = p->pRight;
  26399. p->pLeft = p->pRight = 0;
  26400. for(iDepth=1; pList; iDepth++){
  26401. pLeft = p;
  26402. p = pList;
  26403. pList = p->pRight;
  26404. p->pLeft = pLeft;
  26405. p->pRight = rowSetNDeepTree(&pList, iDepth);
  26406. }
  26407. return p;
  26408. }
  26409. /*
  26410. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  26411. ** sort them all together into one big ordered list on p->pEntry.
  26412. **
  26413. ** This routine should only be called once in the life of a RowSet.
  26414. */
  26415. static void rowSetToList(RowSet *p){
  26416. /* This routine is called only once */
  26417. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  26418. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  26419. p->pEntry = rowSetEntrySort(p->pEntry);
  26420. }
  26421. /* While this module could theoretically support it, sqlite3RowSetNext()
  26422. ** is never called after sqlite3RowSetText() for the same RowSet. So
  26423. ** there is never a forest to deal with. Should this change, simply
  26424. ** remove the assert() and the #if 0. */
  26425. assert( p->pForest==0 );
  26426. #if 0
  26427. while( p->pForest ){
  26428. struct RowSetEntry *pTree = p->pForest->pLeft;
  26429. if( pTree ){
  26430. struct RowSetEntry *pHead, *pTail;
  26431. rowSetTreeToList(pTree, &pHead, &pTail);
  26432. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  26433. }
  26434. p->pForest = p->pForest->pRight;
  26435. }
  26436. #endif
  26437. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  26438. }
  26439. /*
  26440. ** Extract the smallest element from the RowSet.
  26441. ** Write the element into *pRowid. Return 1 on success. Return
  26442. ** 0 if the RowSet is already empty.
  26443. **
  26444. ** After this routine has been called, the sqlite3RowSetInsert()
  26445. ** routine may not be called again.
  26446. */
  26447. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  26448. assert( p!=0 );
  26449. /* Merge the forest into a single sorted list on first call */
  26450. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  26451. /* Return the next entry on the list */
  26452. if( p->pEntry ){
  26453. *pRowid = p->pEntry->v;
  26454. p->pEntry = p->pEntry->pRight;
  26455. if( p->pEntry==0 ){
  26456. sqlite3RowSetClear(p);
  26457. }
  26458. return 1;
  26459. }else{
  26460. return 0;
  26461. }
  26462. }
  26463. /*
  26464. ** Check to see if element iRowid was inserted into the rowset as
  26465. ** part of any insert batch prior to iBatch. Return 1 or 0.
  26466. **
  26467. ** If this is the first test of a new batch and if there exist entires
  26468. ** on pRowSet->pEntry, then sort those entires into the forest at
  26469. ** pRowSet->pForest so that they can be tested.
  26470. */
  26471. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  26472. struct RowSetEntry *p, *pTree;
  26473. /* This routine is never called after sqlite3RowSetNext() */
  26474. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  26475. /* Sort entries into the forest on the first test of a new batch
  26476. */
  26477. if( iBatch!=pRowSet->iBatch ){
  26478. p = pRowSet->pEntry;
  26479. if( p ){
  26480. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  26481. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  26482. p = rowSetEntrySort(p);
  26483. }
  26484. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  26485. ppPrevTree = &pTree->pRight;
  26486. if( pTree->pLeft==0 ){
  26487. pTree->pLeft = rowSetListToTree(p);
  26488. break;
  26489. }else{
  26490. struct RowSetEntry *pAux, *pTail;
  26491. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  26492. pTree->pLeft = 0;
  26493. p = rowSetEntryMerge(pAux, p);
  26494. }
  26495. }
  26496. if( pTree==0 ){
  26497. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  26498. if( pTree ){
  26499. pTree->v = 0;
  26500. pTree->pRight = 0;
  26501. pTree->pLeft = rowSetListToTree(p);
  26502. }
  26503. }
  26504. pRowSet->pEntry = 0;
  26505. pRowSet->pLast = 0;
  26506. pRowSet->rsFlags |= ROWSET_SORTED;
  26507. }
  26508. pRowSet->iBatch = iBatch;
  26509. }
  26510. /* Test to see if the iRowid value appears anywhere in the forest.
  26511. ** Return 1 if it does and 0 if not.
  26512. */
  26513. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  26514. p = pTree->pLeft;
  26515. while( p ){
  26516. if( p->v<iRowid ){
  26517. p = p->pRight;
  26518. }else if( p->v>iRowid ){
  26519. p = p->pLeft;
  26520. }else{
  26521. return 1;
  26522. }
  26523. }
  26524. }
  26525. return 0;
  26526. }
  26527. /************** End of rowset.c **********************************************/
  26528. /************** Begin file pager.c *******************************************/
  26529. /*
  26530. ** 2001 September 15
  26531. **
  26532. ** The author disclaims copyright to this source code. In place of
  26533. ** a legal notice, here is a blessing:
  26534. **
  26535. ** May you do good and not evil.
  26536. ** May you find forgiveness for yourself and forgive others.
  26537. ** May you share freely, never taking more than you give.
  26538. **
  26539. *************************************************************************
  26540. ** This is the implementation of the page cache subsystem or "pager".
  26541. **
  26542. ** The pager is used to access a database disk file. It implements
  26543. ** atomic commit and rollback through the use of a journal file that
  26544. ** is separate from the database file. The pager also implements file
  26545. ** locking to prevent two processes from writing the same database
  26546. ** file simultaneously, or one process from reading the database while
  26547. ** another is writing.
  26548. */
  26549. #ifndef SQLITE_OMIT_DISKIO
  26550. /************** Include wal.h in the middle of pager.c ***********************/
  26551. /************** Begin file wal.h *********************************************/
  26552. /*
  26553. ** 2010 February 1
  26554. **
  26555. ** The author disclaims copyright to this source code. In place of
  26556. ** a legal notice, here is a blessing:
  26557. **
  26558. ** May you do good and not evil.
  26559. ** May you find forgiveness for yourself and forgive others.
  26560. ** May you share freely, never taking more than you give.
  26561. **
  26562. *************************************************************************
  26563. ** This header file defines the interface to the write-ahead logging
  26564. ** system. Refer to the comments below and the header comment attached to
  26565. ** the implementation of each function in log.c for further details.
  26566. */
  26567. #ifndef _WAL_H_
  26568. #define _WAL_H_
  26569. /* Additional values that can be added to the sync_flags argument of
  26570. ** sqlite3WalFrames():
  26571. */
  26572. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  26573. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  26574. #ifdef SQLITE_OMIT_WAL
  26575. # define sqlite3WalOpen(x,y,z) 0
  26576. # define sqlite3WalLimit(x,y)
  26577. # define sqlite3WalClose(w,x,y,z) 0
  26578. # define sqlite3WalBeginReadTransaction(y,z) 0
  26579. # define sqlite3WalEndReadTransaction(z)
  26580. # define sqlite3WalDbsize(y) 0
  26581. # define sqlite3WalBeginWriteTransaction(y) 0
  26582. # define sqlite3WalEndWriteTransaction(x) 0
  26583. # define sqlite3WalUndo(x,y,z) 0
  26584. # define sqlite3WalSavepoint(y,z)
  26585. # define sqlite3WalSavepointUndo(y,z) 0
  26586. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  26587. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  26588. # define sqlite3WalCallback(z) 0
  26589. # define sqlite3WalExclusiveMode(y,z) 0
  26590. # define sqlite3WalHeapMemory(z) 0
  26591. # define sqlite3WalFramesize(z) 0
  26592. # define sqlite3WalFindFrame(x,y,z) 0
  26593. #else
  26594. #define WAL_SAVEPOINT_NDATA 4
  26595. /* Connection to a write-ahead log (WAL) file.
  26596. ** There is one object of this type for each pager.
  26597. */
  26598. typedef struct Wal Wal;
  26599. /* Open and close a connection to a write-ahead log. */
  26600. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  26601. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  26602. /* Set the limiting size of a WAL file. */
  26603. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  26604. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  26605. ** snapshot is like a read-transaction. It is the state of the database
  26606. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  26607. ** preserves the current state even if the other threads or processes
  26608. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  26609. ** transaction and releases the lock.
  26610. */
  26611. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  26612. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  26613. /* Read a page from the write-ahead log, if it is present. */
  26614. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  26615. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  26616. /* If the WAL is not empty, return the size of the database. */
  26617. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  26618. /* Obtain or release the WRITER lock. */
  26619. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  26620. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  26621. /* Undo any frames written (but not committed) to the log */
  26622. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  26623. /* Return an integer that records the current (uncommitted) write
  26624. ** position in the WAL */
  26625. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  26626. /* Move the write position of the WAL back to iFrame. Called in
  26627. ** response to a ROLLBACK TO command. */
  26628. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  26629. /* Write a frame or frames to the log. */
  26630. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  26631. /* Copy pages from the log to the database file */
  26632. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  26633. Wal *pWal, /* Write-ahead log connection */
  26634. int eMode, /* One of PASSIVE, FULL and RESTART */
  26635. int (*xBusy)(void*), /* Function to call when busy */
  26636. void *pBusyArg, /* Context argument for xBusyHandler */
  26637. int sync_flags, /* Flags to sync db file with (or 0) */
  26638. int nBuf, /* Size of buffer nBuf */
  26639. u8 *zBuf, /* Temporary buffer to use */
  26640. int *pnLog, /* OUT: Number of frames in WAL */
  26641. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  26642. );
  26643. /* Return the value to pass to a sqlite3_wal_hook callback, the
  26644. ** number of frames in the WAL at the point of the last commit since
  26645. ** sqlite3WalCallback() was called. If no commits have occurred since
  26646. ** the last call, then return 0.
  26647. */
  26648. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  26649. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  26650. ** by the pager layer on the database file.
  26651. */
  26652. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  26653. /* Return true if the argument is non-NULL and the WAL module is using
  26654. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  26655. ** WAL module is using shared-memory, return false.
  26656. */
  26657. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  26658. #ifdef SQLITE_ENABLE_ZIPVFS
  26659. /* If the WAL file is not empty, return the number of bytes of content
  26660. ** stored in each frame (i.e. the db page-size when the WAL was created).
  26661. */
  26662. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  26663. #endif
  26664. #endif /* ifndef SQLITE_OMIT_WAL */
  26665. #endif /* _WAL_H_ */
  26666. /************** End of wal.h *************************************************/
  26667. /************** Continuing where we left off in pager.c **********************/
  26668. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  26669. **
  26670. ** This comment block describes invariants that hold when using a rollback
  26671. ** journal. These invariants do not apply for journal_mode=WAL,
  26672. ** journal_mode=MEMORY, or journal_mode=OFF.
  26673. **
  26674. ** Within this comment block, a page is deemed to have been synced
  26675. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  26676. ** Otherwise, the page is not synced until the xSync method of the VFS
  26677. ** is called successfully on the file containing the page.
  26678. **
  26679. ** Definition: A page of the database file is said to be "overwriteable" if
  26680. ** one or more of the following are true about the page:
  26681. **
  26682. ** (a) The original content of the page as it was at the beginning of
  26683. ** the transaction has been written into the rollback journal and
  26684. ** synced.
  26685. **
  26686. ** (b) The page was a freelist leaf page at the start of the transaction.
  26687. **
  26688. ** (c) The page number is greater than the largest page that existed in
  26689. ** the database file at the start of the transaction.
  26690. **
  26691. ** (1) A page of the database file is never overwritten unless one of the
  26692. ** following are true:
  26693. **
  26694. ** (a) The page and all other pages on the same sector are overwriteable.
  26695. **
  26696. ** (b) The atomic page write optimization is enabled, and the entire
  26697. ** transaction other than the update of the transaction sequence
  26698. ** number consists of a single page change.
  26699. **
  26700. ** (2) The content of a page written into the rollback journal exactly matches
  26701. ** both the content in the database when the rollback journal was written
  26702. ** and the content in the database at the beginning of the current
  26703. ** transaction.
  26704. **
  26705. ** (3) Writes to the database file are an integer multiple of the page size
  26706. ** in length and are aligned on a page boundary.
  26707. **
  26708. ** (4) Reads from the database file are either aligned on a page boundary and
  26709. ** an integer multiple of the page size in length or are taken from the
  26710. ** first 100 bytes of the database file.
  26711. **
  26712. ** (5) All writes to the database file are synced prior to the rollback journal
  26713. ** being deleted, truncated, or zeroed.
  26714. **
  26715. ** (6) If a master journal file is used, then all writes to the database file
  26716. ** are synced prior to the master journal being deleted.
  26717. **
  26718. ** Definition: Two databases (or the same database at two points it time)
  26719. ** are said to be "logically equivalent" if they give the same answer to
  26720. ** all queries. Note in particular the content of freelist leaf
  26721. ** pages can be changed arbitarily without effecting the logical equivalence
  26722. ** of the database.
  26723. **
  26724. ** (7) At any time, if any subset, including the empty set and the total set,
  26725. ** of the unsynced changes to a rollback journal are removed and the
  26726. ** journal is rolled back, the resulting database file will be logical
  26727. ** equivalent to the database file at the beginning of the transaction.
  26728. **
  26729. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  26730. ** is called to restore the database file to the same size it was at
  26731. ** the beginning of the transaction. (In some VFSes, the xTruncate
  26732. ** method is a no-op, but that does not change the fact the SQLite will
  26733. ** invoke it.)
  26734. **
  26735. ** (9) Whenever the database file is modified, at least one bit in the range
  26736. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  26737. ** the EXCLUSIVE lock, thus signaling other connections on the same
  26738. ** database to flush their caches.
  26739. **
  26740. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  26741. ** than one billion transactions.
  26742. **
  26743. ** (11) A database file is well-formed at the beginning and at the conclusion
  26744. ** of every transaction.
  26745. **
  26746. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  26747. ** the database file.
  26748. **
  26749. ** (13) A SHARED lock is held on the database file while reading any
  26750. ** content out of the database file.
  26751. **
  26752. ******************************************************************************/
  26753. /*
  26754. ** Macros for troubleshooting. Normally turned off
  26755. */
  26756. #if 0
  26757. int sqlite3PagerTrace=1; /* True to enable tracing */
  26758. #define sqlite3DebugPrintf printf
  26759. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  26760. #else
  26761. #define PAGERTRACE(X)
  26762. #endif
  26763. /*
  26764. ** The following two macros are used within the PAGERTRACE() macros above
  26765. ** to print out file-descriptors.
  26766. **
  26767. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  26768. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  26769. ** struct as its argument.
  26770. */
  26771. #define PAGERID(p) ((int)(p->fd))
  26772. #define FILEHANDLEID(fd) ((int)fd)
  26773. /*
  26774. ** The Pager.eState variable stores the current 'state' of a pager. A
  26775. ** pager may be in any one of the seven states shown in the following
  26776. ** state diagram.
  26777. **
  26778. ** OPEN <------+------+
  26779. ** | | |
  26780. ** V | |
  26781. ** +---------> READER-------+ |
  26782. ** | | |
  26783. ** | V |
  26784. ** |<-------WRITER_LOCKED------> ERROR
  26785. ** | | ^
  26786. ** | V |
  26787. ** |<------WRITER_CACHEMOD-------->|
  26788. ** | | |
  26789. ** | V |
  26790. ** |<-------WRITER_DBMOD---------->|
  26791. ** | | |
  26792. ** | V |
  26793. ** +<------WRITER_FINISHED-------->+
  26794. **
  26795. **
  26796. ** List of state transitions and the C [function] that performs each:
  26797. **
  26798. ** OPEN -> READER [sqlite3PagerSharedLock]
  26799. ** READER -> OPEN [pager_unlock]
  26800. **
  26801. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  26802. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  26803. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  26804. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  26805. ** WRITER_*** -> READER [pager_end_transaction]
  26806. **
  26807. ** WRITER_*** -> ERROR [pager_error]
  26808. ** ERROR -> OPEN [pager_unlock]
  26809. **
  26810. **
  26811. ** OPEN:
  26812. **
  26813. ** The pager starts up in this state. Nothing is guaranteed in this
  26814. ** state - the file may or may not be locked and the database size is
  26815. ** unknown. The database may not be read or written.
  26816. **
  26817. ** * No read or write transaction is active.
  26818. ** * Any lock, or no lock at all, may be held on the database file.
  26819. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  26820. **
  26821. ** READER:
  26822. **
  26823. ** In this state all the requirements for reading the database in
  26824. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  26825. ** was) in exclusive-locking mode, a user-level read transaction is
  26826. ** open. The database size is known in this state.
  26827. **
  26828. ** A connection running with locking_mode=normal enters this state when
  26829. ** it opens a read-transaction on the database and returns to state
  26830. ** OPEN after the read-transaction is completed. However a connection
  26831. ** running in locking_mode=exclusive (including temp databases) remains in
  26832. ** this state even after the read-transaction is closed. The only way
  26833. ** a locking_mode=exclusive connection can transition from READER to OPEN
  26834. ** is via the ERROR state (see below).
  26835. **
  26836. ** * A read transaction may be active (but a write-transaction cannot).
  26837. ** * A SHARED or greater lock is held on the database file.
  26838. ** * The dbSize variable may be trusted (even if a user-level read
  26839. ** transaction is not active). The dbOrigSize and dbFileSize variables
  26840. ** may not be trusted at this point.
  26841. ** * If the database is a WAL database, then the WAL connection is open.
  26842. ** * Even if a read-transaction is not open, it is guaranteed that
  26843. ** there is no hot-journal in the file-system.
  26844. **
  26845. ** WRITER_LOCKED:
  26846. **
  26847. ** The pager moves to this state from READER when a write-transaction
  26848. ** is first opened on the database. In WRITER_LOCKED state, all locks
  26849. ** required to start a write-transaction are held, but no actual
  26850. ** modifications to the cache or database have taken place.
  26851. **
  26852. ** In rollback mode, a RESERVED or (if the transaction was opened with
  26853. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  26854. ** moving to this state, but the journal file is not written to or opened
  26855. ** to in this state. If the transaction is committed or rolled back while
  26856. ** in WRITER_LOCKED state, all that is required is to unlock the database
  26857. ** file.
  26858. **
  26859. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  26860. ** If the connection is running with locking_mode=exclusive, an attempt
  26861. ** is made to obtain an EXCLUSIVE lock on the database file.
  26862. **
  26863. ** * A write transaction is active.
  26864. ** * If the connection is open in rollback-mode, a RESERVED or greater
  26865. ** lock is held on the database file.
  26866. ** * If the connection is open in WAL-mode, a WAL write transaction
  26867. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  26868. ** called).
  26869. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  26870. ** * The contents of the pager cache have not been modified.
  26871. ** * The journal file may or may not be open.
  26872. ** * Nothing (not even the first header) has been written to the journal.
  26873. **
  26874. ** WRITER_CACHEMOD:
  26875. **
  26876. ** A pager moves from WRITER_LOCKED state to this state when a page is
  26877. ** first modified by the upper layer. In rollback mode the journal file
  26878. ** is opened (if it is not already open) and a header written to the
  26879. ** start of it. The database file on disk has not been modified.
  26880. **
  26881. ** * A write transaction is active.
  26882. ** * A RESERVED or greater lock is held on the database file.
  26883. ** * The journal file is open and the first header has been written
  26884. ** to it, but the header has not been synced to disk.
  26885. ** * The contents of the page cache have been modified.
  26886. **
  26887. ** WRITER_DBMOD:
  26888. **
  26889. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  26890. ** when it modifies the contents of the database file. WAL connections
  26891. ** never enter this state (since they do not modify the database file,
  26892. ** just the log file).
  26893. **
  26894. ** * A write transaction is active.
  26895. ** * An EXCLUSIVE or greater lock is held on the database file.
  26896. ** * The journal file is open and the first header has been written
  26897. ** and synced to disk.
  26898. ** * The contents of the page cache have been modified (and possibly
  26899. ** written to disk).
  26900. **
  26901. ** WRITER_FINISHED:
  26902. **
  26903. ** It is not possible for a WAL connection to enter this state.
  26904. **
  26905. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  26906. ** state after the entire transaction has been successfully written into the
  26907. ** database file. In this state the transaction may be committed simply
  26908. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  26909. ** not possible to modify the database further. At this point, the upper
  26910. ** layer must either commit or rollback the transaction.
  26911. **
  26912. ** * A write transaction is active.
  26913. ** * An EXCLUSIVE or greater lock is held on the database file.
  26914. ** * All writing and syncing of journal and database data has finished.
  26915. ** If no error occurred, all that remains is to finalize the journal to
  26916. ** commit the transaction. If an error did occur, the caller will need
  26917. ** to rollback the transaction.
  26918. **
  26919. ** ERROR:
  26920. **
  26921. ** The ERROR state is entered when an IO or disk-full error (including
  26922. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  26923. ** difficult to be sure that the in-memory pager state (cache contents,
  26924. ** db size etc.) are consistent with the contents of the file-system.
  26925. **
  26926. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  26927. ** cannot.
  26928. **
  26929. ** For example, if an IO error occurs while performing a rollback,
  26930. ** the contents of the page-cache may be left in an inconsistent state.
  26931. ** At this point it would be dangerous to change back to READER state
  26932. ** (as usually happens after a rollback). Any subsequent readers might
  26933. ** report database corruption (due to the inconsistent cache), and if
  26934. ** they upgrade to writers, they may inadvertently corrupt the database
  26935. ** file. To avoid this hazard, the pager switches into the ERROR state
  26936. ** instead of READER following such an error.
  26937. **
  26938. ** Once it has entered the ERROR state, any attempt to use the pager
  26939. ** to read or write data returns an error. Eventually, once all
  26940. ** outstanding transactions have been abandoned, the pager is able to
  26941. ** transition back to OPEN state, discarding the contents of the
  26942. ** page-cache and any other in-memory state at the same time. Everything
  26943. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  26944. ** when a read-transaction is next opened on the pager (transitioning
  26945. ** the pager into READER state). At that point the system has recovered
  26946. ** from the error.
  26947. **
  26948. ** Specifically, the pager jumps into the ERROR state if:
  26949. **
  26950. ** 1. An error occurs while attempting a rollback. This happens in
  26951. ** function sqlite3PagerRollback().
  26952. **
  26953. ** 2. An error occurs while attempting to finalize a journal file
  26954. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  26955. **
  26956. ** 3. An error occurs while attempting to write to the journal or
  26957. ** database file in function pagerStress() in order to free up
  26958. ** memory.
  26959. **
  26960. ** In other cases, the error is returned to the b-tree layer. The b-tree
  26961. ** layer then attempts a rollback operation. If the error condition
  26962. ** persists, the pager enters the ERROR state via condition (1) above.
  26963. **
  26964. ** Condition (3) is necessary because it can be triggered by a read-only
  26965. ** statement executed within a transaction. In this case, if the error
  26966. ** code were simply returned to the user, the b-tree layer would not
  26967. ** automatically attempt a rollback, as it assumes that an error in a
  26968. ** read-only statement cannot leave the pager in an internally inconsistent
  26969. ** state.
  26970. **
  26971. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  26972. ** * There are one or more outstanding references to pages (after the
  26973. ** last reference is dropped the pager should move back to OPEN state).
  26974. ** * The pager is not an in-memory pager.
  26975. **
  26976. **
  26977. ** Notes:
  26978. **
  26979. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  26980. ** connection is open in WAL mode. A WAL connection is always in one
  26981. ** of the first four states.
  26982. **
  26983. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  26984. ** state. There are two exceptions: immediately after exclusive-mode has
  26985. ** been turned on (and before any read or write transactions are
  26986. ** executed), and when the pager is leaving the "error state".
  26987. **
  26988. ** * See also: assert_pager_state().
  26989. */
  26990. #define PAGER_OPEN 0
  26991. #define PAGER_READER 1
  26992. #define PAGER_WRITER_LOCKED 2
  26993. #define PAGER_WRITER_CACHEMOD 3
  26994. #define PAGER_WRITER_DBMOD 4
  26995. #define PAGER_WRITER_FINISHED 5
  26996. #define PAGER_ERROR 6
  26997. /*
  26998. ** The Pager.eLock variable is almost always set to one of the
  26999. ** following locking-states, according to the lock currently held on
  27000. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  27001. ** This variable is kept up to date as locks are taken and released by
  27002. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  27003. **
  27004. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  27005. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  27006. ** the operation was successful. In these circumstances pagerLockDb() and
  27007. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  27008. ** when unlocking the file, and only updated when locking the file if the
  27009. ** VFS call is successful. This way, the Pager.eLock variable may be set
  27010. ** to a less exclusive (lower) value than the lock that is actually held
  27011. ** at the system level, but it is never set to a more exclusive value.
  27012. **
  27013. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  27014. ** be a few redundant xLock() calls or a lock may be held for longer than
  27015. ** required, but nothing really goes wrong.
  27016. **
  27017. ** The exception is when the database file is unlocked as the pager moves
  27018. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  27019. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  27020. ** transition, by the same pager or any other). If the call to xUnlock()
  27021. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  27022. ** can confuse the call to xCheckReservedLock() call made later as part
  27023. ** of hot-journal detection.
  27024. **
  27025. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  27026. ** lock held by this process or any others". So xCheckReservedLock may
  27027. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  27028. ** doesn't know it because of a previous error in xUnlock). If this happens
  27029. ** a hot-journal may be mistaken for a journal being created by an active
  27030. ** transaction in another process, causing SQLite to read from the database
  27031. ** without rolling it back.
  27032. **
  27033. ** To work around this, if a call to xUnlock() fails when unlocking the
  27034. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  27035. ** is only changed back to a real locking state after a successful call
  27036. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  27037. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  27038. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  27039. ** lock on the database file before attempting to roll it back. See function
  27040. ** PagerSharedLock() for more detail.
  27041. **
  27042. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  27043. ** PAGER_OPEN state.
  27044. */
  27045. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  27046. /*
  27047. ** A macro used for invoking the codec if there is one
  27048. */
  27049. #ifdef SQLITE_HAS_CODEC
  27050. # define CODEC1(P,D,N,X,E) \
  27051. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  27052. # define CODEC2(P,D,N,X,E,O) \
  27053. if( P->xCodec==0 ){ O=(char*)D; }else \
  27054. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  27055. #else
  27056. # define CODEC1(P,D,N,X,E) /* NO-OP */
  27057. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  27058. #endif
  27059. /*
  27060. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  27061. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  27062. ** This could conceivably cause corruption following a power failure on
  27063. ** such a system. This is currently an undocumented limit.
  27064. */
  27065. #define MAX_SECTOR_SIZE 0x10000
  27066. /*
  27067. ** An instance of the following structure is allocated for each active
  27068. ** savepoint and statement transaction in the system. All such structures
  27069. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  27070. ** resized using sqlite3Realloc().
  27071. **
  27072. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  27073. ** set to 0. If a journal-header is written into the main journal while
  27074. ** the savepoint is active, then iHdrOffset is set to the byte offset
  27075. ** immediately following the last journal record written into the main
  27076. ** journal before the journal-header. This is required during savepoint
  27077. ** rollback (see pagerPlaybackSavepoint()).
  27078. */
  27079. typedef struct PagerSavepoint PagerSavepoint;
  27080. struct PagerSavepoint {
  27081. i64 iOffset; /* Starting offset in main journal */
  27082. i64 iHdrOffset; /* See above */
  27083. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  27084. Pgno nOrig; /* Original number of pages in file */
  27085. Pgno iSubRec; /* Index of first record in sub-journal */
  27086. #ifndef SQLITE_OMIT_WAL
  27087. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  27088. #endif
  27089. };
  27090. /*
  27091. ** Bits of the Pager.doNotSpill flag. See further description below.
  27092. */
  27093. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  27094. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  27095. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  27096. /*
  27097. ** A open page cache is an instance of struct Pager. A description of
  27098. ** some of the more important member variables follows:
  27099. **
  27100. ** eState
  27101. **
  27102. ** The current 'state' of the pager object. See the comment and state
  27103. ** diagram above for a description of the pager state.
  27104. **
  27105. ** eLock
  27106. **
  27107. ** For a real on-disk database, the current lock held on the database file -
  27108. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  27109. **
  27110. ** For a temporary or in-memory database (neither of which require any
  27111. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  27112. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  27113. ** logic into thinking that it already has all the locks it will ever
  27114. ** need (and no reason to release them).
  27115. **
  27116. ** In some (obscure) circumstances, this variable may also be set to
  27117. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  27118. ** details.
  27119. **
  27120. ** changeCountDone
  27121. **
  27122. ** This boolean variable is used to make sure that the change-counter
  27123. ** (the 4-byte header field at byte offset 24 of the database file) is
  27124. ** not updated more often than necessary.
  27125. **
  27126. ** It is set to true when the change-counter field is updated, which
  27127. ** can only happen if an exclusive lock is held on the database file.
  27128. ** It is cleared (set to false) whenever an exclusive lock is
  27129. ** relinquished on the database file. Each time a transaction is committed,
  27130. ** The changeCountDone flag is inspected. If it is true, the work of
  27131. ** updating the change-counter is omitted for the current transaction.
  27132. **
  27133. ** This mechanism means that when running in exclusive mode, a connection
  27134. ** need only update the change-counter once, for the first transaction
  27135. ** committed.
  27136. **
  27137. ** setMaster
  27138. **
  27139. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  27140. ** (or may not) specify a master-journal name to be written into the
  27141. ** journal file before it is synced to disk.
  27142. **
  27143. ** Whether or not a journal file contains a master-journal pointer affects
  27144. ** the way in which the journal file is finalized after the transaction is
  27145. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  27146. ** If a journal file does not contain a master-journal pointer, it is
  27147. ** finalized by overwriting the first journal header with zeroes. If
  27148. ** it does contain a master-journal pointer the journal file is finalized
  27149. ** by truncating it to zero bytes, just as if the connection were
  27150. ** running in "journal_mode=truncate" mode.
  27151. **
  27152. ** Journal files that contain master journal pointers cannot be finalized
  27153. ** simply by overwriting the first journal-header with zeroes, as the
  27154. ** master journal pointer could interfere with hot-journal rollback of any
  27155. ** subsequently interrupted transaction that reuses the journal file.
  27156. **
  27157. ** The flag is cleared as soon as the journal file is finalized (either
  27158. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  27159. ** journal file from being successfully finalized, the setMaster flag
  27160. ** is cleared anyway (and the pager will move to ERROR state).
  27161. **
  27162. ** doNotSpill
  27163. **
  27164. ** This variables control the behavior of cache-spills (calls made by
  27165. ** the pcache module to the pagerStress() routine to write cached data
  27166. ** to the file-system in order to free up memory).
  27167. **
  27168. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  27169. ** writing to the database from pagerStress() is disabled altogether.
  27170. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  27171. ** comes up during savepoint rollback that requires the pcache module
  27172. ** to allocate a new page to prevent the journal file from being written
  27173. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  27174. ** case is a user preference.
  27175. **
  27176. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  27177. ** is permitted, but syncing the journal file is not. This flag is set
  27178. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  27179. ** the database page-size in order to prevent a journal sync from happening
  27180. ** in between the journalling of two pages on the same sector.
  27181. **
  27182. ** subjInMemory
  27183. **
  27184. ** This is a boolean variable. If true, then any required sub-journal
  27185. ** is opened as an in-memory journal file. If false, then in-memory
  27186. ** sub-journals are only used for in-memory pager files.
  27187. **
  27188. ** This variable is updated by the upper layer each time a new
  27189. ** write-transaction is opened.
  27190. **
  27191. ** dbSize, dbOrigSize, dbFileSize
  27192. **
  27193. ** Variable dbSize is set to the number of pages in the database file.
  27194. ** It is valid in PAGER_READER and higher states (all states except for
  27195. ** OPEN and ERROR).
  27196. **
  27197. ** dbSize is set based on the size of the database file, which may be
  27198. ** larger than the size of the database (the value stored at offset
  27199. ** 28 of the database header by the btree). If the size of the file
  27200. ** is not an integer multiple of the page-size, the value stored in
  27201. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  27202. ** Except, any file that is greater than 0 bytes in size is considered
  27203. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  27204. ** to dbSize==1).
  27205. **
  27206. ** During a write-transaction, if pages with page-numbers greater than
  27207. ** dbSize are modified in the cache, dbSize is updated accordingly.
  27208. ** Similarly, if the database is truncated using PagerTruncateImage(),
  27209. ** dbSize is updated.
  27210. **
  27211. ** Variables dbOrigSize and dbFileSize are valid in states
  27212. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  27213. ** variable at the start of the transaction. It is used during rollback,
  27214. ** and to determine whether or not pages need to be journalled before
  27215. ** being modified.
  27216. **
  27217. ** Throughout a write-transaction, dbFileSize contains the size of
  27218. ** the file on disk in pages. It is set to a copy of dbSize when the
  27219. ** write-transaction is first opened, and updated when VFS calls are made
  27220. ** to write or truncate the database file on disk.
  27221. **
  27222. ** The only reason the dbFileSize variable is required is to suppress
  27223. ** unnecessary calls to xTruncate() after committing a transaction. If,
  27224. ** when a transaction is committed, the dbFileSize variable indicates
  27225. ** that the database file is larger than the database image (Pager.dbSize),
  27226. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  27227. ** to measure the database file on disk, and then truncates it if required.
  27228. ** dbFileSize is not used when rolling back a transaction. In this case
  27229. ** pager_truncate() is called unconditionally (which means there may be
  27230. ** a call to xFilesize() that is not strictly required). In either case,
  27231. ** pager_truncate() may cause the file to become smaller or larger.
  27232. **
  27233. ** dbHintSize
  27234. **
  27235. ** The dbHintSize variable is used to limit the number of calls made to
  27236. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  27237. **
  27238. ** dbHintSize is set to a copy of the dbSize variable when a
  27239. ** write-transaction is opened (at the same time as dbFileSize and
  27240. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  27241. ** dbHintSize is increased to the number of pages that correspond to the
  27242. ** size-hint passed to the method call. See pager_write_pagelist() for
  27243. ** details.
  27244. **
  27245. ** errCode
  27246. **
  27247. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  27248. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  27249. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  27250. ** sub-codes.
  27251. */
  27252. struct Pager {
  27253. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  27254. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  27255. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  27256. u8 useJournal; /* Use a rollback journal on this file */
  27257. u8 noSync; /* Do not sync the journal if true */
  27258. u8 fullSync; /* Do extra syncs of the journal for robustness */
  27259. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  27260. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  27261. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  27262. u8 tempFile; /* zFilename is a temporary file */
  27263. u8 readOnly; /* True for a read-only database */
  27264. u8 memDb; /* True to inhibit all file I/O */
  27265. /**************************************************************************
  27266. ** The following block contains those class members that change during
  27267. ** routine opertion. Class members not in this block are either fixed
  27268. ** when the pager is first created or else only change when there is a
  27269. ** significant mode change (such as changing the page_size, locking_mode,
  27270. ** or the journal_mode). From another view, these class members describe
  27271. ** the "state" of the pager, while other class members describe the
  27272. ** "configuration" of the pager.
  27273. */
  27274. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  27275. u8 eLock; /* Current lock held on database file */
  27276. u8 changeCountDone; /* Set after incrementing the change-counter */
  27277. u8 setMaster; /* True if a m-j name has been written to jrnl */
  27278. u8 doNotSpill; /* Do not spill the cache when non-zero */
  27279. u8 subjInMemory; /* True to use in-memory sub-journals */
  27280. Pgno dbSize; /* Number of pages in the database */
  27281. Pgno dbOrigSize; /* dbSize before the current transaction */
  27282. Pgno dbFileSize; /* Number of pages in the database file */
  27283. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  27284. int errCode; /* One of several kinds of errors */
  27285. int nRec; /* Pages journalled since last j-header written */
  27286. u32 cksumInit; /* Quasi-random value added to every checksum */
  27287. u32 nSubRec; /* Number of records written to sub-journal */
  27288. Bitvec *pInJournal; /* One bit for each page in the database file */
  27289. sqlite3_file *fd; /* File descriptor for database */
  27290. sqlite3_file *jfd; /* File descriptor for main journal */
  27291. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  27292. i64 journalOff; /* Current write offset in the journal file */
  27293. i64 journalHdr; /* Byte offset to previous journal header */
  27294. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  27295. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  27296. int nSavepoint; /* Number of elements in aSavepoint[] */
  27297. char dbFileVers[16]; /* Changes whenever database file changes */
  27298. u8 bUseFetch; /* True to use xFetch() */
  27299. int nMmapOut; /* Number of mmap pages currently outstanding */
  27300. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  27301. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  27302. /*
  27303. ** End of the routinely-changing class members
  27304. ***************************************************************************/
  27305. u16 nExtra; /* Add this many bytes to each in-memory page */
  27306. i16 nReserve; /* Number of unused bytes at end of each page */
  27307. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  27308. u32 sectorSize; /* Assumed sector size during rollback */
  27309. int pageSize; /* Number of bytes in a page */
  27310. Pgno mxPgno; /* Maximum allowed size of the database */
  27311. i64 journalSizeLimit; /* Size limit for persistent journal files */
  27312. char *zFilename; /* Name of the database file */
  27313. char *zJournal; /* Name of the journal file */
  27314. int (*xBusyHandler)(void*); /* Function to call when busy */
  27315. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  27316. int aStat[3]; /* Total cache hits, misses and writes */
  27317. #ifdef SQLITE_TEST
  27318. int nRead; /* Database pages read */
  27319. #endif
  27320. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  27321. #ifdef SQLITE_HAS_CODEC
  27322. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  27323. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  27324. void (*xCodecFree)(void*); /* Destructor for the codec */
  27325. void *pCodec; /* First argument to xCodec... methods */
  27326. #endif
  27327. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  27328. PCache *pPCache; /* Pointer to page cache object */
  27329. #ifndef SQLITE_OMIT_WAL
  27330. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  27331. char *zWal; /* File name for write-ahead log */
  27332. #endif
  27333. };
  27334. /*
  27335. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  27336. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  27337. ** or CACHE_WRITE to sqlite3_db_status().
  27338. */
  27339. #define PAGER_STAT_HIT 0
  27340. #define PAGER_STAT_MISS 1
  27341. #define PAGER_STAT_WRITE 2
  27342. /*
  27343. ** The following global variables hold counters used for
  27344. ** testing purposes only. These variables do not exist in
  27345. ** a non-testing build. These variables are not thread-safe.
  27346. */
  27347. #ifdef SQLITE_TEST
  27348. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  27349. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  27350. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  27351. # define PAGER_INCR(v) v++
  27352. #else
  27353. # define PAGER_INCR(v)
  27354. #endif
  27355. /*
  27356. ** Journal files begin with the following magic string. The data
  27357. ** was obtained from /dev/random. It is used only as a sanity check.
  27358. **
  27359. ** Since version 2.8.0, the journal format contains additional sanity
  27360. ** checking information. If the power fails while the journal is being
  27361. ** written, semi-random garbage data might appear in the journal
  27362. ** file after power is restored. If an attempt is then made
  27363. ** to roll the journal back, the database could be corrupted. The additional
  27364. ** sanity checking data is an attempt to discover the garbage in the
  27365. ** journal and ignore it.
  27366. **
  27367. ** The sanity checking information for the new journal format consists
  27368. ** of a 32-bit checksum on each page of data. The checksum covers both
  27369. ** the page number and the pPager->pageSize bytes of data for the page.
  27370. ** This cksum is initialized to a 32-bit random value that appears in the
  27371. ** journal file right after the header. The random initializer is important,
  27372. ** because garbage data that appears at the end of a journal is likely
  27373. ** data that was once in other files that have now been deleted. If the
  27374. ** garbage data came from an obsolete journal file, the checksums might
  27375. ** be correct. But by initializing the checksum to random value which
  27376. ** is different for every journal, we minimize that risk.
  27377. */
  27378. static const unsigned char aJournalMagic[] = {
  27379. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  27380. };
  27381. /*
  27382. ** The size of the of each page record in the journal is given by
  27383. ** the following macro.
  27384. */
  27385. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  27386. /*
  27387. ** The journal header size for this pager. This is usually the same
  27388. ** size as a single disk sector. See also setSectorSize().
  27389. */
  27390. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  27391. /*
  27392. ** The macro MEMDB is true if we are dealing with an in-memory database.
  27393. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  27394. ** the value of MEMDB will be a constant and the compiler will optimize
  27395. ** out code that would never execute.
  27396. */
  27397. #ifdef SQLITE_OMIT_MEMORYDB
  27398. # define MEMDB 0
  27399. #else
  27400. # define MEMDB pPager->memDb
  27401. #endif
  27402. /*
  27403. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  27404. ** interfaces to access the database using memory-mapped I/O.
  27405. */
  27406. #if SQLITE_MAX_MMAP_SIZE>0
  27407. # define USEFETCH(x) ((x)->bUseFetch)
  27408. #else
  27409. # define USEFETCH(x) 0
  27410. #endif
  27411. /*
  27412. ** The maximum legal page number is (2^31 - 1).
  27413. */
  27414. #define PAGER_MAX_PGNO 2147483647
  27415. /*
  27416. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  27417. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  27418. **
  27419. ** This is so that expressions can be written as:
  27420. **
  27421. ** if( isOpen(pPager->jfd) ){ ...
  27422. **
  27423. ** instead of
  27424. **
  27425. ** if( pPager->jfd->pMethods ){ ...
  27426. */
  27427. #define isOpen(pFd) ((pFd)->pMethods)
  27428. /*
  27429. ** Return true if this pager uses a write-ahead log instead of the usual
  27430. ** rollback journal. Otherwise false.
  27431. */
  27432. #ifndef SQLITE_OMIT_WAL
  27433. static int pagerUseWal(Pager *pPager){
  27434. return (pPager->pWal!=0);
  27435. }
  27436. #else
  27437. # define pagerUseWal(x) 0
  27438. # define pagerRollbackWal(x) 0
  27439. # define pagerWalFrames(v,w,x,y) 0
  27440. # define pagerOpenWalIfPresent(z) SQLITE_OK
  27441. # define pagerBeginReadTransaction(z) SQLITE_OK
  27442. #endif
  27443. #ifndef NDEBUG
  27444. /*
  27445. ** Usage:
  27446. **
  27447. ** assert( assert_pager_state(pPager) );
  27448. **
  27449. ** This function runs many asserts to try to find inconsistencies in
  27450. ** the internal state of the Pager object.
  27451. */
  27452. static int assert_pager_state(Pager *p){
  27453. Pager *pPager = p;
  27454. /* State must be valid. */
  27455. assert( p->eState==PAGER_OPEN
  27456. || p->eState==PAGER_READER
  27457. || p->eState==PAGER_WRITER_LOCKED
  27458. || p->eState==PAGER_WRITER_CACHEMOD
  27459. || p->eState==PAGER_WRITER_DBMOD
  27460. || p->eState==PAGER_WRITER_FINISHED
  27461. || p->eState==PAGER_ERROR
  27462. );
  27463. /* Regardless of the current state, a temp-file connection always behaves
  27464. ** as if it has an exclusive lock on the database file. It never updates
  27465. ** the change-counter field, so the changeCountDone flag is always set.
  27466. */
  27467. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  27468. assert( p->tempFile==0 || pPager->changeCountDone );
  27469. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  27470. ** And if the journal-mode is "OFF", the journal file must not be open.
  27471. */
  27472. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  27473. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  27474. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  27475. ** this means an in-memory pager performs no IO at all, it cannot encounter
  27476. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  27477. ** a journal file. (although the in-memory journal implementation may
  27478. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  27479. ** is therefore not possible for an in-memory pager to enter the ERROR
  27480. ** state.
  27481. */
  27482. if( MEMDB ){
  27483. assert( p->noSync );
  27484. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  27485. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  27486. );
  27487. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  27488. assert( pagerUseWal(p)==0 );
  27489. }
  27490. /* If changeCountDone is set, a RESERVED lock or greater must be held
  27491. ** on the file.
  27492. */
  27493. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  27494. assert( p->eLock!=PENDING_LOCK );
  27495. switch( p->eState ){
  27496. case PAGER_OPEN:
  27497. assert( !MEMDB );
  27498. assert( pPager->errCode==SQLITE_OK );
  27499. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  27500. break;
  27501. case PAGER_READER:
  27502. assert( pPager->errCode==SQLITE_OK );
  27503. assert( p->eLock!=UNKNOWN_LOCK );
  27504. assert( p->eLock>=SHARED_LOCK );
  27505. break;
  27506. case PAGER_WRITER_LOCKED:
  27507. assert( p->eLock!=UNKNOWN_LOCK );
  27508. assert( pPager->errCode==SQLITE_OK );
  27509. if( !pagerUseWal(pPager) ){
  27510. assert( p->eLock>=RESERVED_LOCK );
  27511. }
  27512. assert( pPager->dbSize==pPager->dbOrigSize );
  27513. assert( pPager->dbOrigSize==pPager->dbFileSize );
  27514. assert( pPager->dbOrigSize==pPager->dbHintSize );
  27515. assert( pPager->setMaster==0 );
  27516. break;
  27517. case PAGER_WRITER_CACHEMOD:
  27518. assert( p->eLock!=UNKNOWN_LOCK );
  27519. assert( pPager->errCode==SQLITE_OK );
  27520. if( !pagerUseWal(pPager) ){
  27521. /* It is possible that if journal_mode=wal here that neither the
  27522. ** journal file nor the WAL file are open. This happens during
  27523. ** a rollback transaction that switches from journal_mode=off
  27524. ** to journal_mode=wal.
  27525. */
  27526. assert( p->eLock>=RESERVED_LOCK );
  27527. assert( isOpen(p->jfd)
  27528. || p->journalMode==PAGER_JOURNALMODE_OFF
  27529. || p->journalMode==PAGER_JOURNALMODE_WAL
  27530. );
  27531. }
  27532. assert( pPager->dbOrigSize==pPager->dbFileSize );
  27533. assert( pPager->dbOrigSize==pPager->dbHintSize );
  27534. break;
  27535. case PAGER_WRITER_DBMOD:
  27536. assert( p->eLock==EXCLUSIVE_LOCK );
  27537. assert( pPager->errCode==SQLITE_OK );
  27538. assert( !pagerUseWal(pPager) );
  27539. assert( p->eLock>=EXCLUSIVE_LOCK );
  27540. assert( isOpen(p->jfd)
  27541. || p->journalMode==PAGER_JOURNALMODE_OFF
  27542. || p->journalMode==PAGER_JOURNALMODE_WAL
  27543. );
  27544. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  27545. break;
  27546. case PAGER_WRITER_FINISHED:
  27547. assert( p->eLock==EXCLUSIVE_LOCK );
  27548. assert( pPager->errCode==SQLITE_OK );
  27549. assert( !pagerUseWal(pPager) );
  27550. assert( isOpen(p->jfd)
  27551. || p->journalMode==PAGER_JOURNALMODE_OFF
  27552. || p->journalMode==PAGER_JOURNALMODE_WAL
  27553. );
  27554. break;
  27555. case PAGER_ERROR:
  27556. /* There must be at least one outstanding reference to the pager if
  27557. ** in ERROR state. Otherwise the pager should have already dropped
  27558. ** back to OPEN state.
  27559. */
  27560. assert( pPager->errCode!=SQLITE_OK );
  27561. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  27562. break;
  27563. }
  27564. return 1;
  27565. }
  27566. #endif /* ifndef NDEBUG */
  27567. #ifdef SQLITE_DEBUG
  27568. /*
  27569. ** Return a pointer to a human readable string in a static buffer
  27570. ** containing the state of the Pager object passed as an argument. This
  27571. ** is intended to be used within debuggers. For example, as an alternative
  27572. ** to "print *pPager" in gdb:
  27573. **
  27574. ** (gdb) printf "%s", print_pager_state(pPager)
  27575. */
  27576. static char *print_pager_state(Pager *p){
  27577. static char zRet[1024];
  27578. sqlite3_snprintf(1024, zRet,
  27579. "Filename: %s\n"
  27580. "State: %s errCode=%d\n"
  27581. "Lock: %s\n"
  27582. "Locking mode: locking_mode=%s\n"
  27583. "Journal mode: journal_mode=%s\n"
  27584. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  27585. "Journal: journalOff=%lld journalHdr=%lld\n"
  27586. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  27587. , p->zFilename
  27588. , p->eState==PAGER_OPEN ? "OPEN" :
  27589. p->eState==PAGER_READER ? "READER" :
  27590. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  27591. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  27592. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  27593. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  27594. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  27595. , (int)p->errCode
  27596. , p->eLock==NO_LOCK ? "NO_LOCK" :
  27597. p->eLock==RESERVED_LOCK ? "RESERVED" :
  27598. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  27599. p->eLock==SHARED_LOCK ? "SHARED" :
  27600. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  27601. , p->exclusiveMode ? "exclusive" : "normal"
  27602. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  27603. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  27604. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  27605. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  27606. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  27607. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  27608. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  27609. , p->journalOff, p->journalHdr
  27610. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  27611. );
  27612. return zRet;
  27613. }
  27614. #endif
  27615. /*
  27616. ** Return true if it is necessary to write page *pPg into the sub-journal.
  27617. ** A page needs to be written into the sub-journal if there exists one
  27618. ** or more open savepoints for which:
  27619. **
  27620. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  27621. ** * The bit corresponding to the page-number is not set in
  27622. ** PagerSavepoint.pInSavepoint.
  27623. */
  27624. static int subjRequiresPage(PgHdr *pPg){
  27625. Pager *pPager = pPg->pPager;
  27626. PagerSavepoint *p;
  27627. Pgno pgno;
  27628. int i;
  27629. if( pPager->nSavepoint ){
  27630. pgno = pPg->pgno;
  27631. for(i=0; i<pPager->nSavepoint; i++){
  27632. p = &pPager->aSavepoint[i];
  27633. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  27634. return 1;
  27635. }
  27636. }
  27637. }
  27638. return 0;
  27639. }
  27640. /*
  27641. ** Return true if the page is already in the journal file.
  27642. */
  27643. static int pageInJournal(PgHdr *pPg){
  27644. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  27645. }
  27646. /*
  27647. ** Read a 32-bit integer from the given file descriptor. Store the integer
  27648. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  27649. ** error code is something goes wrong.
  27650. **
  27651. ** All values are stored on disk as big-endian.
  27652. */
  27653. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  27654. unsigned char ac[4];
  27655. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  27656. if( rc==SQLITE_OK ){
  27657. *pRes = sqlite3Get4byte(ac);
  27658. }
  27659. return rc;
  27660. }
  27661. /*
  27662. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  27663. */
  27664. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  27665. /*
  27666. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  27667. ** on success or an error code is something goes wrong.
  27668. */
  27669. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  27670. char ac[4];
  27671. put32bits(ac, val);
  27672. return sqlite3OsWrite(fd, ac, 4, offset);
  27673. }
  27674. /*
  27675. ** Unlock the database file to level eLock, which must be either NO_LOCK
  27676. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  27677. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  27678. **
  27679. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  27680. ** called, do not modify it. See the comment above the #define of
  27681. ** UNKNOWN_LOCK for an explanation of this.
  27682. */
  27683. static int pagerUnlockDb(Pager *pPager, int eLock){
  27684. int rc = SQLITE_OK;
  27685. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  27686. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  27687. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  27688. if( isOpen(pPager->fd) ){
  27689. assert( pPager->eLock>=eLock );
  27690. rc = sqlite3OsUnlock(pPager->fd, eLock);
  27691. if( pPager->eLock!=UNKNOWN_LOCK ){
  27692. pPager->eLock = (u8)eLock;
  27693. }
  27694. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  27695. }
  27696. return rc;
  27697. }
  27698. /*
  27699. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  27700. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  27701. ** Pager.eLock variable to the new locking state.
  27702. **
  27703. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  27704. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  27705. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  27706. ** of this.
  27707. */
  27708. static int pagerLockDb(Pager *pPager, int eLock){
  27709. int rc = SQLITE_OK;
  27710. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  27711. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  27712. rc = sqlite3OsLock(pPager->fd, eLock);
  27713. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  27714. pPager->eLock = (u8)eLock;
  27715. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  27716. }
  27717. }
  27718. return rc;
  27719. }
  27720. /*
  27721. ** This function determines whether or not the atomic-write optimization
  27722. ** can be used with this pager. The optimization can be used if:
  27723. **
  27724. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  27725. ** a database page may be written atomically, and
  27726. ** (b) the value returned by OsSectorSize() is less than or equal
  27727. ** to the page size.
  27728. **
  27729. ** The optimization is also always enabled for temporary files. It is
  27730. ** an error to call this function if pPager is opened on an in-memory
  27731. ** database.
  27732. **
  27733. ** If the optimization cannot be used, 0 is returned. If it can be used,
  27734. ** then the value returned is the size of the journal file when it
  27735. ** contains rollback data for exactly one page.
  27736. */
  27737. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  27738. static int jrnlBufferSize(Pager *pPager){
  27739. assert( !MEMDB );
  27740. if( !pPager->tempFile ){
  27741. int dc; /* Device characteristics */
  27742. int nSector; /* Sector size */
  27743. int szPage; /* Page size */
  27744. assert( isOpen(pPager->fd) );
  27745. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  27746. nSector = pPager->sectorSize;
  27747. szPage = pPager->pageSize;
  27748. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  27749. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  27750. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  27751. return 0;
  27752. }
  27753. }
  27754. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  27755. }
  27756. #endif
  27757. /*
  27758. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  27759. ** on the cache using a hash function. This is used for testing
  27760. ** and debugging only.
  27761. */
  27762. #ifdef SQLITE_CHECK_PAGES
  27763. /*
  27764. ** Return a 32-bit hash of the page data for pPage.
  27765. */
  27766. static u32 pager_datahash(int nByte, unsigned char *pData){
  27767. u32 hash = 0;
  27768. int i;
  27769. for(i=0; i<nByte; i++){
  27770. hash = (hash*1039) + pData[i];
  27771. }
  27772. return hash;
  27773. }
  27774. static u32 pager_pagehash(PgHdr *pPage){
  27775. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  27776. }
  27777. static void pager_set_pagehash(PgHdr *pPage){
  27778. pPage->pageHash = pager_pagehash(pPage);
  27779. }
  27780. /*
  27781. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  27782. ** is defined, and NDEBUG is not defined, an assert() statement checks
  27783. ** that the page is either dirty or still matches the calculated page-hash.
  27784. */
  27785. #define CHECK_PAGE(x) checkPage(x)
  27786. static void checkPage(PgHdr *pPg){
  27787. Pager *pPager = pPg->pPager;
  27788. assert( pPager->eState!=PAGER_ERROR );
  27789. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  27790. }
  27791. #else
  27792. #define pager_datahash(X,Y) 0
  27793. #define pager_pagehash(X) 0
  27794. #define pager_set_pagehash(X)
  27795. #define CHECK_PAGE(x)
  27796. #endif /* SQLITE_CHECK_PAGES */
  27797. /*
  27798. ** When this is called the journal file for pager pPager must be open.
  27799. ** This function attempts to read a master journal file name from the
  27800. ** end of the file and, if successful, copies it into memory supplied
  27801. ** by the caller. See comments above writeMasterJournal() for the format
  27802. ** used to store a master journal file name at the end of a journal file.
  27803. **
  27804. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  27805. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  27806. ** enough space to write the master journal name). If the master journal
  27807. ** name in the journal is longer than nMaster bytes (including a
  27808. ** nul-terminator), then this is handled as if no master journal name
  27809. ** were present in the journal.
  27810. **
  27811. ** If a master journal file name is present at the end of the journal
  27812. ** file, then it is copied into the buffer pointed to by zMaster. A
  27813. ** nul-terminator byte is appended to the buffer following the master
  27814. ** journal file name.
  27815. **
  27816. ** If it is determined that no master journal file name is present
  27817. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  27818. **
  27819. ** If an error occurs while reading from the journal file, an SQLite
  27820. ** error code is returned.
  27821. */
  27822. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  27823. int rc; /* Return code */
  27824. u32 len; /* Length in bytes of master journal name */
  27825. i64 szJ; /* Total size in bytes of journal file pJrnl */
  27826. u32 cksum; /* MJ checksum value read from journal */
  27827. u32 u; /* Unsigned loop counter */
  27828. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  27829. zMaster[0] = '\0';
  27830. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  27831. || szJ<16
  27832. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  27833. || len>=nMaster
  27834. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  27835. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  27836. || memcmp(aMagic, aJournalMagic, 8)
  27837. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  27838. ){
  27839. return rc;
  27840. }
  27841. /* See if the checksum matches the master journal name */
  27842. for(u=0; u<len; u++){
  27843. cksum -= zMaster[u];
  27844. }
  27845. if( cksum ){
  27846. /* If the checksum doesn't add up, then one or more of the disk sectors
  27847. ** containing the master journal filename is corrupted. This means
  27848. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  27849. ** master-journal filename.
  27850. */
  27851. len = 0;
  27852. }
  27853. zMaster[len] = '\0';
  27854. return SQLITE_OK;
  27855. }
  27856. /*
  27857. ** Return the offset of the sector boundary at or immediately
  27858. ** following the value in pPager->journalOff, assuming a sector
  27859. ** size of pPager->sectorSize bytes.
  27860. **
  27861. ** i.e for a sector size of 512:
  27862. **
  27863. ** Pager.journalOff Return value
  27864. ** ---------------------------------------
  27865. ** 0 0
  27866. ** 512 512
  27867. ** 100 512
  27868. ** 2000 2048
  27869. **
  27870. */
  27871. static i64 journalHdrOffset(Pager *pPager){
  27872. i64 offset = 0;
  27873. i64 c = pPager->journalOff;
  27874. if( c ){
  27875. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  27876. }
  27877. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  27878. assert( offset>=c );
  27879. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  27880. return offset;
  27881. }
  27882. /*
  27883. ** The journal file must be open when this function is called.
  27884. **
  27885. ** This function is a no-op if the journal file has not been written to
  27886. ** within the current transaction (i.e. if Pager.journalOff==0).
  27887. **
  27888. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  27889. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  27890. ** zero the 28-byte header at the start of the journal file. In either case,
  27891. ** if the pager is not in no-sync mode, sync the journal file immediately
  27892. ** after writing or truncating it.
  27893. **
  27894. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  27895. ** following the truncation or zeroing described above the size of the
  27896. ** journal file in bytes is larger than this value, then truncate the
  27897. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  27898. ** not need to be synced following this operation.
  27899. **
  27900. ** If an IO error occurs, abandon processing and return the IO error code.
  27901. ** Otherwise, return SQLITE_OK.
  27902. */
  27903. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  27904. int rc = SQLITE_OK; /* Return code */
  27905. assert( isOpen(pPager->jfd) );
  27906. if( pPager->journalOff ){
  27907. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  27908. IOTRACE(("JZEROHDR %p\n", pPager))
  27909. if( doTruncate || iLimit==0 ){
  27910. rc = sqlite3OsTruncate(pPager->jfd, 0);
  27911. }else{
  27912. static const char zeroHdr[28] = {0};
  27913. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  27914. }
  27915. if( rc==SQLITE_OK && !pPager->noSync ){
  27916. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  27917. }
  27918. /* At this point the transaction is committed but the write lock
  27919. ** is still held on the file. If there is a size limit configured for
  27920. ** the persistent journal and the journal file currently consumes more
  27921. ** space than that limit allows for, truncate it now. There is no need
  27922. ** to sync the file following this operation.
  27923. */
  27924. if( rc==SQLITE_OK && iLimit>0 ){
  27925. i64 sz;
  27926. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  27927. if( rc==SQLITE_OK && sz>iLimit ){
  27928. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  27929. }
  27930. }
  27931. }
  27932. return rc;
  27933. }
  27934. /*
  27935. ** The journal file must be open when this routine is called. A journal
  27936. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  27937. ** current location.
  27938. **
  27939. ** The format for the journal header is as follows:
  27940. ** - 8 bytes: Magic identifying journal format.
  27941. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  27942. ** - 4 bytes: Random number used for page hash.
  27943. ** - 4 bytes: Initial database page count.
  27944. ** - 4 bytes: Sector size used by the process that wrote this journal.
  27945. ** - 4 bytes: Database page size.
  27946. **
  27947. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  27948. */
  27949. static int writeJournalHdr(Pager *pPager){
  27950. int rc = SQLITE_OK; /* Return code */
  27951. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  27952. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  27953. u32 nWrite; /* Bytes of header sector written */
  27954. int ii; /* Loop counter */
  27955. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  27956. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  27957. nHeader = JOURNAL_HDR_SZ(pPager);
  27958. }
  27959. /* If there are active savepoints and any of them were created
  27960. ** since the most recent journal header was written, update the
  27961. ** PagerSavepoint.iHdrOffset fields now.
  27962. */
  27963. for(ii=0; ii<pPager->nSavepoint; ii++){
  27964. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  27965. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  27966. }
  27967. }
  27968. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  27969. /*
  27970. ** Write the nRec Field - the number of page records that follow this
  27971. ** journal header. Normally, zero is written to this value at this time.
  27972. ** After the records are added to the journal (and the journal synced,
  27973. ** if in full-sync mode), the zero is overwritten with the true number
  27974. ** of records (see syncJournal()).
  27975. **
  27976. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  27977. ** reading the journal this value tells SQLite to assume that the
  27978. ** rest of the journal file contains valid page records. This assumption
  27979. ** is dangerous, as if a failure occurred whilst writing to the journal
  27980. ** file it may contain some garbage data. There are two scenarios
  27981. ** where this risk can be ignored:
  27982. **
  27983. ** * When the pager is in no-sync mode. Corruption can follow a
  27984. ** power failure in this case anyway.
  27985. **
  27986. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  27987. ** that garbage data is never appended to the journal file.
  27988. */
  27989. assert( isOpen(pPager->fd) || pPager->noSync );
  27990. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  27991. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  27992. ){
  27993. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  27994. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  27995. }else{
  27996. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  27997. }
  27998. /* The random check-hash initializer */
  27999. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  28000. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  28001. /* The initial database size */
  28002. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  28003. /* The assumed sector size for this process */
  28004. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  28005. /* The page size */
  28006. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  28007. /* Initializing the tail of the buffer is not necessary. Everything
  28008. ** works find if the following memset() is omitted. But initializing
  28009. ** the memory prevents valgrind from complaining, so we are willing to
  28010. ** take the performance hit.
  28011. */
  28012. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  28013. nHeader-(sizeof(aJournalMagic)+20));
  28014. /* In theory, it is only necessary to write the 28 bytes that the
  28015. ** journal header consumes to the journal file here. Then increment the
  28016. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  28017. ** record is written to the following sector (leaving a gap in the file
  28018. ** that will be implicitly filled in by the OS).
  28019. **
  28020. ** However it has been discovered that on some systems this pattern can
  28021. ** be significantly slower than contiguously writing data to the file,
  28022. ** even if that means explicitly writing data to the block of
  28023. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  28024. ** is done.
  28025. **
  28026. ** The loop is required here in case the sector-size is larger than the
  28027. ** database page size. Since the zHeader buffer is only Pager.pageSize
  28028. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  28029. ** to populate the entire journal header sector.
  28030. */
  28031. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  28032. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  28033. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  28034. assert( pPager->journalHdr <= pPager->journalOff );
  28035. pPager->journalOff += nHeader;
  28036. }
  28037. return rc;
  28038. }
  28039. /*
  28040. ** The journal file must be open when this is called. A journal header file
  28041. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  28042. ** file. The current location in the journal file is given by
  28043. ** pPager->journalOff. See comments above function writeJournalHdr() for
  28044. ** a description of the journal header format.
  28045. **
  28046. ** If the header is read successfully, *pNRec is set to the number of
  28047. ** page records following this header and *pDbSize is set to the size of the
  28048. ** database before the transaction began, in pages. Also, pPager->cksumInit
  28049. ** is set to the value read from the journal header. SQLITE_OK is returned
  28050. ** in this case.
  28051. **
  28052. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  28053. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  28054. ** cannot be read from the journal file an error code is returned.
  28055. */
  28056. static int readJournalHdr(
  28057. Pager *pPager, /* Pager object */
  28058. int isHot,
  28059. i64 journalSize, /* Size of the open journal file in bytes */
  28060. u32 *pNRec, /* OUT: Value read from the nRec field */
  28061. u32 *pDbSize /* OUT: Value of original database size field */
  28062. ){
  28063. int rc; /* Return code */
  28064. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  28065. i64 iHdrOff; /* Offset of journal header being read */
  28066. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  28067. /* Advance Pager.journalOff to the start of the next sector. If the
  28068. ** journal file is too small for there to be a header stored at this
  28069. ** point, return SQLITE_DONE.
  28070. */
  28071. pPager->journalOff = journalHdrOffset(pPager);
  28072. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  28073. return SQLITE_DONE;
  28074. }
  28075. iHdrOff = pPager->journalOff;
  28076. /* Read in the first 8 bytes of the journal header. If they do not match
  28077. ** the magic string found at the start of each journal header, return
  28078. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  28079. ** proceed.
  28080. */
  28081. if( isHot || iHdrOff!=pPager->journalHdr ){
  28082. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  28083. if( rc ){
  28084. return rc;
  28085. }
  28086. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  28087. return SQLITE_DONE;
  28088. }
  28089. }
  28090. /* Read the first three 32-bit fields of the journal header: The nRec
  28091. ** field, the checksum-initializer and the database size at the start
  28092. ** of the transaction. Return an error code if anything goes wrong.
  28093. */
  28094. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  28095. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  28096. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  28097. ){
  28098. return rc;
  28099. }
  28100. if( pPager->journalOff==0 ){
  28101. u32 iPageSize; /* Page-size field of journal header */
  28102. u32 iSectorSize; /* Sector-size field of journal header */
  28103. /* Read the page-size and sector-size journal header fields. */
  28104. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  28105. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  28106. ){
  28107. return rc;
  28108. }
  28109. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  28110. ** journal header to zero. In this case, assume that the Pager.pageSize
  28111. ** variable is already set to the correct page size.
  28112. */
  28113. if( iPageSize==0 ){
  28114. iPageSize = pPager->pageSize;
  28115. }
  28116. /* Check that the values read from the page-size and sector-size fields
  28117. ** are within range. To be 'in range', both values need to be a power
  28118. ** of two greater than or equal to 512 or 32, and not greater than their
  28119. ** respective compile time maximum limits.
  28120. */
  28121. if( iPageSize<512 || iSectorSize<32
  28122. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  28123. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  28124. ){
  28125. /* If the either the page-size or sector-size in the journal-header is
  28126. ** invalid, then the process that wrote the journal-header must have
  28127. ** crashed before the header was synced. In this case stop reading
  28128. ** the journal file here.
  28129. */
  28130. return SQLITE_DONE;
  28131. }
  28132. /* Update the page-size to match the value read from the journal.
  28133. ** Use a testcase() macro to make sure that malloc failure within
  28134. ** PagerSetPagesize() is tested.
  28135. */
  28136. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  28137. testcase( rc!=SQLITE_OK );
  28138. /* Update the assumed sector-size to match the value used by
  28139. ** the process that created this journal. If this journal was
  28140. ** created by a process other than this one, then this routine
  28141. ** is being called from within pager_playback(). The local value
  28142. ** of Pager.sectorSize is restored at the end of that routine.
  28143. */
  28144. pPager->sectorSize = iSectorSize;
  28145. }
  28146. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  28147. return rc;
  28148. }
  28149. /*
  28150. ** Write the supplied master journal name into the journal file for pager
  28151. ** pPager at the current location. The master journal name must be the last
  28152. ** thing written to a journal file. If the pager is in full-sync mode, the
  28153. ** journal file descriptor is advanced to the next sector boundary before
  28154. ** anything is written. The format is:
  28155. **
  28156. ** + 4 bytes: PAGER_MJ_PGNO.
  28157. ** + N bytes: Master journal filename in utf-8.
  28158. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  28159. ** + 4 bytes: Master journal name checksum.
  28160. ** + 8 bytes: aJournalMagic[].
  28161. **
  28162. ** The master journal page checksum is the sum of the bytes in the master
  28163. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  28164. **
  28165. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  28166. ** this call is a no-op.
  28167. */
  28168. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  28169. int rc; /* Return code */
  28170. int nMaster; /* Length of string zMaster */
  28171. i64 iHdrOff; /* Offset of header in journal file */
  28172. i64 jrnlSize; /* Size of journal file on disk */
  28173. u32 cksum = 0; /* Checksum of string zMaster */
  28174. assert( pPager->setMaster==0 );
  28175. assert( !pagerUseWal(pPager) );
  28176. if( !zMaster
  28177. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  28178. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  28179. ){
  28180. return SQLITE_OK;
  28181. }
  28182. pPager->setMaster = 1;
  28183. assert( isOpen(pPager->jfd) );
  28184. assert( pPager->journalHdr <= pPager->journalOff );
  28185. /* Calculate the length in bytes and the checksum of zMaster */
  28186. for(nMaster=0; zMaster[nMaster]; nMaster++){
  28187. cksum += zMaster[nMaster];
  28188. }
  28189. /* If in full-sync mode, advance to the next disk sector before writing
  28190. ** the master journal name. This is in case the previous page written to
  28191. ** the journal has already been synced.
  28192. */
  28193. if( pPager->fullSync ){
  28194. pPager->journalOff = journalHdrOffset(pPager);
  28195. }
  28196. iHdrOff = pPager->journalOff;
  28197. /* Write the master journal data to the end of the journal file. If
  28198. ** an error occurs, return the error code to the caller.
  28199. */
  28200. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  28201. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  28202. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  28203. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  28204. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  28205. ){
  28206. return rc;
  28207. }
  28208. pPager->journalOff += (nMaster+20);
  28209. /* If the pager is in peristent-journal mode, then the physical
  28210. ** journal-file may extend past the end of the master-journal name
  28211. ** and 8 bytes of magic data just written to the file. This is
  28212. ** dangerous because the code to rollback a hot-journal file
  28213. ** will not be able to find the master-journal name to determine
  28214. ** whether or not the journal is hot.
  28215. **
  28216. ** Easiest thing to do in this scenario is to truncate the journal
  28217. ** file to the required size.
  28218. */
  28219. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  28220. && jrnlSize>pPager->journalOff
  28221. ){
  28222. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  28223. }
  28224. return rc;
  28225. }
  28226. /*
  28227. ** Find a page in the hash table given its page number. Return
  28228. ** a pointer to the page or NULL if the requested page is not
  28229. ** already in memory.
  28230. */
  28231. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  28232. PgHdr *p; /* Return value */
  28233. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  28234. ** fail, since no attempt to allocate dynamic memory will be made.
  28235. */
  28236. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  28237. return p;
  28238. }
  28239. /*
  28240. ** Discard the entire contents of the in-memory page-cache.
  28241. */
  28242. static void pager_reset(Pager *pPager){
  28243. sqlite3BackupRestart(pPager->pBackup);
  28244. sqlite3PcacheClear(pPager->pPCache);
  28245. }
  28246. /*
  28247. ** Free all structures in the Pager.aSavepoint[] array and set both
  28248. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  28249. ** if it is open and the pager is not in exclusive mode.
  28250. */
  28251. static void releaseAllSavepoints(Pager *pPager){
  28252. int ii; /* Iterator for looping through Pager.aSavepoint */
  28253. for(ii=0; ii<pPager->nSavepoint; ii++){
  28254. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  28255. }
  28256. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  28257. sqlite3OsClose(pPager->sjfd);
  28258. }
  28259. sqlite3_free(pPager->aSavepoint);
  28260. pPager->aSavepoint = 0;
  28261. pPager->nSavepoint = 0;
  28262. pPager->nSubRec = 0;
  28263. }
  28264. /*
  28265. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  28266. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  28267. ** or SQLITE_NOMEM if a malloc failure occurs.
  28268. */
  28269. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  28270. int ii; /* Loop counter */
  28271. int rc = SQLITE_OK; /* Result code */
  28272. for(ii=0; ii<pPager->nSavepoint; ii++){
  28273. PagerSavepoint *p = &pPager->aSavepoint[ii];
  28274. if( pgno<=p->nOrig ){
  28275. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  28276. testcase( rc==SQLITE_NOMEM );
  28277. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  28278. }
  28279. }
  28280. return rc;
  28281. }
  28282. /*
  28283. ** This function is a no-op if the pager is in exclusive mode and not
  28284. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  28285. ** state.
  28286. **
  28287. ** If the pager is not in exclusive-access mode, the database file is
  28288. ** completely unlocked. If the file is unlocked and the file-system does
  28289. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  28290. ** closed (if it is open).
  28291. **
  28292. ** If the pager is in ERROR state when this function is called, the
  28293. ** contents of the pager cache are discarded before switching back to
  28294. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  28295. ** or not, any journal file left in the file-system will be treated
  28296. ** as a hot-journal and rolled back the next time a read-transaction
  28297. ** is opened (by this or by any other connection).
  28298. */
  28299. static void pager_unlock(Pager *pPager){
  28300. assert( pPager->eState==PAGER_READER
  28301. || pPager->eState==PAGER_OPEN
  28302. || pPager->eState==PAGER_ERROR
  28303. );
  28304. sqlite3BitvecDestroy(pPager->pInJournal);
  28305. pPager->pInJournal = 0;
  28306. releaseAllSavepoints(pPager);
  28307. if( pagerUseWal(pPager) ){
  28308. assert( !isOpen(pPager->jfd) );
  28309. sqlite3WalEndReadTransaction(pPager->pWal);
  28310. pPager->eState = PAGER_OPEN;
  28311. }else if( !pPager->exclusiveMode ){
  28312. int rc; /* Error code returned by pagerUnlockDb() */
  28313. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  28314. /* If the operating system support deletion of open files, then
  28315. ** close the journal file when dropping the database lock. Otherwise
  28316. ** another connection with journal_mode=delete might delete the file
  28317. ** out from under us.
  28318. */
  28319. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  28320. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  28321. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  28322. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  28323. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  28324. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  28325. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  28326. || 1!=(pPager->journalMode & 5)
  28327. ){
  28328. sqlite3OsClose(pPager->jfd);
  28329. }
  28330. /* If the pager is in the ERROR state and the call to unlock the database
  28331. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  28332. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  28333. ** is necessary.
  28334. */
  28335. rc = pagerUnlockDb(pPager, NO_LOCK);
  28336. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  28337. pPager->eLock = UNKNOWN_LOCK;
  28338. }
  28339. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  28340. ** without clearing the error code. This is intentional - the error
  28341. ** code is cleared and the cache reset in the block below.
  28342. */
  28343. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  28344. pPager->changeCountDone = 0;
  28345. pPager->eState = PAGER_OPEN;
  28346. }
  28347. /* If Pager.errCode is set, the contents of the pager cache cannot be
  28348. ** trusted. Now that there are no outstanding references to the pager,
  28349. ** it can safely move back to PAGER_OPEN state. This happens in both
  28350. ** normal and exclusive-locking mode.
  28351. */
  28352. if( pPager->errCode ){
  28353. assert( !MEMDB );
  28354. pager_reset(pPager);
  28355. pPager->changeCountDone = pPager->tempFile;
  28356. pPager->eState = PAGER_OPEN;
  28357. pPager->errCode = SQLITE_OK;
  28358. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  28359. }
  28360. pPager->journalOff = 0;
  28361. pPager->journalHdr = 0;
  28362. pPager->setMaster = 0;
  28363. }
  28364. /*
  28365. ** This function is called whenever an IOERR or FULL error that requires
  28366. ** the pager to transition into the ERROR state may ahve occurred.
  28367. ** The first argument is a pointer to the pager structure, the second
  28368. ** the error-code about to be returned by a pager API function. The
  28369. ** value returned is a copy of the second argument to this function.
  28370. **
  28371. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  28372. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  28373. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  28374. ** all major API calls on the Pager will immediately return Pager.errCode.
  28375. **
  28376. ** The ERROR state indicates that the contents of the pager-cache
  28377. ** cannot be trusted. This state can be cleared by completely discarding
  28378. ** the contents of the pager-cache. If a transaction was active when
  28379. ** the persistent error occurred, then the rollback journal may need
  28380. ** to be replayed to restore the contents of the database file (as if
  28381. ** it were a hot-journal).
  28382. */
  28383. static int pager_error(Pager *pPager, int rc){
  28384. int rc2 = rc & 0xff;
  28385. assert( rc==SQLITE_OK || !MEMDB );
  28386. assert(
  28387. pPager->errCode==SQLITE_FULL ||
  28388. pPager->errCode==SQLITE_OK ||
  28389. (pPager->errCode & 0xff)==SQLITE_IOERR
  28390. );
  28391. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  28392. pPager->errCode = rc;
  28393. pPager->eState = PAGER_ERROR;
  28394. }
  28395. return rc;
  28396. }
  28397. static int pager_truncate(Pager *pPager, Pgno nPage);
  28398. /*
  28399. ** This routine ends a transaction. A transaction is usually ended by
  28400. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  28401. ** after rollback of a hot-journal, or if an error occurs while opening
  28402. ** the journal file or writing the very first journal-header of a
  28403. ** database transaction.
  28404. **
  28405. ** This routine is never called in PAGER_ERROR state. If it is called
  28406. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  28407. ** exclusive than a RESERVED lock, it is a no-op.
  28408. **
  28409. ** Otherwise, any active savepoints are released.
  28410. **
  28411. ** If the journal file is open, then it is "finalized". Once a journal
  28412. ** file has been finalized it is not possible to use it to roll back a
  28413. ** transaction. Nor will it be considered to be a hot-journal by this
  28414. ** or any other database connection. Exactly how a journal is finalized
  28415. ** depends on whether or not the pager is running in exclusive mode and
  28416. ** the current journal-mode (Pager.journalMode value), as follows:
  28417. **
  28418. ** journalMode==MEMORY
  28419. ** Journal file descriptor is simply closed. This destroys an
  28420. ** in-memory journal.
  28421. **
  28422. ** journalMode==TRUNCATE
  28423. ** Journal file is truncated to zero bytes in size.
  28424. **
  28425. ** journalMode==PERSIST
  28426. ** The first 28 bytes of the journal file are zeroed. This invalidates
  28427. ** the first journal header in the file, and hence the entire journal
  28428. ** file. An invalid journal file cannot be rolled back.
  28429. **
  28430. ** journalMode==DELETE
  28431. ** The journal file is closed and deleted using sqlite3OsDelete().
  28432. **
  28433. ** If the pager is running in exclusive mode, this method of finalizing
  28434. ** the journal file is never used. Instead, if the journalMode is
  28435. ** DELETE and the pager is in exclusive mode, the method described under
  28436. ** journalMode==PERSIST is used instead.
  28437. **
  28438. ** After the journal is finalized, the pager moves to PAGER_READER state.
  28439. ** If running in non-exclusive rollback mode, the lock on the file is
  28440. ** downgraded to a SHARED_LOCK.
  28441. **
  28442. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  28443. ** any of the IO operations to finalize the journal file or unlock the
  28444. ** database then the IO error code is returned to the user. If the
  28445. ** operation to finalize the journal file fails, then the code still
  28446. ** tries to unlock the database file if not in exclusive mode. If the
  28447. ** unlock operation fails as well, then the first error code related
  28448. ** to the first error encountered (the journal finalization one) is
  28449. ** returned.
  28450. */
  28451. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  28452. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  28453. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  28454. /* Do nothing if the pager does not have an open write transaction
  28455. ** or at least a RESERVED lock. This function may be called when there
  28456. ** is no write-transaction active but a RESERVED or greater lock is
  28457. ** held under two circumstances:
  28458. **
  28459. ** 1. After a successful hot-journal rollback, it is called with
  28460. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  28461. **
  28462. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  28463. ** lock switches back to locking_mode=normal and then executes a
  28464. ** read-transaction, this function is called with eState==PAGER_READER
  28465. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  28466. */
  28467. assert( assert_pager_state(pPager) );
  28468. assert( pPager->eState!=PAGER_ERROR );
  28469. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  28470. return SQLITE_OK;
  28471. }
  28472. releaseAllSavepoints(pPager);
  28473. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  28474. if( isOpen(pPager->jfd) ){
  28475. assert( !pagerUseWal(pPager) );
  28476. /* Finalize the journal file. */
  28477. if( sqlite3IsMemJournal(pPager->jfd) ){
  28478. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  28479. sqlite3OsClose(pPager->jfd);
  28480. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  28481. if( pPager->journalOff==0 ){
  28482. rc = SQLITE_OK;
  28483. }else{
  28484. rc = sqlite3OsTruncate(pPager->jfd, 0);
  28485. }
  28486. pPager->journalOff = 0;
  28487. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  28488. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  28489. ){
  28490. rc = zeroJournalHdr(pPager, hasMaster);
  28491. pPager->journalOff = 0;
  28492. }else{
  28493. /* This branch may be executed with Pager.journalMode==MEMORY if
  28494. ** a hot-journal was just rolled back. In this case the journal
  28495. ** file should be closed and deleted. If this connection writes to
  28496. ** the database file, it will do so using an in-memory journal.
  28497. */
  28498. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  28499. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  28500. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  28501. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  28502. );
  28503. sqlite3OsClose(pPager->jfd);
  28504. if( bDelete ){
  28505. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  28506. }
  28507. }
  28508. }
  28509. #ifdef SQLITE_CHECK_PAGES
  28510. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  28511. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  28512. PgHdr *p = pager_lookup(pPager, 1);
  28513. if( p ){
  28514. p->pageHash = 0;
  28515. sqlite3PagerUnref(p);
  28516. }
  28517. }
  28518. #endif
  28519. sqlite3BitvecDestroy(pPager->pInJournal);
  28520. pPager->pInJournal = 0;
  28521. pPager->nRec = 0;
  28522. sqlite3PcacheCleanAll(pPager->pPCache);
  28523. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  28524. if( pagerUseWal(pPager) ){
  28525. /* Drop the WAL write-lock, if any. Also, if the connection was in
  28526. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  28527. ** lock held on the database file.
  28528. */
  28529. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  28530. assert( rc2==SQLITE_OK );
  28531. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  28532. /* This branch is taken when committing a transaction in rollback-journal
  28533. ** mode if the database file on disk is larger than the database image.
  28534. ** At this point the journal has been finalized and the transaction
  28535. ** successfully committed, but the EXCLUSIVE lock is still held on the
  28536. ** file. So it is safe to truncate the database file to its minimum
  28537. ** required size. */
  28538. assert( pPager->eLock==EXCLUSIVE_LOCK );
  28539. rc = pager_truncate(pPager, pPager->dbSize);
  28540. }
  28541. if( !pPager->exclusiveMode
  28542. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  28543. ){
  28544. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  28545. pPager->changeCountDone = 0;
  28546. }
  28547. pPager->eState = PAGER_READER;
  28548. pPager->setMaster = 0;
  28549. return (rc==SQLITE_OK?rc2:rc);
  28550. }
  28551. /*
  28552. ** Execute a rollback if a transaction is active and unlock the
  28553. ** database file.
  28554. **
  28555. ** If the pager has already entered the ERROR state, do not attempt
  28556. ** the rollback at this time. Instead, pager_unlock() is called. The
  28557. ** call to pager_unlock() will discard all in-memory pages, unlock
  28558. ** the database file and move the pager back to OPEN state. If this
  28559. ** means that there is a hot-journal left in the file-system, the next
  28560. ** connection to obtain a shared lock on the pager (which may be this one)
  28561. ** will roll it back.
  28562. **
  28563. ** If the pager has not already entered the ERROR state, but an IO or
  28564. ** malloc error occurs during a rollback, then this will itself cause
  28565. ** the pager to enter the ERROR state. Which will be cleared by the
  28566. ** call to pager_unlock(), as described above.
  28567. */
  28568. static void pagerUnlockAndRollback(Pager *pPager){
  28569. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  28570. assert( assert_pager_state(pPager) );
  28571. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  28572. sqlite3BeginBenignMalloc();
  28573. sqlite3PagerRollback(pPager);
  28574. sqlite3EndBenignMalloc();
  28575. }else if( !pPager->exclusiveMode ){
  28576. assert( pPager->eState==PAGER_READER );
  28577. pager_end_transaction(pPager, 0, 0);
  28578. }
  28579. }
  28580. pager_unlock(pPager);
  28581. }
  28582. /*
  28583. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  28584. ** of data. Compute and return a checksum based ont the contents of the
  28585. ** page of data and the current value of pPager->cksumInit.
  28586. **
  28587. ** This is not a real checksum. It is really just the sum of the
  28588. ** random initial value (pPager->cksumInit) and every 200th byte
  28589. ** of the page data, starting with byte offset (pPager->pageSize%200).
  28590. ** Each byte is interpreted as an 8-bit unsigned integer.
  28591. **
  28592. ** Changing the formula used to compute this checksum results in an
  28593. ** incompatible journal file format.
  28594. **
  28595. ** If journal corruption occurs due to a power failure, the most likely
  28596. ** scenario is that one end or the other of the record will be changed.
  28597. ** It is much less likely that the two ends of the journal record will be
  28598. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  28599. ** though fast and simple, catches the mostly likely kind of corruption.
  28600. */
  28601. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  28602. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  28603. int i = pPager->pageSize-200; /* Loop counter */
  28604. while( i>0 ){
  28605. cksum += aData[i];
  28606. i -= 200;
  28607. }
  28608. return cksum;
  28609. }
  28610. /*
  28611. ** Report the current page size and number of reserved bytes back
  28612. ** to the codec.
  28613. */
  28614. #ifdef SQLITE_HAS_CODEC
  28615. static void pagerReportSize(Pager *pPager){
  28616. if( pPager->xCodecSizeChng ){
  28617. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  28618. (int)pPager->nReserve);
  28619. }
  28620. }
  28621. #else
  28622. # define pagerReportSize(X) /* No-op if we do not support a codec */
  28623. #endif
  28624. /*
  28625. ** Read a single page from either the journal file (if isMainJrnl==1) or
  28626. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  28627. ** The page begins at offset *pOffset into the file. The *pOffset
  28628. ** value is increased to the start of the next page in the journal.
  28629. **
  28630. ** The main rollback journal uses checksums - the statement journal does
  28631. ** not.
  28632. **
  28633. ** If the page number of the page record read from the (sub-)journal file
  28634. ** is greater than the current value of Pager.dbSize, then playback is
  28635. ** skipped and SQLITE_OK is returned.
  28636. **
  28637. ** If pDone is not NULL, then it is a record of pages that have already
  28638. ** been played back. If the page at *pOffset has already been played back
  28639. ** (if the corresponding pDone bit is set) then skip the playback.
  28640. ** Make sure the pDone bit corresponding to the *pOffset page is set
  28641. ** prior to returning.
  28642. **
  28643. ** If the page record is successfully read from the (sub-)journal file
  28644. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  28645. ** while reading the record from the (sub-)journal file or while writing
  28646. ** to the database file, then the IO error code is returned. If data
  28647. ** is successfully read from the (sub-)journal file but appears to be
  28648. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  28649. ** two circumstances:
  28650. **
  28651. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  28652. ** * If the record is being rolled back from the main journal file
  28653. ** and the checksum field does not match the record content.
  28654. **
  28655. ** Neither of these two scenarios are possible during a savepoint rollback.
  28656. **
  28657. ** If this is a savepoint rollback, then memory may have to be dynamically
  28658. ** allocated by this function. If this is the case and an allocation fails,
  28659. ** SQLITE_NOMEM is returned.
  28660. */
  28661. static int pager_playback_one_page(
  28662. Pager *pPager, /* The pager being played back */
  28663. i64 *pOffset, /* Offset of record to playback */
  28664. Bitvec *pDone, /* Bitvec of pages already played back */
  28665. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  28666. int isSavepnt /* True for a savepoint rollback */
  28667. ){
  28668. int rc;
  28669. PgHdr *pPg; /* An existing page in the cache */
  28670. Pgno pgno; /* The page number of a page in journal */
  28671. u32 cksum; /* Checksum used for sanity checking */
  28672. char *aData; /* Temporary storage for the page */
  28673. sqlite3_file *jfd; /* The file descriptor for the journal file */
  28674. int isSynced; /* True if journal page is synced */
  28675. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  28676. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  28677. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  28678. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  28679. aData = pPager->pTmpSpace;
  28680. assert( aData ); /* Temp storage must have already been allocated */
  28681. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  28682. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  28683. ** or savepoint rollback done at the request of the caller) or this is
  28684. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  28685. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  28686. ** only reads from the main journal, not the sub-journal.
  28687. */
  28688. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  28689. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  28690. );
  28691. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  28692. /* Read the page number and page data from the journal or sub-journal
  28693. ** file. Return an error code to the caller if an IO error occurs.
  28694. */
  28695. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  28696. rc = read32bits(jfd, *pOffset, &pgno);
  28697. if( rc!=SQLITE_OK ) return rc;
  28698. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  28699. if( rc!=SQLITE_OK ) return rc;
  28700. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  28701. /* Sanity checking on the page. This is more important that I originally
  28702. ** thought. If a power failure occurs while the journal is being written,
  28703. ** it could cause invalid data to be written into the journal. We need to
  28704. ** detect this invalid data (with high probability) and ignore it.
  28705. */
  28706. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  28707. assert( !isSavepnt );
  28708. return SQLITE_DONE;
  28709. }
  28710. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  28711. return SQLITE_OK;
  28712. }
  28713. if( isMainJrnl ){
  28714. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  28715. if( rc ) return rc;
  28716. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  28717. return SQLITE_DONE;
  28718. }
  28719. }
  28720. /* If this page has already been played by before during the current
  28721. ** rollback, then don't bother to play it back again.
  28722. */
  28723. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  28724. return rc;
  28725. }
  28726. /* When playing back page 1, restore the nReserve setting
  28727. */
  28728. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  28729. pPager->nReserve = ((u8*)aData)[20];
  28730. pagerReportSize(pPager);
  28731. }
  28732. /* If the pager is in CACHEMOD state, then there must be a copy of this
  28733. ** page in the pager cache. In this case just update the pager cache,
  28734. ** not the database file. The page is left marked dirty in this case.
  28735. **
  28736. ** An exception to the above rule: If the database is in no-sync mode
  28737. ** and a page is moved during an incremental vacuum then the page may
  28738. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  28739. ** during a Movepage() call, then the page may not be in the cache
  28740. ** either. So the condition described in the above paragraph is not
  28741. ** assert()able.
  28742. **
  28743. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  28744. ** pager cache if it exists and the main file. The page is then marked
  28745. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  28746. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  28747. ** if the pager is in OPEN state.
  28748. **
  28749. ** Ticket #1171: The statement journal might contain page content that is
  28750. ** different from the page content at the start of the transaction.
  28751. ** This occurs when a page is changed prior to the start of a statement
  28752. ** then changed again within the statement. When rolling back such a
  28753. ** statement we must not write to the original database unless we know
  28754. ** for certain that original page contents are synced into the main rollback
  28755. ** journal. Otherwise, a power loss might leave modified data in the
  28756. ** database file without an entry in the rollback journal that can
  28757. ** restore the database to its original form. Two conditions must be
  28758. ** met before writing to the database files. (1) the database must be
  28759. ** locked. (2) we know that the original page content is fully synced
  28760. ** in the main journal either because the page is not in cache or else
  28761. ** the page is marked as needSync==0.
  28762. **
  28763. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  28764. ** is possible to fail a statement on a database that does not yet exist.
  28765. ** Do not attempt to write if database file has never been opened.
  28766. */
  28767. if( pagerUseWal(pPager) ){
  28768. pPg = 0;
  28769. }else{
  28770. pPg = pager_lookup(pPager, pgno);
  28771. }
  28772. assert( pPg || !MEMDB );
  28773. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  28774. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  28775. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  28776. (isMainJrnl?"main-journal":"sub-journal")
  28777. ));
  28778. if( isMainJrnl ){
  28779. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  28780. }else{
  28781. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  28782. }
  28783. if( isOpen(pPager->fd)
  28784. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  28785. && isSynced
  28786. ){
  28787. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  28788. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  28789. assert( !pagerUseWal(pPager) );
  28790. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  28791. if( pgno>pPager->dbFileSize ){
  28792. pPager->dbFileSize = pgno;
  28793. }
  28794. if( pPager->pBackup ){
  28795. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  28796. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  28797. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  28798. }
  28799. }else if( !isMainJrnl && pPg==0 ){
  28800. /* If this is a rollback of a savepoint and data was not written to
  28801. ** the database and the page is not in-memory, there is a potential
  28802. ** problem. When the page is next fetched by the b-tree layer, it
  28803. ** will be read from the database file, which may or may not be
  28804. ** current.
  28805. **
  28806. ** There are a couple of different ways this can happen. All are quite
  28807. ** obscure. When running in synchronous mode, this can only happen
  28808. ** if the page is on the free-list at the start of the transaction, then
  28809. ** populated, then moved using sqlite3PagerMovepage().
  28810. **
  28811. ** The solution is to add an in-memory page to the cache containing
  28812. ** the data just read from the sub-journal. Mark the page as dirty
  28813. ** and if the pager requires a journal-sync, then mark the page as
  28814. ** requiring a journal-sync before it is written.
  28815. */
  28816. assert( isSavepnt );
  28817. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  28818. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  28819. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  28820. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  28821. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  28822. if( rc!=SQLITE_OK ) return rc;
  28823. pPg->flags &= ~PGHDR_NEED_READ;
  28824. sqlite3PcacheMakeDirty(pPg);
  28825. }
  28826. if( pPg ){
  28827. /* No page should ever be explicitly rolled back that is in use, except
  28828. ** for page 1 which is held in use in order to keep the lock on the
  28829. ** database active. However such a page may be rolled back as a result
  28830. ** of an internal error resulting in an automatic call to
  28831. ** sqlite3PagerRollback().
  28832. */
  28833. void *pData;
  28834. pData = pPg->pData;
  28835. memcpy(pData, (u8*)aData, pPager->pageSize);
  28836. pPager->xReiniter(pPg);
  28837. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  28838. /* If the contents of this page were just restored from the main
  28839. ** journal file, then its content must be as they were when the
  28840. ** transaction was first opened. In this case we can mark the page
  28841. ** as clean, since there will be no need to write it out to the
  28842. ** database.
  28843. **
  28844. ** There is one exception to this rule. If the page is being rolled
  28845. ** back as part of a savepoint (or statement) rollback from an
  28846. ** unsynced portion of the main journal file, then it is not safe
  28847. ** to mark the page as clean. This is because marking the page as
  28848. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  28849. ** already in the journal file (recorded in Pager.pInJournal) and
  28850. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  28851. ** again within this transaction, it will be marked as dirty but
  28852. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  28853. ** be written out into the database file before its journal file
  28854. ** segment is synced. If a crash occurs during or following this,
  28855. ** database corruption may ensue.
  28856. */
  28857. assert( !pagerUseWal(pPager) );
  28858. sqlite3PcacheMakeClean(pPg);
  28859. }
  28860. pager_set_pagehash(pPg);
  28861. /* If this was page 1, then restore the value of Pager.dbFileVers.
  28862. ** Do this before any decoding. */
  28863. if( pgno==1 ){
  28864. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  28865. }
  28866. /* Decode the page just read from disk */
  28867. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  28868. sqlite3PcacheRelease(pPg);
  28869. }
  28870. return rc;
  28871. }
  28872. /*
  28873. ** Parameter zMaster is the name of a master journal file. A single journal
  28874. ** file that referred to the master journal file has just been rolled back.
  28875. ** This routine checks if it is possible to delete the master journal file,
  28876. ** and does so if it is.
  28877. **
  28878. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  28879. ** available for use within this function.
  28880. **
  28881. ** When a master journal file is created, it is populated with the names
  28882. ** of all of its child journals, one after another, formatted as utf-8
  28883. ** encoded text. The end of each child journal file is marked with a
  28884. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  28885. ** file for a transaction involving two databases might be:
  28886. **
  28887. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  28888. **
  28889. ** A master journal file may only be deleted once all of its child
  28890. ** journals have been rolled back.
  28891. **
  28892. ** This function reads the contents of the master-journal file into
  28893. ** memory and loops through each of the child journal names. For
  28894. ** each child journal, it checks if:
  28895. **
  28896. ** * if the child journal exists, and if so
  28897. ** * if the child journal contains a reference to master journal
  28898. ** file zMaster
  28899. **
  28900. ** If a child journal can be found that matches both of the criteria
  28901. ** above, this function returns without doing anything. Otherwise, if
  28902. ** no such child journal can be found, file zMaster is deleted from
  28903. ** the file-system using sqlite3OsDelete().
  28904. **
  28905. ** If an IO error within this function, an error code is returned. This
  28906. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  28907. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  28908. ** occur, SQLITE_OK is returned.
  28909. **
  28910. ** TODO: This function allocates a single block of memory to load
  28911. ** the entire contents of the master journal file. This could be
  28912. ** a couple of kilobytes or so - potentially larger than the page
  28913. ** size.
  28914. */
  28915. static int pager_delmaster(Pager *pPager, const char *zMaster){
  28916. sqlite3_vfs *pVfs = pPager->pVfs;
  28917. int rc; /* Return code */
  28918. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  28919. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  28920. char *zMasterJournal = 0; /* Contents of master journal file */
  28921. i64 nMasterJournal; /* Size of master journal file */
  28922. char *zJournal; /* Pointer to one journal within MJ file */
  28923. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  28924. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  28925. /* Allocate space for both the pJournal and pMaster file descriptors.
  28926. ** If successful, open the master journal file for reading.
  28927. */
  28928. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  28929. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  28930. if( !pMaster ){
  28931. rc = SQLITE_NOMEM;
  28932. }else{
  28933. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  28934. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  28935. }
  28936. if( rc!=SQLITE_OK ) goto delmaster_out;
  28937. /* Load the entire master journal file into space obtained from
  28938. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  28939. ** sufficient space (in zMasterPtr) to hold the names of master
  28940. ** journal files extracted from regular rollback-journals.
  28941. */
  28942. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  28943. if( rc!=SQLITE_OK ) goto delmaster_out;
  28944. nMasterPtr = pVfs->mxPathname+1;
  28945. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  28946. if( !zMasterJournal ){
  28947. rc = SQLITE_NOMEM;
  28948. goto delmaster_out;
  28949. }
  28950. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  28951. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  28952. if( rc!=SQLITE_OK ) goto delmaster_out;
  28953. zMasterJournal[nMasterJournal] = 0;
  28954. zJournal = zMasterJournal;
  28955. while( (zJournal-zMasterJournal)<nMasterJournal ){
  28956. int exists;
  28957. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  28958. if( rc!=SQLITE_OK ){
  28959. goto delmaster_out;
  28960. }
  28961. if( exists ){
  28962. /* One of the journals pointed to by the master journal exists.
  28963. ** Open it and check if it points at the master journal. If
  28964. ** so, return without deleting the master journal file.
  28965. */
  28966. int c;
  28967. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  28968. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  28969. if( rc!=SQLITE_OK ){
  28970. goto delmaster_out;
  28971. }
  28972. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  28973. sqlite3OsClose(pJournal);
  28974. if( rc!=SQLITE_OK ){
  28975. goto delmaster_out;
  28976. }
  28977. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  28978. if( c ){
  28979. /* We have a match. Do not delete the master journal file. */
  28980. goto delmaster_out;
  28981. }
  28982. }
  28983. zJournal += (sqlite3Strlen30(zJournal)+1);
  28984. }
  28985. sqlite3OsClose(pMaster);
  28986. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  28987. delmaster_out:
  28988. sqlite3_free(zMasterJournal);
  28989. if( pMaster ){
  28990. sqlite3OsClose(pMaster);
  28991. assert( !isOpen(pJournal) );
  28992. sqlite3_free(pMaster);
  28993. }
  28994. return rc;
  28995. }
  28996. /*
  28997. ** This function is used to change the actual size of the database
  28998. ** file in the file-system. This only happens when committing a transaction,
  28999. ** or rolling back a transaction (including rolling back a hot-journal).
  29000. **
  29001. ** If the main database file is not open, or the pager is not in either
  29002. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  29003. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  29004. ** If the file on disk is currently larger than nPage pages, then use the VFS
  29005. ** xTruncate() method to truncate it.
  29006. **
  29007. ** Or, it might might be the case that the file on disk is smaller than
  29008. ** nPage pages. Some operating system implementations can get confused if
  29009. ** you try to truncate a file to some size that is larger than it
  29010. ** currently is, so detect this case and write a single zero byte to
  29011. ** the end of the new file instead.
  29012. **
  29013. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  29014. ** the database file, return the error code to the caller.
  29015. */
  29016. static int pager_truncate(Pager *pPager, Pgno nPage){
  29017. int rc = SQLITE_OK;
  29018. assert( pPager->eState!=PAGER_ERROR );
  29019. assert( pPager->eState!=PAGER_READER );
  29020. if( isOpen(pPager->fd)
  29021. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  29022. ){
  29023. i64 currentSize, newSize;
  29024. int szPage = pPager->pageSize;
  29025. assert( pPager->eLock==EXCLUSIVE_LOCK );
  29026. /* TODO: Is it safe to use Pager.dbFileSize here? */
  29027. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  29028. newSize = szPage*(i64)nPage;
  29029. if( rc==SQLITE_OK && currentSize!=newSize ){
  29030. if( currentSize>newSize ){
  29031. rc = sqlite3OsTruncate(pPager->fd, newSize);
  29032. }else if( (currentSize+szPage)<=newSize ){
  29033. char *pTmp = pPager->pTmpSpace;
  29034. memset(pTmp, 0, szPage);
  29035. testcase( (newSize-szPage) == currentSize );
  29036. testcase( (newSize-szPage) > currentSize );
  29037. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  29038. }
  29039. if( rc==SQLITE_OK ){
  29040. pPager->dbFileSize = nPage;
  29041. }
  29042. }
  29043. }
  29044. return rc;
  29045. }
  29046. /*
  29047. ** Return a sanitized version of the sector-size of OS file pFile. The
  29048. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  29049. */
  29050. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  29051. int iRet = sqlite3OsSectorSize(pFile);
  29052. if( iRet<32 ){
  29053. iRet = 512;
  29054. }else if( iRet>MAX_SECTOR_SIZE ){
  29055. assert( MAX_SECTOR_SIZE>=512 );
  29056. iRet = MAX_SECTOR_SIZE;
  29057. }
  29058. return iRet;
  29059. }
  29060. /*
  29061. ** Set the value of the Pager.sectorSize variable for the given
  29062. ** pager based on the value returned by the xSectorSize method
  29063. ** of the open database file. The sector size will be used used
  29064. ** to determine the size and alignment of journal header and
  29065. ** master journal pointers within created journal files.
  29066. **
  29067. ** For temporary files the effective sector size is always 512 bytes.
  29068. **
  29069. ** Otherwise, for non-temporary files, the effective sector size is
  29070. ** the value returned by the xSectorSize() method rounded up to 32 if
  29071. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  29072. ** is greater than MAX_SECTOR_SIZE.
  29073. **
  29074. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  29075. ** the effective sector size to its minimum value (512). The purpose of
  29076. ** pPager->sectorSize is to define the "blast radius" of bytes that
  29077. ** might change if a crash occurs while writing to a single byte in
  29078. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  29079. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  29080. ** size. For backwards compatibility of the rollback journal file format,
  29081. ** we cannot reduce the effective sector size below 512.
  29082. */
  29083. static void setSectorSize(Pager *pPager){
  29084. assert( isOpen(pPager->fd) || pPager->tempFile );
  29085. if( pPager->tempFile
  29086. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  29087. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  29088. ){
  29089. /* Sector size doesn't matter for temporary files. Also, the file
  29090. ** may not have been opened yet, in which case the OsSectorSize()
  29091. ** call will segfault. */
  29092. pPager->sectorSize = 512;
  29093. }else{
  29094. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  29095. }
  29096. }
  29097. /*
  29098. ** Playback the journal and thus restore the database file to
  29099. ** the state it was in before we started making changes.
  29100. **
  29101. ** The journal file format is as follows:
  29102. **
  29103. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  29104. ** (2) 4 byte big-endian integer which is the number of valid page records
  29105. ** in the journal. If this value is 0xffffffff, then compute the
  29106. ** number of page records from the journal size.
  29107. ** (3) 4 byte big-endian integer which is the initial value for the
  29108. ** sanity checksum.
  29109. ** (4) 4 byte integer which is the number of pages to truncate the
  29110. ** database to during a rollback.
  29111. ** (5) 4 byte big-endian integer which is the sector size. The header
  29112. ** is this many bytes in size.
  29113. ** (6) 4 byte big-endian integer which is the page size.
  29114. ** (7) zero padding out to the next sector size.
  29115. ** (8) Zero or more pages instances, each as follows:
  29116. ** + 4 byte page number.
  29117. ** + pPager->pageSize bytes of data.
  29118. ** + 4 byte checksum
  29119. **
  29120. ** When we speak of the journal header, we mean the first 7 items above.
  29121. ** Each entry in the journal is an instance of the 8th item.
  29122. **
  29123. ** Call the value from the second bullet "nRec". nRec is the number of
  29124. ** valid page entries in the journal. In most cases, you can compute the
  29125. ** value of nRec from the size of the journal file. But if a power
  29126. ** failure occurred while the journal was being written, it could be the
  29127. ** case that the size of the journal file had already been increased but
  29128. ** the extra entries had not yet made it safely to disk. In such a case,
  29129. ** the value of nRec computed from the file size would be too large. For
  29130. ** that reason, we always use the nRec value in the header.
  29131. **
  29132. ** If the nRec value is 0xffffffff it means that nRec should be computed
  29133. ** from the file size. This value is used when the user selects the
  29134. ** no-sync option for the journal. A power failure could lead to corruption
  29135. ** in this case. But for things like temporary table (which will be
  29136. ** deleted when the power is restored) we don't care.
  29137. **
  29138. ** If the file opened as the journal file is not a well-formed
  29139. ** journal file then all pages up to the first corrupted page are rolled
  29140. ** back (or no pages if the journal header is corrupted). The journal file
  29141. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  29142. ** been encountered.
  29143. **
  29144. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  29145. ** and an error code is returned.
  29146. **
  29147. ** The isHot parameter indicates that we are trying to rollback a journal
  29148. ** that might be a hot journal. Or, it could be that the journal is
  29149. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  29150. ** If the journal really is hot, reset the pager cache prior rolling
  29151. ** back any content. If the journal is merely persistent, no reset is
  29152. ** needed.
  29153. */
  29154. static int pager_playback(Pager *pPager, int isHot){
  29155. sqlite3_vfs *pVfs = pPager->pVfs;
  29156. i64 szJ; /* Size of the journal file in bytes */
  29157. u32 nRec; /* Number of Records in the journal */
  29158. u32 u; /* Unsigned loop counter */
  29159. Pgno mxPg = 0; /* Size of the original file in pages */
  29160. int rc; /* Result code of a subroutine */
  29161. int res = 1; /* Value returned by sqlite3OsAccess() */
  29162. char *zMaster = 0; /* Name of master journal file if any */
  29163. int needPagerReset; /* True to reset page prior to first page rollback */
  29164. int nPlayback = 0; /* Total number of pages restored from journal */
  29165. /* Figure out how many records are in the journal. Abort early if
  29166. ** the journal is empty.
  29167. */
  29168. assert( isOpen(pPager->jfd) );
  29169. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  29170. if( rc!=SQLITE_OK ){
  29171. goto end_playback;
  29172. }
  29173. /* Read the master journal name from the journal, if it is present.
  29174. ** If a master journal file name is specified, but the file is not
  29175. ** present on disk, then the journal is not hot and does not need to be
  29176. ** played back.
  29177. **
  29178. ** TODO: Technically the following is an error because it assumes that
  29179. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  29180. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  29181. ** mxPathname is 512, which is the same as the minimum allowable value
  29182. ** for pageSize.
  29183. */
  29184. zMaster = pPager->pTmpSpace;
  29185. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  29186. if( rc==SQLITE_OK && zMaster[0] ){
  29187. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  29188. }
  29189. zMaster = 0;
  29190. if( rc!=SQLITE_OK || !res ){
  29191. goto end_playback;
  29192. }
  29193. pPager->journalOff = 0;
  29194. needPagerReset = isHot;
  29195. /* This loop terminates either when a readJournalHdr() or
  29196. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  29197. ** occurs.
  29198. */
  29199. while( 1 ){
  29200. /* Read the next journal header from the journal file. If there are
  29201. ** not enough bytes left in the journal file for a complete header, or
  29202. ** it is corrupted, then a process must have failed while writing it.
  29203. ** This indicates nothing more needs to be rolled back.
  29204. */
  29205. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  29206. if( rc!=SQLITE_OK ){
  29207. if( rc==SQLITE_DONE ){
  29208. rc = SQLITE_OK;
  29209. }
  29210. goto end_playback;
  29211. }
  29212. /* If nRec is 0xffffffff, then this journal was created by a process
  29213. ** working in no-sync mode. This means that the rest of the journal
  29214. ** file consists of pages, there are no more journal headers. Compute
  29215. ** the value of nRec based on this assumption.
  29216. */
  29217. if( nRec==0xffffffff ){
  29218. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  29219. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  29220. }
  29221. /* If nRec is 0 and this rollback is of a transaction created by this
  29222. ** process and if this is the final header in the journal, then it means
  29223. ** that this part of the journal was being filled but has not yet been
  29224. ** synced to disk. Compute the number of pages based on the remaining
  29225. ** size of the file.
  29226. **
  29227. ** The third term of the test was added to fix ticket #2565.
  29228. ** When rolling back a hot journal, nRec==0 always means that the next
  29229. ** chunk of the journal contains zero pages to be rolled back. But
  29230. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  29231. ** the journal, it means that the journal might contain additional
  29232. ** pages that need to be rolled back and that the number of pages
  29233. ** should be computed based on the journal file size.
  29234. */
  29235. if( nRec==0 && !isHot &&
  29236. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  29237. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  29238. }
  29239. /* If this is the first header read from the journal, truncate the
  29240. ** database file back to its original size.
  29241. */
  29242. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  29243. rc = pager_truncate(pPager, mxPg);
  29244. if( rc!=SQLITE_OK ){
  29245. goto end_playback;
  29246. }
  29247. pPager->dbSize = mxPg;
  29248. }
  29249. /* Copy original pages out of the journal and back into the
  29250. ** database file and/or page cache.
  29251. */
  29252. for(u=0; u<nRec; u++){
  29253. if( needPagerReset ){
  29254. pager_reset(pPager);
  29255. needPagerReset = 0;
  29256. }
  29257. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  29258. if( rc==SQLITE_OK ){
  29259. nPlayback++;
  29260. }else{
  29261. if( rc==SQLITE_DONE ){
  29262. pPager->journalOff = szJ;
  29263. break;
  29264. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  29265. /* If the journal has been truncated, simply stop reading and
  29266. ** processing the journal. This might happen if the journal was
  29267. ** not completely written and synced prior to a crash. In that
  29268. ** case, the database should have never been written in the
  29269. ** first place so it is OK to simply abandon the rollback. */
  29270. rc = SQLITE_OK;
  29271. goto end_playback;
  29272. }else{
  29273. /* If we are unable to rollback, quit and return the error
  29274. ** code. This will cause the pager to enter the error state
  29275. ** so that no further harm will be done. Perhaps the next
  29276. ** process to come along will be able to rollback the database.
  29277. */
  29278. goto end_playback;
  29279. }
  29280. }
  29281. }
  29282. }
  29283. /*NOTREACHED*/
  29284. assert( 0 );
  29285. end_playback:
  29286. /* Following a rollback, the database file should be back in its original
  29287. ** state prior to the start of the transaction, so invoke the
  29288. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  29289. ** assertion that the transaction counter was modified.
  29290. */
  29291. #ifdef SQLITE_DEBUG
  29292. if( pPager->fd->pMethods ){
  29293. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  29294. }
  29295. #endif
  29296. /* If this playback is happening automatically as a result of an IO or
  29297. ** malloc error that occurred after the change-counter was updated but
  29298. ** before the transaction was committed, then the change-counter
  29299. ** modification may just have been reverted. If this happens in exclusive
  29300. ** mode, then subsequent transactions performed by the connection will not
  29301. ** update the change-counter at all. This may lead to cache inconsistency
  29302. ** problems for other processes at some point in the future. So, just
  29303. ** in case this has happened, clear the changeCountDone flag now.
  29304. */
  29305. pPager->changeCountDone = pPager->tempFile;
  29306. if( rc==SQLITE_OK ){
  29307. zMaster = pPager->pTmpSpace;
  29308. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  29309. testcase( rc!=SQLITE_OK );
  29310. }
  29311. if( rc==SQLITE_OK
  29312. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  29313. ){
  29314. rc = sqlite3PagerSync(pPager);
  29315. }
  29316. if( rc==SQLITE_OK ){
  29317. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  29318. testcase( rc!=SQLITE_OK );
  29319. }
  29320. if( rc==SQLITE_OK && zMaster[0] && res ){
  29321. /* If there was a master journal and this routine will return success,
  29322. ** see if it is possible to delete the master journal.
  29323. */
  29324. rc = pager_delmaster(pPager, zMaster);
  29325. testcase( rc!=SQLITE_OK );
  29326. }
  29327. if( isHot && nPlayback ){
  29328. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  29329. nPlayback, pPager->zJournal);
  29330. }
  29331. /* The Pager.sectorSize variable may have been updated while rolling
  29332. ** back a journal created by a process with a different sector size
  29333. ** value. Reset it to the correct value for this process.
  29334. */
  29335. setSectorSize(pPager);
  29336. return rc;
  29337. }
  29338. /*
  29339. ** Read the content for page pPg out of the database file and into
  29340. ** pPg->pData. A shared lock or greater must be held on the database
  29341. ** file before this function is called.
  29342. **
  29343. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  29344. ** the value read from the database file.
  29345. **
  29346. ** If an IO error occurs, then the IO error is returned to the caller.
  29347. ** Otherwise, SQLITE_OK is returned.
  29348. */
  29349. static int readDbPage(PgHdr *pPg, u32 iFrame){
  29350. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  29351. Pgno pgno = pPg->pgno; /* Page number to read */
  29352. int rc = SQLITE_OK; /* Return code */
  29353. int pgsz = pPager->pageSize; /* Number of bytes to read */
  29354. assert( pPager->eState>=PAGER_READER && !MEMDB );
  29355. assert( isOpen(pPager->fd) );
  29356. #ifndef SQLITE_OMIT_WAL
  29357. if( iFrame ){
  29358. /* Try to pull the page from the write-ahead log. */
  29359. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  29360. }else
  29361. #endif
  29362. {
  29363. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  29364. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  29365. if( rc==SQLITE_IOERR_SHORT_READ ){
  29366. rc = SQLITE_OK;
  29367. }
  29368. }
  29369. if( pgno==1 ){
  29370. if( rc ){
  29371. /* If the read is unsuccessful, set the dbFileVers[] to something
  29372. ** that will never be a valid file version. dbFileVers[] is a copy
  29373. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  29374. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  29375. ** should be page numbers which are never 0xffffffff. So filling
  29376. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  29377. **
  29378. ** For an encrypted database, the situation is more complex: bytes
  29379. ** 24..39 of the database are white noise. But the probability of
  29380. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  29381. ** we should still be ok.
  29382. */
  29383. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  29384. }else{
  29385. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  29386. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  29387. }
  29388. }
  29389. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  29390. PAGER_INCR(sqlite3_pager_readdb_count);
  29391. PAGER_INCR(pPager->nRead);
  29392. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  29393. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  29394. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  29395. return rc;
  29396. }
  29397. /*
  29398. ** Update the value of the change-counter at offsets 24 and 92 in
  29399. ** the header and the sqlite version number at offset 96.
  29400. **
  29401. ** This is an unconditional update. See also the pager_incr_changecounter()
  29402. ** routine which only updates the change-counter if the update is actually
  29403. ** needed, as determined by the pPager->changeCountDone state variable.
  29404. */
  29405. static void pager_write_changecounter(PgHdr *pPg){
  29406. u32 change_counter;
  29407. /* Increment the value just read and write it back to byte 24. */
  29408. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  29409. put32bits(((char*)pPg->pData)+24, change_counter);
  29410. /* Also store the SQLite version number in bytes 96..99 and in
  29411. ** bytes 92..95 store the change counter for which the version number
  29412. ** is valid. */
  29413. put32bits(((char*)pPg->pData)+92, change_counter);
  29414. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  29415. }
  29416. #ifndef SQLITE_OMIT_WAL
  29417. /*
  29418. ** This function is invoked once for each page that has already been
  29419. ** written into the log file when a WAL transaction is rolled back.
  29420. ** Parameter iPg is the page number of said page. The pCtx argument
  29421. ** is actually a pointer to the Pager structure.
  29422. **
  29423. ** If page iPg is present in the cache, and has no outstanding references,
  29424. ** it is discarded. Otherwise, if there are one or more outstanding
  29425. ** references, the page content is reloaded from the database. If the
  29426. ** attempt to reload content from the database is required and fails,
  29427. ** return an SQLite error code. Otherwise, SQLITE_OK.
  29428. */
  29429. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  29430. int rc = SQLITE_OK;
  29431. Pager *pPager = (Pager *)pCtx;
  29432. PgHdr *pPg;
  29433. assert( pagerUseWal(pPager) );
  29434. pPg = sqlite3PagerLookup(pPager, iPg);
  29435. if( pPg ){
  29436. if( sqlite3PcachePageRefcount(pPg)==1 ){
  29437. sqlite3PcacheDrop(pPg);
  29438. }else{
  29439. u32 iFrame = 0;
  29440. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  29441. if( rc==SQLITE_OK ){
  29442. rc = readDbPage(pPg, iFrame);
  29443. }
  29444. if( rc==SQLITE_OK ){
  29445. pPager->xReiniter(pPg);
  29446. }
  29447. sqlite3PagerUnref(pPg);
  29448. }
  29449. }
  29450. /* Normally, if a transaction is rolled back, any backup processes are
  29451. ** updated as data is copied out of the rollback journal and into the
  29452. ** database. This is not generally possible with a WAL database, as
  29453. ** rollback involves simply truncating the log file. Therefore, if one
  29454. ** or more frames have already been written to the log (and therefore
  29455. ** also copied into the backup databases) as part of this transaction,
  29456. ** the backups must be restarted.
  29457. */
  29458. sqlite3BackupRestart(pPager->pBackup);
  29459. return rc;
  29460. }
  29461. /*
  29462. ** This function is called to rollback a transaction on a WAL database.
  29463. */
  29464. static int pagerRollbackWal(Pager *pPager){
  29465. int rc; /* Return Code */
  29466. PgHdr *pList; /* List of dirty pages to revert */
  29467. /* For all pages in the cache that are currently dirty or have already
  29468. ** been written (but not committed) to the log file, do one of the
  29469. ** following:
  29470. **
  29471. ** + Discard the cached page (if refcount==0), or
  29472. ** + Reload page content from the database (if refcount>0).
  29473. */
  29474. pPager->dbSize = pPager->dbOrigSize;
  29475. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  29476. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  29477. while( pList && rc==SQLITE_OK ){
  29478. PgHdr *pNext = pList->pDirty;
  29479. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  29480. pList = pNext;
  29481. }
  29482. return rc;
  29483. }
  29484. /*
  29485. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  29486. ** the contents of the list of pages headed by pList (connected by pDirty),
  29487. ** this function notifies any active backup processes that the pages have
  29488. ** changed.
  29489. **
  29490. ** The list of pages passed into this routine is always sorted by page number.
  29491. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  29492. */
  29493. static int pagerWalFrames(
  29494. Pager *pPager, /* Pager object */
  29495. PgHdr *pList, /* List of frames to log */
  29496. Pgno nTruncate, /* Database size after this commit */
  29497. int isCommit /* True if this is a commit */
  29498. ){
  29499. int rc; /* Return code */
  29500. int nList; /* Number of pages in pList */
  29501. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  29502. PgHdr *p; /* For looping over pages */
  29503. #endif
  29504. assert( pPager->pWal );
  29505. assert( pList );
  29506. #ifdef SQLITE_DEBUG
  29507. /* Verify that the page list is in accending order */
  29508. for(p=pList; p && p->pDirty; p=p->pDirty){
  29509. assert( p->pgno < p->pDirty->pgno );
  29510. }
  29511. #endif
  29512. assert( pList->pDirty==0 || isCommit );
  29513. if( isCommit ){
  29514. /* If a WAL transaction is being committed, there is no point in writing
  29515. ** any pages with page numbers greater than nTruncate into the WAL file.
  29516. ** They will never be read by any client. So remove them from the pDirty
  29517. ** list here. */
  29518. PgHdr *p;
  29519. PgHdr **ppNext = &pList;
  29520. nList = 0;
  29521. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  29522. if( p->pgno<=nTruncate ){
  29523. ppNext = &p->pDirty;
  29524. nList++;
  29525. }
  29526. }
  29527. assert( pList );
  29528. }else{
  29529. nList = 1;
  29530. }
  29531. pPager->aStat[PAGER_STAT_WRITE] += nList;
  29532. if( pList->pgno==1 ) pager_write_changecounter(pList);
  29533. rc = sqlite3WalFrames(pPager->pWal,
  29534. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  29535. );
  29536. if( rc==SQLITE_OK && pPager->pBackup ){
  29537. PgHdr *p;
  29538. for(p=pList; p; p=p->pDirty){
  29539. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  29540. }
  29541. }
  29542. #ifdef SQLITE_CHECK_PAGES
  29543. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  29544. for(p=pList; p; p=p->pDirty){
  29545. pager_set_pagehash(p);
  29546. }
  29547. #endif
  29548. return rc;
  29549. }
  29550. /*
  29551. ** Begin a read transaction on the WAL.
  29552. **
  29553. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  29554. ** makes a snapshot of the database at the current point in time and preserves
  29555. ** that snapshot for use by the reader in spite of concurrently changes by
  29556. ** other writers or checkpointers.
  29557. */
  29558. static int pagerBeginReadTransaction(Pager *pPager){
  29559. int rc; /* Return code */
  29560. int changed = 0; /* True if cache must be reset */
  29561. assert( pagerUseWal(pPager) );
  29562. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  29563. /* sqlite3WalEndReadTransaction() was not called for the previous
  29564. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  29565. ** are in locking_mode=NORMAL and EndRead() was previously called,
  29566. ** the duplicate call is harmless.
  29567. */
  29568. sqlite3WalEndReadTransaction(pPager->pWal);
  29569. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  29570. if( rc!=SQLITE_OK || changed ){
  29571. pager_reset(pPager);
  29572. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  29573. }
  29574. return rc;
  29575. }
  29576. #endif
  29577. /*
  29578. ** This function is called as part of the transition from PAGER_OPEN
  29579. ** to PAGER_READER state to determine the size of the database file
  29580. ** in pages (assuming the page size currently stored in Pager.pageSize).
  29581. **
  29582. ** If no error occurs, SQLITE_OK is returned and the size of the database
  29583. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  29584. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  29585. */
  29586. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  29587. Pgno nPage; /* Value to return via *pnPage */
  29588. /* Query the WAL sub-system for the database size. The WalDbsize()
  29589. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  29590. ** if the database size is not available. The database size is not
  29591. ** available from the WAL sub-system if the log file is empty or
  29592. ** contains no valid committed transactions.
  29593. */
  29594. assert( pPager->eState==PAGER_OPEN );
  29595. assert( pPager->eLock>=SHARED_LOCK );
  29596. nPage = sqlite3WalDbsize(pPager->pWal);
  29597. /* If the database size was not available from the WAL sub-system,
  29598. ** determine it based on the size of the database file. If the size
  29599. ** of the database file is not an integer multiple of the page-size,
  29600. ** round down to the nearest page. Except, any file larger than 0
  29601. ** bytes in size is considered to contain at least one page.
  29602. */
  29603. if( nPage==0 ){
  29604. i64 n = 0; /* Size of db file in bytes */
  29605. assert( isOpen(pPager->fd) || pPager->tempFile );
  29606. if( isOpen(pPager->fd) ){
  29607. int rc = sqlite3OsFileSize(pPager->fd, &n);
  29608. if( rc!=SQLITE_OK ){
  29609. return rc;
  29610. }
  29611. }
  29612. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  29613. }
  29614. /* If the current number of pages in the file is greater than the
  29615. ** configured maximum pager number, increase the allowed limit so
  29616. ** that the file can be read.
  29617. */
  29618. if( nPage>pPager->mxPgno ){
  29619. pPager->mxPgno = (Pgno)nPage;
  29620. }
  29621. *pnPage = nPage;
  29622. return SQLITE_OK;
  29623. }
  29624. #ifndef SQLITE_OMIT_WAL
  29625. /*
  29626. ** Check if the *-wal file that corresponds to the database opened by pPager
  29627. ** exists if the database is not empy, or verify that the *-wal file does
  29628. ** not exist (by deleting it) if the database file is empty.
  29629. **
  29630. ** If the database is not empty and the *-wal file exists, open the pager
  29631. ** in WAL mode. If the database is empty or if no *-wal file exists and
  29632. ** if no error occurs, make sure Pager.journalMode is not set to
  29633. ** PAGER_JOURNALMODE_WAL.
  29634. **
  29635. ** Return SQLITE_OK or an error code.
  29636. **
  29637. ** The caller must hold a SHARED lock on the database file to call this
  29638. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  29639. ** a WAL on a none-empty database, this ensures there is no race condition
  29640. ** between the xAccess() below and an xDelete() being executed by some
  29641. ** other connection.
  29642. */
  29643. static int pagerOpenWalIfPresent(Pager *pPager){
  29644. int rc = SQLITE_OK;
  29645. assert( pPager->eState==PAGER_OPEN );
  29646. assert( pPager->eLock>=SHARED_LOCK );
  29647. if( !pPager->tempFile ){
  29648. int isWal; /* True if WAL file exists */
  29649. Pgno nPage; /* Size of the database file */
  29650. rc = pagerPagecount(pPager, &nPage);
  29651. if( rc ) return rc;
  29652. if( nPage==0 ){
  29653. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  29654. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  29655. isWal = 0;
  29656. }else{
  29657. rc = sqlite3OsAccess(
  29658. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  29659. );
  29660. }
  29661. if( rc==SQLITE_OK ){
  29662. if( isWal ){
  29663. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  29664. rc = sqlite3PagerOpenWal(pPager, 0);
  29665. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  29666. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  29667. }
  29668. }
  29669. }
  29670. return rc;
  29671. }
  29672. #endif
  29673. /*
  29674. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  29675. ** the entire master journal file. The case pSavepoint==NULL occurs when
  29676. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  29677. ** savepoint.
  29678. **
  29679. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  29680. ** being rolled back), then the rollback consists of up to three stages,
  29681. ** performed in the order specified:
  29682. **
  29683. ** * Pages are played back from the main journal starting at byte
  29684. ** offset PagerSavepoint.iOffset and continuing to
  29685. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  29686. ** file if PagerSavepoint.iHdrOffset is zero.
  29687. **
  29688. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  29689. ** back starting from the journal header immediately following
  29690. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  29691. **
  29692. ** * Pages are then played back from the sub-journal file, starting
  29693. ** with the PagerSavepoint.iSubRec and continuing to the end of
  29694. ** the journal file.
  29695. **
  29696. ** Throughout the rollback process, each time a page is rolled back, the
  29697. ** corresponding bit is set in a bitvec structure (variable pDone in the
  29698. ** implementation below). This is used to ensure that a page is only
  29699. ** rolled back the first time it is encountered in either journal.
  29700. **
  29701. ** If pSavepoint is NULL, then pages are only played back from the main
  29702. ** journal file. There is no need for a bitvec in this case.
  29703. **
  29704. ** In either case, before playback commences the Pager.dbSize variable
  29705. ** is reset to the value that it held at the start of the savepoint
  29706. ** (or transaction). No page with a page-number greater than this value
  29707. ** is played back. If one is encountered it is simply skipped.
  29708. */
  29709. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  29710. i64 szJ; /* Effective size of the main journal */
  29711. i64 iHdrOff; /* End of first segment of main-journal records */
  29712. int rc = SQLITE_OK; /* Return code */
  29713. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  29714. assert( pPager->eState!=PAGER_ERROR );
  29715. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  29716. /* Allocate a bitvec to use to store the set of pages rolled back */
  29717. if( pSavepoint ){
  29718. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  29719. if( !pDone ){
  29720. return SQLITE_NOMEM;
  29721. }
  29722. }
  29723. /* Set the database size back to the value it was before the savepoint
  29724. ** being reverted was opened.
  29725. */
  29726. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  29727. pPager->changeCountDone = pPager->tempFile;
  29728. if( !pSavepoint && pagerUseWal(pPager) ){
  29729. return pagerRollbackWal(pPager);
  29730. }
  29731. /* Use pPager->journalOff as the effective size of the main rollback
  29732. ** journal. The actual file might be larger than this in
  29733. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  29734. ** past pPager->journalOff is off-limits to us.
  29735. */
  29736. szJ = pPager->journalOff;
  29737. assert( pagerUseWal(pPager)==0 || szJ==0 );
  29738. /* Begin by rolling back records from the main journal starting at
  29739. ** PagerSavepoint.iOffset and continuing to the next journal header.
  29740. ** There might be records in the main journal that have a page number
  29741. ** greater than the current database size (pPager->dbSize) but those
  29742. ** will be skipped automatically. Pages are added to pDone as they
  29743. ** are played back.
  29744. */
  29745. if( pSavepoint && !pagerUseWal(pPager) ){
  29746. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  29747. pPager->journalOff = pSavepoint->iOffset;
  29748. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  29749. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  29750. }
  29751. assert( rc!=SQLITE_DONE );
  29752. }else{
  29753. pPager->journalOff = 0;
  29754. }
  29755. /* Continue rolling back records out of the main journal starting at
  29756. ** the first journal header seen and continuing until the effective end
  29757. ** of the main journal file. Continue to skip out-of-range pages and
  29758. ** continue adding pages rolled back to pDone.
  29759. */
  29760. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  29761. u32 ii; /* Loop counter */
  29762. u32 nJRec = 0; /* Number of Journal Records */
  29763. u32 dummy;
  29764. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  29765. assert( rc!=SQLITE_DONE );
  29766. /*
  29767. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  29768. ** test is related to ticket #2565. See the discussion in the
  29769. ** pager_playback() function for additional information.
  29770. */
  29771. if( nJRec==0
  29772. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  29773. ){
  29774. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  29775. }
  29776. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  29777. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  29778. }
  29779. assert( rc!=SQLITE_DONE );
  29780. }
  29781. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  29782. /* Finally, rollback pages from the sub-journal. Page that were
  29783. ** previously rolled back out of the main journal (and are hence in pDone)
  29784. ** will be skipped. Out-of-range pages are also skipped.
  29785. */
  29786. if( pSavepoint ){
  29787. u32 ii; /* Loop counter */
  29788. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  29789. if( pagerUseWal(pPager) ){
  29790. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  29791. }
  29792. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  29793. assert( offset==(i64)ii*(4+pPager->pageSize) );
  29794. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  29795. }
  29796. assert( rc!=SQLITE_DONE );
  29797. }
  29798. sqlite3BitvecDestroy(pDone);
  29799. if( rc==SQLITE_OK ){
  29800. pPager->journalOff = szJ;
  29801. }
  29802. return rc;
  29803. }
  29804. /*
  29805. ** Change the maximum number of in-memory pages that are allowed.
  29806. */
  29807. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  29808. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  29809. }
  29810. /*
  29811. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  29812. */
  29813. static void pagerFixMaplimit(Pager *pPager){
  29814. #if SQLITE_MAX_MMAP_SIZE>0
  29815. sqlite3_file *fd = pPager->fd;
  29816. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  29817. sqlite3_int64 sz;
  29818. sz = pPager->szMmap;
  29819. pPager->bUseFetch = (sz>0);
  29820. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  29821. }
  29822. #endif
  29823. }
  29824. /*
  29825. ** Change the maximum size of any memory mapping made of the database file.
  29826. */
  29827. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  29828. pPager->szMmap = szMmap;
  29829. pagerFixMaplimit(pPager);
  29830. }
  29831. /*
  29832. ** Free as much memory as possible from the pager.
  29833. */
  29834. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  29835. sqlite3PcacheShrink(pPager->pPCache);
  29836. }
  29837. /*
  29838. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  29839. **
  29840. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  29841. ** of the database to damage due to OS crashes or power failures by
  29842. ** changing the number of syncs()s when writing the journals.
  29843. ** There are three levels:
  29844. **
  29845. ** OFF sqlite3OsSync() is never called. This is the default
  29846. ** for temporary and transient files.
  29847. **
  29848. ** NORMAL The journal is synced once before writes begin on the
  29849. ** database. This is normally adequate protection, but
  29850. ** it is theoretically possible, though very unlikely,
  29851. ** that an inopertune power failure could leave the journal
  29852. ** in a state which would cause damage to the database
  29853. ** when it is rolled back.
  29854. **
  29855. ** FULL The journal is synced twice before writes begin on the
  29856. ** database (with some additional information - the nRec field
  29857. ** of the journal header - being written in between the two
  29858. ** syncs). If we assume that writing a
  29859. ** single disk sector is atomic, then this mode provides
  29860. ** assurance that the journal will not be corrupted to the
  29861. ** point of causing damage to the database during rollback.
  29862. **
  29863. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  29864. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  29865. ** prior to the start of checkpoint and that the database file is synced
  29866. ** at the conclusion of the checkpoint if the entire content of the WAL
  29867. ** was written back into the database. But no sync operations occur for
  29868. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  29869. ** file is synced following each commit operation, in addition to the
  29870. ** syncs associated with NORMAL.
  29871. **
  29872. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  29873. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  29874. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  29875. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  29876. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  29877. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  29878. ** the xSync primitive is called and is relevant to all platforms.
  29879. **
  29880. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  29881. ** and FULL=3.
  29882. */
  29883. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  29884. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  29885. Pager *pPager, /* The pager to set safety level for */
  29886. unsigned pgFlags /* Various flags */
  29887. ){
  29888. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  29889. assert( level>=1 && level<=3 );
  29890. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  29891. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  29892. if( pPager->noSync ){
  29893. pPager->syncFlags = 0;
  29894. pPager->ckptSyncFlags = 0;
  29895. }else if( pgFlags & PAGER_FULLFSYNC ){
  29896. pPager->syncFlags = SQLITE_SYNC_FULL;
  29897. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  29898. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  29899. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  29900. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  29901. }else{
  29902. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  29903. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  29904. }
  29905. pPager->walSyncFlags = pPager->syncFlags;
  29906. if( pPager->fullSync ){
  29907. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  29908. }
  29909. if( pgFlags & PAGER_CACHESPILL ){
  29910. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  29911. }else{
  29912. pPager->doNotSpill |= SPILLFLAG_OFF;
  29913. }
  29914. }
  29915. #endif
  29916. /*
  29917. ** The following global variable is incremented whenever the library
  29918. ** attempts to open a temporary file. This information is used for
  29919. ** testing and analysis only.
  29920. */
  29921. #ifdef SQLITE_TEST
  29922. SQLITE_API int sqlite3_opentemp_count = 0;
  29923. #endif
  29924. /*
  29925. ** Open a temporary file.
  29926. **
  29927. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  29928. ** or some other error code if we fail. The OS will automatically
  29929. ** delete the temporary file when it is closed.
  29930. **
  29931. ** The flags passed to the VFS layer xOpen() call are those specified
  29932. ** by parameter vfsFlags ORed with the following:
  29933. **
  29934. ** SQLITE_OPEN_READWRITE
  29935. ** SQLITE_OPEN_CREATE
  29936. ** SQLITE_OPEN_EXCLUSIVE
  29937. ** SQLITE_OPEN_DELETEONCLOSE
  29938. */
  29939. static int pagerOpentemp(
  29940. Pager *pPager, /* The pager object */
  29941. sqlite3_file *pFile, /* Write the file descriptor here */
  29942. int vfsFlags /* Flags passed through to the VFS */
  29943. ){
  29944. int rc; /* Return code */
  29945. #ifdef SQLITE_TEST
  29946. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  29947. #endif
  29948. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  29949. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  29950. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  29951. assert( rc!=SQLITE_OK || isOpen(pFile) );
  29952. return rc;
  29953. }
  29954. /*
  29955. ** Set the busy handler function.
  29956. **
  29957. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  29958. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  29959. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  29960. ** lock. It does *not* invoke the busy handler when upgrading from
  29961. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  29962. ** (which occurs during hot-journal rollback). Summary:
  29963. **
  29964. ** Transition | Invokes xBusyHandler
  29965. ** --------------------------------------------------------
  29966. ** NO_LOCK -> SHARED_LOCK | Yes
  29967. ** SHARED_LOCK -> RESERVED_LOCK | No
  29968. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  29969. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  29970. **
  29971. ** If the busy-handler callback returns non-zero, the lock is
  29972. ** retried. If it returns zero, then the SQLITE_BUSY error is
  29973. ** returned to the caller of the pager API function.
  29974. */
  29975. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  29976. Pager *pPager, /* Pager object */
  29977. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  29978. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  29979. ){
  29980. pPager->xBusyHandler = xBusyHandler;
  29981. pPager->pBusyHandlerArg = pBusyHandlerArg;
  29982. if( isOpen(pPager->fd) ){
  29983. void **ap = (void **)&pPager->xBusyHandler;
  29984. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  29985. assert( ap[1]==pBusyHandlerArg );
  29986. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  29987. }
  29988. }
  29989. /*
  29990. ** Change the page size used by the Pager object. The new page size
  29991. ** is passed in *pPageSize.
  29992. **
  29993. ** If the pager is in the error state when this function is called, it
  29994. ** is a no-op. The value returned is the error state error code (i.e.
  29995. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  29996. **
  29997. ** Otherwise, if all of the following are true:
  29998. **
  29999. ** * the new page size (value of *pPageSize) is valid (a power
  30000. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  30001. **
  30002. ** * there are no outstanding page references, and
  30003. **
  30004. ** * the database is either not an in-memory database or it is
  30005. ** an in-memory database that currently consists of zero pages.
  30006. **
  30007. ** then the pager object page size is set to *pPageSize.
  30008. **
  30009. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  30010. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  30011. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  30012. ** In all other cases, SQLITE_OK is returned.
  30013. **
  30014. ** If the page size is not changed, either because one of the enumerated
  30015. ** conditions above is not true, the pager was in error state when this
  30016. ** function was called, or because the memory allocation attempt failed,
  30017. ** then *pPageSize is set to the old, retained page size before returning.
  30018. */
  30019. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  30020. int rc = SQLITE_OK;
  30021. /* It is not possible to do a full assert_pager_state() here, as this
  30022. ** function may be called from within PagerOpen(), before the state
  30023. ** of the Pager object is internally consistent.
  30024. **
  30025. ** At one point this function returned an error if the pager was in
  30026. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  30027. ** there is at least one outstanding page reference, this function
  30028. ** is a no-op for that case anyhow.
  30029. */
  30030. u32 pageSize = *pPageSize;
  30031. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  30032. if( (pPager->memDb==0 || pPager->dbSize==0)
  30033. && sqlite3PcacheRefCount(pPager->pPCache)==0
  30034. && pageSize && pageSize!=(u32)pPager->pageSize
  30035. ){
  30036. char *pNew = NULL; /* New temp space */
  30037. i64 nByte = 0;
  30038. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  30039. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  30040. }
  30041. if( rc==SQLITE_OK ){
  30042. pNew = (char *)sqlite3PageMalloc(pageSize);
  30043. if( !pNew ) rc = SQLITE_NOMEM;
  30044. }
  30045. if( rc==SQLITE_OK ){
  30046. pager_reset(pPager);
  30047. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  30048. pPager->pageSize = pageSize;
  30049. sqlite3PageFree(pPager->pTmpSpace);
  30050. pPager->pTmpSpace = pNew;
  30051. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  30052. }
  30053. }
  30054. *pPageSize = pPager->pageSize;
  30055. if( rc==SQLITE_OK ){
  30056. if( nReserve<0 ) nReserve = pPager->nReserve;
  30057. assert( nReserve>=0 && nReserve<1000 );
  30058. pPager->nReserve = (i16)nReserve;
  30059. pagerReportSize(pPager);
  30060. pagerFixMaplimit(pPager);
  30061. }
  30062. return rc;
  30063. }
  30064. /*
  30065. ** Return a pointer to the "temporary page" buffer held internally
  30066. ** by the pager. This is a buffer that is big enough to hold the
  30067. ** entire content of a database page. This buffer is used internally
  30068. ** during rollback and will be overwritten whenever a rollback
  30069. ** occurs. But other modules are free to use it too, as long as
  30070. ** no rollbacks are happening.
  30071. */
  30072. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  30073. return pPager->pTmpSpace;
  30074. }
  30075. /*
  30076. ** Attempt to set the maximum database page count if mxPage is positive.
  30077. ** Make no changes if mxPage is zero or negative. And never reduce the
  30078. ** maximum page count below the current size of the database.
  30079. **
  30080. ** Regardless of mxPage, return the current maximum page count.
  30081. */
  30082. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  30083. if( mxPage>0 ){
  30084. pPager->mxPgno = mxPage;
  30085. }
  30086. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  30087. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  30088. return pPager->mxPgno;
  30089. }
  30090. /*
  30091. ** The following set of routines are used to disable the simulated
  30092. ** I/O error mechanism. These routines are used to avoid simulated
  30093. ** errors in places where we do not care about errors.
  30094. **
  30095. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  30096. ** and generate no code.
  30097. */
  30098. #ifdef SQLITE_TEST
  30099. SQLITE_API extern int sqlite3_io_error_pending;
  30100. SQLITE_API extern int sqlite3_io_error_hit;
  30101. static int saved_cnt;
  30102. void disable_simulated_io_errors(void){
  30103. saved_cnt = sqlite3_io_error_pending;
  30104. sqlite3_io_error_pending = -1;
  30105. }
  30106. void enable_simulated_io_errors(void){
  30107. sqlite3_io_error_pending = saved_cnt;
  30108. }
  30109. #else
  30110. # define disable_simulated_io_errors()
  30111. # define enable_simulated_io_errors()
  30112. #endif
  30113. /*
  30114. ** Read the first N bytes from the beginning of the file into memory
  30115. ** that pDest points to.
  30116. **
  30117. ** If the pager was opened on a transient file (zFilename==""), or
  30118. ** opened on a file less than N bytes in size, the output buffer is
  30119. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  30120. ** function is used to read database headers, and a new transient or
  30121. ** zero sized database has a header than consists entirely of zeroes.
  30122. **
  30123. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  30124. ** the error code is returned to the caller and the contents of the
  30125. ** output buffer undefined.
  30126. */
  30127. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  30128. int rc = SQLITE_OK;
  30129. memset(pDest, 0, N);
  30130. assert( isOpen(pPager->fd) || pPager->tempFile );
  30131. /* This routine is only called by btree immediately after creating
  30132. ** the Pager object. There has not been an opportunity to transition
  30133. ** to WAL mode yet.
  30134. */
  30135. assert( !pagerUseWal(pPager) );
  30136. if( isOpen(pPager->fd) ){
  30137. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  30138. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  30139. if( rc==SQLITE_IOERR_SHORT_READ ){
  30140. rc = SQLITE_OK;
  30141. }
  30142. }
  30143. return rc;
  30144. }
  30145. /*
  30146. ** This function may only be called when a read-transaction is open on
  30147. ** the pager. It returns the total number of pages in the database.
  30148. **
  30149. ** However, if the file is between 1 and <page-size> bytes in size, then
  30150. ** this is considered a 1 page file.
  30151. */
  30152. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  30153. assert( pPager->eState>=PAGER_READER );
  30154. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  30155. *pnPage = (int)pPager->dbSize;
  30156. }
  30157. /*
  30158. ** Try to obtain a lock of type locktype on the database file. If
  30159. ** a similar or greater lock is already held, this function is a no-op
  30160. ** (returning SQLITE_OK immediately).
  30161. **
  30162. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  30163. ** the busy callback if the lock is currently not available. Repeat
  30164. ** until the busy callback returns false or until the attempt to
  30165. ** obtain the lock succeeds.
  30166. **
  30167. ** Return SQLITE_OK on success and an error code if we cannot obtain
  30168. ** the lock. If the lock is obtained successfully, set the Pager.state
  30169. ** variable to locktype before returning.
  30170. */
  30171. static int pager_wait_on_lock(Pager *pPager, int locktype){
  30172. int rc; /* Return code */
  30173. /* Check that this is either a no-op (because the requested lock is
  30174. ** already held, or one of the transistions that the busy-handler
  30175. ** may be invoked during, according to the comment above
  30176. ** sqlite3PagerSetBusyhandler().
  30177. */
  30178. assert( (pPager->eLock>=locktype)
  30179. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  30180. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  30181. );
  30182. do {
  30183. rc = pagerLockDb(pPager, locktype);
  30184. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  30185. return rc;
  30186. }
  30187. /*
  30188. ** Function assertTruncateConstraint(pPager) checks that one of the
  30189. ** following is true for all dirty pages currently in the page-cache:
  30190. **
  30191. ** a) The page number is less than or equal to the size of the
  30192. ** current database image, in pages, OR
  30193. **
  30194. ** b) if the page content were written at this time, it would not
  30195. ** be necessary to write the current content out to the sub-journal
  30196. ** (as determined by function subjRequiresPage()).
  30197. **
  30198. ** If the condition asserted by this function were not true, and the
  30199. ** dirty page were to be discarded from the cache via the pagerStress()
  30200. ** routine, pagerStress() would not write the current page content to
  30201. ** the database file. If a savepoint transaction were rolled back after
  30202. ** this happened, the correct behavior would be to restore the current
  30203. ** content of the page. However, since this content is not present in either
  30204. ** the database file or the portion of the rollback journal and
  30205. ** sub-journal rolled back the content could not be restored and the
  30206. ** database image would become corrupt. It is therefore fortunate that
  30207. ** this circumstance cannot arise.
  30208. */
  30209. #if defined(SQLITE_DEBUG)
  30210. static void assertTruncateConstraintCb(PgHdr *pPg){
  30211. assert( pPg->flags&PGHDR_DIRTY );
  30212. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  30213. }
  30214. static void assertTruncateConstraint(Pager *pPager){
  30215. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  30216. }
  30217. #else
  30218. # define assertTruncateConstraint(pPager)
  30219. #endif
  30220. /*
  30221. ** Truncate the in-memory database file image to nPage pages. This
  30222. ** function does not actually modify the database file on disk. It
  30223. ** just sets the internal state of the pager object so that the
  30224. ** truncation will be done when the current transaction is committed.
  30225. **
  30226. ** This function is only called right before committing a transaction.
  30227. ** Once this function has been called, the transaction must either be
  30228. ** rolled back or committed. It is not safe to call this function and
  30229. ** then continue writing to the database.
  30230. */
  30231. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  30232. assert( pPager->dbSize>=nPage );
  30233. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  30234. pPager->dbSize = nPage;
  30235. /* At one point the code here called assertTruncateConstraint() to
  30236. ** ensure that all pages being truncated away by this operation are,
  30237. ** if one or more savepoints are open, present in the savepoint
  30238. ** journal so that they can be restored if the savepoint is rolled
  30239. ** back. This is no longer necessary as this function is now only
  30240. ** called right before committing a transaction. So although the
  30241. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  30242. ** they cannot be rolled back. So the assertTruncateConstraint() call
  30243. ** is no longer correct. */
  30244. }
  30245. /*
  30246. ** This function is called before attempting a hot-journal rollback. It
  30247. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  30248. ** size of the journal file so that the pager_playback() routine knows
  30249. ** that the entire journal file has been synced.
  30250. **
  30251. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  30252. ** that if a power-failure occurs during the rollback, the process that
  30253. ** attempts rollback following system recovery sees the same journal
  30254. ** content as this process.
  30255. **
  30256. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  30257. ** an SQLite error code.
  30258. */
  30259. static int pagerSyncHotJournal(Pager *pPager){
  30260. int rc = SQLITE_OK;
  30261. if( !pPager->noSync ){
  30262. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  30263. }
  30264. if( rc==SQLITE_OK ){
  30265. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  30266. }
  30267. return rc;
  30268. }
  30269. /*
  30270. ** Obtain a reference to a memory mapped page object for page number pgno.
  30271. ** The new object will use the pointer pData, obtained from xFetch().
  30272. ** If successful, set *ppPage to point to the new page reference
  30273. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  30274. ** *ppPage to zero.
  30275. **
  30276. ** Page references obtained by calling this function should be released
  30277. ** by calling pagerReleaseMapPage().
  30278. */
  30279. static int pagerAcquireMapPage(
  30280. Pager *pPager, /* Pager object */
  30281. Pgno pgno, /* Page number */
  30282. void *pData, /* xFetch()'d data for this page */
  30283. PgHdr **ppPage /* OUT: Acquired page object */
  30284. ){
  30285. PgHdr *p; /* Memory mapped page to return */
  30286. if( pPager->pMmapFreelist ){
  30287. *ppPage = p = pPager->pMmapFreelist;
  30288. pPager->pMmapFreelist = p->pDirty;
  30289. p->pDirty = 0;
  30290. memset(p->pExtra, 0, pPager->nExtra);
  30291. }else{
  30292. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  30293. if( p==0 ){
  30294. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  30295. return SQLITE_NOMEM;
  30296. }
  30297. p->pExtra = (void *)&p[1];
  30298. p->flags = PGHDR_MMAP;
  30299. p->nRef = 1;
  30300. p->pPager = pPager;
  30301. }
  30302. assert( p->pExtra==(void *)&p[1] );
  30303. assert( p->pPage==0 );
  30304. assert( p->flags==PGHDR_MMAP );
  30305. assert( p->pPager==pPager );
  30306. assert( p->nRef==1 );
  30307. p->pgno = pgno;
  30308. p->pData = pData;
  30309. pPager->nMmapOut++;
  30310. return SQLITE_OK;
  30311. }
  30312. /*
  30313. ** Release a reference to page pPg. pPg must have been returned by an
  30314. ** earlier call to pagerAcquireMapPage().
  30315. */
  30316. static void pagerReleaseMapPage(PgHdr *pPg){
  30317. Pager *pPager = pPg->pPager;
  30318. pPager->nMmapOut--;
  30319. pPg->pDirty = pPager->pMmapFreelist;
  30320. pPager->pMmapFreelist = pPg;
  30321. assert( pPager->fd->pMethods->iVersion>=3 );
  30322. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  30323. }
  30324. /*
  30325. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  30326. */
  30327. static void pagerFreeMapHdrs(Pager *pPager){
  30328. PgHdr *p;
  30329. PgHdr *pNext;
  30330. for(p=pPager->pMmapFreelist; p; p=pNext){
  30331. pNext = p->pDirty;
  30332. sqlite3_free(p);
  30333. }
  30334. }
  30335. /*
  30336. ** Shutdown the page cache. Free all memory and close all files.
  30337. **
  30338. ** If a transaction was in progress when this routine is called, that
  30339. ** transaction is rolled back. All outstanding pages are invalidated
  30340. ** and their memory is freed. Any attempt to use a page associated
  30341. ** with this page cache after this function returns will likely
  30342. ** result in a coredump.
  30343. **
  30344. ** This function always succeeds. If a transaction is active an attempt
  30345. ** is made to roll it back. If an error occurs during the rollback
  30346. ** a hot journal may be left in the filesystem but no error is returned
  30347. ** to the caller.
  30348. */
  30349. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  30350. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  30351. assert( assert_pager_state(pPager) );
  30352. disable_simulated_io_errors();
  30353. sqlite3BeginBenignMalloc();
  30354. pagerFreeMapHdrs(pPager);
  30355. /* pPager->errCode = 0; */
  30356. pPager->exclusiveMode = 0;
  30357. #ifndef SQLITE_OMIT_WAL
  30358. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  30359. pPager->pWal = 0;
  30360. #endif
  30361. pager_reset(pPager);
  30362. if( MEMDB ){
  30363. pager_unlock(pPager);
  30364. }else{
  30365. /* If it is open, sync the journal file before calling UnlockAndRollback.
  30366. ** If this is not done, then an unsynced portion of the open journal
  30367. ** file may be played back into the database. If a power failure occurs
  30368. ** while this is happening, the database could become corrupt.
  30369. **
  30370. ** If an error occurs while trying to sync the journal, shift the pager
  30371. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  30372. ** database and close the journal file without attempting to roll it
  30373. ** back or finalize it. The next database user will have to do hot-journal
  30374. ** rollback before accessing the database file.
  30375. */
  30376. if( isOpen(pPager->jfd) ){
  30377. pager_error(pPager, pagerSyncHotJournal(pPager));
  30378. }
  30379. pagerUnlockAndRollback(pPager);
  30380. }
  30381. sqlite3EndBenignMalloc();
  30382. enable_simulated_io_errors();
  30383. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  30384. IOTRACE(("CLOSE %p\n", pPager))
  30385. sqlite3OsClose(pPager->jfd);
  30386. sqlite3OsClose(pPager->fd);
  30387. sqlite3PageFree(pTmp);
  30388. sqlite3PcacheClose(pPager->pPCache);
  30389. #ifdef SQLITE_HAS_CODEC
  30390. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  30391. #endif
  30392. assert( !pPager->aSavepoint && !pPager->pInJournal );
  30393. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  30394. sqlite3_free(pPager);
  30395. return SQLITE_OK;
  30396. }
  30397. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  30398. /*
  30399. ** Return the page number for page pPg.
  30400. */
  30401. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  30402. return pPg->pgno;
  30403. }
  30404. #endif
  30405. /*
  30406. ** Increment the reference count for page pPg.
  30407. */
  30408. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  30409. sqlite3PcacheRef(pPg);
  30410. }
  30411. /*
  30412. ** Sync the journal. In other words, make sure all the pages that have
  30413. ** been written to the journal have actually reached the surface of the
  30414. ** disk and can be restored in the event of a hot-journal rollback.
  30415. **
  30416. ** If the Pager.noSync flag is set, then this function is a no-op.
  30417. ** Otherwise, the actions required depend on the journal-mode and the
  30418. ** device characteristics of the file-system, as follows:
  30419. **
  30420. ** * If the journal file is an in-memory journal file, no action need
  30421. ** be taken.
  30422. **
  30423. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  30424. ** then the nRec field of the most recently written journal header
  30425. ** is updated to contain the number of journal records that have
  30426. ** been written following it. If the pager is operating in full-sync
  30427. ** mode, then the journal file is synced before this field is updated.
  30428. **
  30429. ** * If the device does not support the SEQUENTIAL property, then
  30430. ** journal file is synced.
  30431. **
  30432. ** Or, in pseudo-code:
  30433. **
  30434. ** if( NOT <in-memory journal> ){
  30435. ** if( NOT SAFE_APPEND ){
  30436. ** if( <full-sync mode> ) xSync(<journal file>);
  30437. ** <update nRec field>
  30438. ** }
  30439. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  30440. ** }
  30441. **
  30442. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  30443. ** page currently held in memory before returning SQLITE_OK. If an IO
  30444. ** error is encountered, then the IO error code is returned to the caller.
  30445. */
  30446. static int syncJournal(Pager *pPager, int newHdr){
  30447. int rc; /* Return code */
  30448. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  30449. || pPager->eState==PAGER_WRITER_DBMOD
  30450. );
  30451. assert( assert_pager_state(pPager) );
  30452. assert( !pagerUseWal(pPager) );
  30453. rc = sqlite3PagerExclusiveLock(pPager);
  30454. if( rc!=SQLITE_OK ) return rc;
  30455. if( !pPager->noSync ){
  30456. assert( !pPager->tempFile );
  30457. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  30458. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  30459. assert( isOpen(pPager->jfd) );
  30460. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  30461. /* This block deals with an obscure problem. If the last connection
  30462. ** that wrote to this database was operating in persistent-journal
  30463. ** mode, then the journal file may at this point actually be larger
  30464. ** than Pager.journalOff bytes. If the next thing in the journal
  30465. ** file happens to be a journal-header (written as part of the
  30466. ** previous connection's transaction), and a crash or power-failure
  30467. ** occurs after nRec is updated but before this connection writes
  30468. ** anything else to the journal file (or commits/rolls back its
  30469. ** transaction), then SQLite may become confused when doing the
  30470. ** hot-journal rollback following recovery. It may roll back all
  30471. ** of this connections data, then proceed to rolling back the old,
  30472. ** out-of-date data that follows it. Database corruption.
  30473. **
  30474. ** To work around this, if the journal file does appear to contain
  30475. ** a valid header following Pager.journalOff, then write a 0x00
  30476. ** byte to the start of it to prevent it from being recognized.
  30477. **
  30478. ** Variable iNextHdrOffset is set to the offset at which this
  30479. ** problematic header will occur, if it exists. aMagic is used
  30480. ** as a temporary buffer to inspect the first couple of bytes of
  30481. ** the potential journal header.
  30482. */
  30483. i64 iNextHdrOffset;
  30484. u8 aMagic[8];
  30485. u8 zHeader[sizeof(aJournalMagic)+4];
  30486. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  30487. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  30488. iNextHdrOffset = journalHdrOffset(pPager);
  30489. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  30490. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  30491. static const u8 zerobyte = 0;
  30492. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  30493. }
  30494. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  30495. return rc;
  30496. }
  30497. /* Write the nRec value into the journal file header. If in
  30498. ** full-synchronous mode, sync the journal first. This ensures that
  30499. ** all data has really hit the disk before nRec is updated to mark
  30500. ** it as a candidate for rollback.
  30501. **
  30502. ** This is not required if the persistent media supports the
  30503. ** SAFE_APPEND property. Because in this case it is not possible
  30504. ** for garbage data to be appended to the file, the nRec field
  30505. ** is populated with 0xFFFFFFFF when the journal header is written
  30506. ** and never needs to be updated.
  30507. */
  30508. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30509. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30510. IOTRACE(("JSYNC %p\n", pPager))
  30511. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  30512. if( rc!=SQLITE_OK ) return rc;
  30513. }
  30514. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  30515. rc = sqlite3OsWrite(
  30516. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  30517. );
  30518. if( rc!=SQLITE_OK ) return rc;
  30519. }
  30520. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30521. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30522. IOTRACE(("JSYNC %p\n", pPager))
  30523. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  30524. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  30525. );
  30526. if( rc!=SQLITE_OK ) return rc;
  30527. }
  30528. pPager->journalHdr = pPager->journalOff;
  30529. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  30530. pPager->nRec = 0;
  30531. rc = writeJournalHdr(pPager);
  30532. if( rc!=SQLITE_OK ) return rc;
  30533. }
  30534. }else{
  30535. pPager->journalHdr = pPager->journalOff;
  30536. }
  30537. }
  30538. /* Unless the pager is in noSync mode, the journal file was just
  30539. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  30540. ** all pages.
  30541. */
  30542. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  30543. pPager->eState = PAGER_WRITER_DBMOD;
  30544. assert( assert_pager_state(pPager) );
  30545. return SQLITE_OK;
  30546. }
  30547. /*
  30548. ** The argument is the first in a linked list of dirty pages connected
  30549. ** by the PgHdr.pDirty pointer. This function writes each one of the
  30550. ** in-memory pages in the list to the database file. The argument may
  30551. ** be NULL, representing an empty list. In this case this function is
  30552. ** a no-op.
  30553. **
  30554. ** The pager must hold at least a RESERVED lock when this function
  30555. ** is called. Before writing anything to the database file, this lock
  30556. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  30557. ** SQLITE_BUSY is returned and no data is written to the database file.
  30558. **
  30559. ** If the pager is a temp-file pager and the actual file-system file
  30560. ** is not yet open, it is created and opened before any data is
  30561. ** written out.
  30562. **
  30563. ** Once the lock has been upgraded and, if necessary, the file opened,
  30564. ** the pages are written out to the database file in list order. Writing
  30565. ** a page is skipped if it meets either of the following criteria:
  30566. **
  30567. ** * The page number is greater than Pager.dbSize, or
  30568. ** * The PGHDR_DONT_WRITE flag is set on the page.
  30569. **
  30570. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  30571. ** is updated accordingly. If page 1 is written out, then the value cached
  30572. ** in Pager.dbFileVers[] is updated to match the new value stored in
  30573. ** the database file.
  30574. **
  30575. ** If everything is successful, SQLITE_OK is returned. If an IO error
  30576. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  30577. ** be obtained, SQLITE_BUSY is returned.
  30578. */
  30579. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  30580. int rc = SQLITE_OK; /* Return code */
  30581. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  30582. assert( !pagerUseWal(pPager) );
  30583. assert( pPager->eState==PAGER_WRITER_DBMOD );
  30584. assert( pPager->eLock==EXCLUSIVE_LOCK );
  30585. /* If the file is a temp-file has not yet been opened, open it now. It
  30586. ** is not possible for rc to be other than SQLITE_OK if this branch
  30587. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  30588. */
  30589. if( !isOpen(pPager->fd) ){
  30590. assert( pPager->tempFile && rc==SQLITE_OK );
  30591. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  30592. }
  30593. /* Before the first write, give the VFS a hint of what the final
  30594. ** file size will be.
  30595. */
  30596. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  30597. if( rc==SQLITE_OK
  30598. && pPager->dbHintSize<pPager->dbSize
  30599. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  30600. ){
  30601. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  30602. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  30603. pPager->dbHintSize = pPager->dbSize;
  30604. }
  30605. while( rc==SQLITE_OK && pList ){
  30606. Pgno pgno = pList->pgno;
  30607. /* If there are dirty pages in the page cache with page numbers greater
  30608. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  30609. ** make the file smaller (presumably by auto-vacuum code). Do not write
  30610. ** any such pages to the file.
  30611. **
  30612. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  30613. ** set (set by sqlite3PagerDontWrite()).
  30614. */
  30615. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  30616. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  30617. char *pData; /* Data to write */
  30618. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  30619. if( pList->pgno==1 ) pager_write_changecounter(pList);
  30620. /* Encode the database */
  30621. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  30622. /* Write out the page data. */
  30623. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  30624. /* If page 1 was just written, update Pager.dbFileVers to match
  30625. ** the value now stored in the database file. If writing this
  30626. ** page caused the database file to grow, update dbFileSize.
  30627. */
  30628. if( pgno==1 ){
  30629. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  30630. }
  30631. if( pgno>pPager->dbFileSize ){
  30632. pPager->dbFileSize = pgno;
  30633. }
  30634. pPager->aStat[PAGER_STAT_WRITE]++;
  30635. /* Update any backup objects copying the contents of this pager. */
  30636. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  30637. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  30638. PAGERID(pPager), pgno, pager_pagehash(pList)));
  30639. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  30640. PAGER_INCR(sqlite3_pager_writedb_count);
  30641. }else{
  30642. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  30643. }
  30644. pager_set_pagehash(pList);
  30645. pList = pList->pDirty;
  30646. }
  30647. return rc;
  30648. }
  30649. /*
  30650. ** Ensure that the sub-journal file is open. If it is already open, this
  30651. ** function is a no-op.
  30652. **
  30653. ** SQLITE_OK is returned if everything goes according to plan. An
  30654. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  30655. ** fails.
  30656. */
  30657. static int openSubJournal(Pager *pPager){
  30658. int rc = SQLITE_OK;
  30659. if( !isOpen(pPager->sjfd) ){
  30660. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  30661. sqlite3MemJournalOpen(pPager->sjfd);
  30662. }else{
  30663. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  30664. }
  30665. }
  30666. return rc;
  30667. }
  30668. /*
  30669. ** Append a record of the current state of page pPg to the sub-journal.
  30670. ** It is the callers responsibility to use subjRequiresPage() to check
  30671. ** that it is really required before calling this function.
  30672. **
  30673. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  30674. ** for all open savepoints before returning.
  30675. **
  30676. ** This function returns SQLITE_OK if everything is successful, an IO
  30677. ** error code if the attempt to write to the sub-journal fails, or
  30678. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  30679. ** bitvec.
  30680. */
  30681. static int subjournalPage(PgHdr *pPg){
  30682. int rc = SQLITE_OK;
  30683. Pager *pPager = pPg->pPager;
  30684. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  30685. /* Open the sub-journal, if it has not already been opened */
  30686. assert( pPager->useJournal );
  30687. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  30688. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  30689. assert( pagerUseWal(pPager)
  30690. || pageInJournal(pPg)
  30691. || pPg->pgno>pPager->dbOrigSize
  30692. );
  30693. rc = openSubJournal(pPager);
  30694. /* If the sub-journal was opened successfully (or was already open),
  30695. ** write the journal record into the file. */
  30696. if( rc==SQLITE_OK ){
  30697. void *pData = pPg->pData;
  30698. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  30699. char *pData2;
  30700. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  30701. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  30702. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  30703. if( rc==SQLITE_OK ){
  30704. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  30705. }
  30706. }
  30707. }
  30708. if( rc==SQLITE_OK ){
  30709. pPager->nSubRec++;
  30710. assert( pPager->nSavepoint>0 );
  30711. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  30712. }
  30713. return rc;
  30714. }
  30715. /*
  30716. ** This function is called by the pcache layer when it has reached some
  30717. ** soft memory limit. The first argument is a pointer to a Pager object
  30718. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  30719. ** database). The second argument is a reference to a page that is
  30720. ** currently dirty but has no outstanding references. The page
  30721. ** is always associated with the Pager object passed as the first
  30722. ** argument.
  30723. **
  30724. ** The job of this function is to make pPg clean by writing its contents
  30725. ** out to the database file, if possible. This may involve syncing the
  30726. ** journal file.
  30727. **
  30728. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  30729. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  30730. ** page clean, the IO error code is returned. If the page cannot be
  30731. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  30732. ** is returned by sqlite3PcacheMakeClean() is not called.
  30733. */
  30734. static int pagerStress(void *p, PgHdr *pPg){
  30735. Pager *pPager = (Pager *)p;
  30736. int rc = SQLITE_OK;
  30737. assert( pPg->pPager==pPager );
  30738. assert( pPg->flags&PGHDR_DIRTY );
  30739. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  30740. ** journal (and adding a new header) is not allowed. This occurs
  30741. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  30742. ** pages belonging to the same sector.
  30743. **
  30744. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  30745. ** regardless of whether or not a sync is required. This is set during
  30746. ** a rollback or by user request, respectively.
  30747. **
  30748. ** Spilling is also prohibited when in an error state since that could
  30749. ** lead to database corruption. In the current implementaton it
  30750. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  30751. ** while in the error state, hence it is impossible for this routine to
  30752. ** be called in the error state. Nevertheless, we include a NEVER()
  30753. ** test for the error state as a safeguard against future changes.
  30754. */
  30755. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  30756. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  30757. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  30758. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  30759. if( pPager->doNotSpill
  30760. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  30761. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  30762. ){
  30763. return SQLITE_OK;
  30764. }
  30765. pPg->pDirty = 0;
  30766. if( pagerUseWal(pPager) ){
  30767. /* Write a single frame for this page to the log. */
  30768. if( subjRequiresPage(pPg) ){
  30769. rc = subjournalPage(pPg);
  30770. }
  30771. if( rc==SQLITE_OK ){
  30772. rc = pagerWalFrames(pPager, pPg, 0, 0);
  30773. }
  30774. }else{
  30775. /* Sync the journal file if required. */
  30776. if( pPg->flags&PGHDR_NEED_SYNC
  30777. || pPager->eState==PAGER_WRITER_CACHEMOD
  30778. ){
  30779. rc = syncJournal(pPager, 1);
  30780. }
  30781. /* If the page number of this page is larger than the current size of
  30782. ** the database image, it may need to be written to the sub-journal.
  30783. ** This is because the call to pager_write_pagelist() below will not
  30784. ** actually write data to the file in this case.
  30785. **
  30786. ** Consider the following sequence of events:
  30787. **
  30788. ** BEGIN;
  30789. ** <journal page X>
  30790. ** <modify page X>
  30791. ** SAVEPOINT sp;
  30792. ** <shrink database file to Y pages>
  30793. ** pagerStress(page X)
  30794. ** ROLLBACK TO sp;
  30795. **
  30796. ** If (X>Y), then when pagerStress is called page X will not be written
  30797. ** out to the database file, but will be dropped from the cache. Then,
  30798. ** following the "ROLLBACK TO sp" statement, reading page X will read
  30799. ** data from the database file. This will be the copy of page X as it
  30800. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  30801. ** was executed.
  30802. **
  30803. ** The solution is to write the current data for page X into the
  30804. ** sub-journal file now (if it is not already there), so that it will
  30805. ** be restored to its current value when the "ROLLBACK TO sp" is
  30806. ** executed.
  30807. */
  30808. if( NEVER(
  30809. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  30810. ) ){
  30811. rc = subjournalPage(pPg);
  30812. }
  30813. /* Write the contents of the page out to the database file. */
  30814. if( rc==SQLITE_OK ){
  30815. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  30816. rc = pager_write_pagelist(pPager, pPg);
  30817. }
  30818. }
  30819. /* Mark the page as clean. */
  30820. if( rc==SQLITE_OK ){
  30821. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  30822. sqlite3PcacheMakeClean(pPg);
  30823. }
  30824. return pager_error(pPager, rc);
  30825. }
  30826. /*
  30827. ** Allocate and initialize a new Pager object and put a pointer to it
  30828. ** in *ppPager. The pager should eventually be freed by passing it
  30829. ** to sqlite3PagerClose().
  30830. **
  30831. ** The zFilename argument is the path to the database file to open.
  30832. ** If zFilename is NULL then a randomly-named temporary file is created
  30833. ** and used as the file to be cached. Temporary files are be deleted
  30834. ** automatically when they are closed. If zFilename is ":memory:" then
  30835. ** all information is held in cache. It is never written to disk.
  30836. ** This can be used to implement an in-memory database.
  30837. **
  30838. ** The nExtra parameter specifies the number of bytes of space allocated
  30839. ** along with each page reference. This space is available to the user
  30840. ** via the sqlite3PagerGetExtra() API.
  30841. **
  30842. ** The flags argument is used to specify properties that affect the
  30843. ** operation of the pager. It should be passed some bitwise combination
  30844. ** of the PAGER_* flags.
  30845. **
  30846. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  30847. ** of the xOpen() method of the supplied VFS when opening files.
  30848. **
  30849. ** If the pager object is allocated and the specified file opened
  30850. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  30851. ** the new pager object. If an error occurs, *ppPager is set to NULL
  30852. ** and error code returned. This function may return SQLITE_NOMEM
  30853. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  30854. ** various SQLITE_IO_XXX errors.
  30855. */
  30856. SQLITE_PRIVATE int sqlite3PagerOpen(
  30857. sqlite3_vfs *pVfs, /* The virtual file system to use */
  30858. Pager **ppPager, /* OUT: Return the Pager structure here */
  30859. const char *zFilename, /* Name of the database file to open */
  30860. int nExtra, /* Extra bytes append to each in-memory page */
  30861. int flags, /* flags controlling this file */
  30862. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  30863. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  30864. ){
  30865. u8 *pPtr;
  30866. Pager *pPager = 0; /* Pager object to allocate and return */
  30867. int rc = SQLITE_OK; /* Return code */
  30868. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  30869. int memDb = 0; /* True if this is an in-memory file */
  30870. int readOnly = 0; /* True if this is a read-only file */
  30871. int journalFileSize; /* Bytes to allocate for each journal fd */
  30872. char *zPathname = 0; /* Full path to database file */
  30873. int nPathname = 0; /* Number of bytes in zPathname */
  30874. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  30875. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  30876. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  30877. const char *zUri = 0; /* URI args to copy */
  30878. int nUri = 0; /* Number of bytes of URI args at *zUri */
  30879. /* Figure out how much space is required for each journal file-handle
  30880. ** (there are two of them, the main journal and the sub-journal). This
  30881. ** is the maximum space required for an in-memory journal file handle
  30882. ** and a regular journal file-handle. Note that a "regular journal-handle"
  30883. ** may be a wrapper capable of caching the first portion of the journal
  30884. ** file in memory to implement the atomic-write optimization (see
  30885. ** source file journal.c).
  30886. */
  30887. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  30888. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  30889. }else{
  30890. journalFileSize = ROUND8(sqlite3MemJournalSize());
  30891. }
  30892. /* Set the output variable to NULL in case an error occurs. */
  30893. *ppPager = 0;
  30894. #ifndef SQLITE_OMIT_MEMORYDB
  30895. if( flags & PAGER_MEMORY ){
  30896. memDb = 1;
  30897. if( zFilename && zFilename[0] ){
  30898. zPathname = sqlite3DbStrDup(0, zFilename);
  30899. if( zPathname==0 ) return SQLITE_NOMEM;
  30900. nPathname = sqlite3Strlen30(zPathname);
  30901. zFilename = 0;
  30902. }
  30903. }
  30904. #endif
  30905. /* Compute and store the full pathname in an allocated buffer pointed
  30906. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  30907. ** leave both nPathname and zPathname set to 0.
  30908. */
  30909. if( zFilename && zFilename[0] ){
  30910. const char *z;
  30911. nPathname = pVfs->mxPathname+1;
  30912. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  30913. if( zPathname==0 ){
  30914. return SQLITE_NOMEM;
  30915. }
  30916. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  30917. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  30918. nPathname = sqlite3Strlen30(zPathname);
  30919. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  30920. while( *z ){
  30921. z += sqlite3Strlen30(z)+1;
  30922. z += sqlite3Strlen30(z)+1;
  30923. }
  30924. nUri = (int)(&z[1] - zUri);
  30925. assert( nUri>=0 );
  30926. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  30927. /* This branch is taken when the journal path required by
  30928. ** the database being opened will be more than pVfs->mxPathname
  30929. ** bytes in length. This means the database cannot be opened,
  30930. ** as it will not be possible to open the journal file or even
  30931. ** check for a hot-journal before reading.
  30932. */
  30933. rc = SQLITE_CANTOPEN_BKPT;
  30934. }
  30935. if( rc!=SQLITE_OK ){
  30936. sqlite3DbFree(0, zPathname);
  30937. return rc;
  30938. }
  30939. }
  30940. /* Allocate memory for the Pager structure, PCache object, the
  30941. ** three file descriptors, the database file name and the journal
  30942. ** file name. The layout in memory is as follows:
  30943. **
  30944. ** Pager object (sizeof(Pager) bytes)
  30945. ** PCache object (sqlite3PcacheSize() bytes)
  30946. ** Database file handle (pVfs->szOsFile bytes)
  30947. ** Sub-journal file handle (journalFileSize bytes)
  30948. ** Main journal file handle (journalFileSize bytes)
  30949. ** Database file name (nPathname+1 bytes)
  30950. ** Journal file name (nPathname+8+1 bytes)
  30951. */
  30952. pPtr = (u8 *)sqlite3MallocZero(
  30953. ROUND8(sizeof(*pPager)) + /* Pager structure */
  30954. ROUND8(pcacheSize) + /* PCache object */
  30955. ROUND8(pVfs->szOsFile) + /* The main db file */
  30956. journalFileSize * 2 + /* The two journal files */
  30957. nPathname + 1 + nUri + /* zFilename */
  30958. nPathname + 8 + 2 /* zJournal */
  30959. #ifndef SQLITE_OMIT_WAL
  30960. + nPathname + 4 + 2 /* zWal */
  30961. #endif
  30962. );
  30963. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  30964. if( !pPtr ){
  30965. sqlite3DbFree(0, zPathname);
  30966. return SQLITE_NOMEM;
  30967. }
  30968. pPager = (Pager*)(pPtr);
  30969. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  30970. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  30971. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  30972. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  30973. pPager->zFilename = (char*)(pPtr += journalFileSize);
  30974. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  30975. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  30976. if( zPathname ){
  30977. assert( nPathname>0 );
  30978. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  30979. memcpy(pPager->zFilename, zPathname, nPathname);
  30980. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  30981. memcpy(pPager->zJournal, zPathname, nPathname);
  30982. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  30983. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  30984. #ifndef SQLITE_OMIT_WAL
  30985. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  30986. memcpy(pPager->zWal, zPathname, nPathname);
  30987. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  30988. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  30989. #endif
  30990. sqlite3DbFree(0, zPathname);
  30991. }
  30992. pPager->pVfs = pVfs;
  30993. pPager->vfsFlags = vfsFlags;
  30994. /* Open the pager file.
  30995. */
  30996. if( zFilename && zFilename[0] ){
  30997. int fout = 0; /* VFS flags returned by xOpen() */
  30998. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  30999. assert( !memDb );
  31000. readOnly = (fout&SQLITE_OPEN_READONLY);
  31001. /* If the file was successfully opened for read/write access,
  31002. ** choose a default page size in case we have to create the
  31003. ** database file. The default page size is the maximum of:
  31004. **
  31005. ** + SQLITE_DEFAULT_PAGE_SIZE,
  31006. ** + The value returned by sqlite3OsSectorSize()
  31007. ** + The largest page size that can be written atomically.
  31008. */
  31009. if( rc==SQLITE_OK && !readOnly ){
  31010. setSectorSize(pPager);
  31011. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  31012. if( szPageDflt<pPager->sectorSize ){
  31013. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  31014. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  31015. }else{
  31016. szPageDflt = (u32)pPager->sectorSize;
  31017. }
  31018. }
  31019. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31020. {
  31021. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  31022. int ii;
  31023. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  31024. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  31025. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  31026. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  31027. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  31028. szPageDflt = ii;
  31029. }
  31030. }
  31031. }
  31032. #endif
  31033. }
  31034. }else{
  31035. /* If a temporary file is requested, it is not opened immediately.
  31036. ** In this case we accept the default page size and delay actually
  31037. ** opening the file until the first call to OsWrite().
  31038. **
  31039. ** This branch is also run for an in-memory database. An in-memory
  31040. ** database is the same as a temp-file that is never written out to
  31041. ** disk and uses an in-memory rollback journal.
  31042. */
  31043. tempFile = 1;
  31044. pPager->eState = PAGER_READER;
  31045. pPager->eLock = EXCLUSIVE_LOCK;
  31046. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  31047. }
  31048. /* The following call to PagerSetPagesize() serves to set the value of
  31049. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  31050. */
  31051. if( rc==SQLITE_OK ){
  31052. assert( pPager->memDb==0 );
  31053. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  31054. testcase( rc!=SQLITE_OK );
  31055. }
  31056. /* If an error occurred in either of the blocks above, free the
  31057. ** Pager structure and close the file.
  31058. */
  31059. if( rc!=SQLITE_OK ){
  31060. assert( !pPager->pTmpSpace );
  31061. sqlite3OsClose(pPager->fd);
  31062. sqlite3_free(pPager);
  31063. return rc;
  31064. }
  31065. /* Initialize the PCache object. */
  31066. assert( nExtra<1000 );
  31067. nExtra = ROUND8(nExtra);
  31068. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  31069. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  31070. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  31071. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  31072. pPager->useJournal = (u8)useJournal;
  31073. /* pPager->stmtOpen = 0; */
  31074. /* pPager->stmtInUse = 0; */
  31075. /* pPager->nRef = 0; */
  31076. /* pPager->stmtSize = 0; */
  31077. /* pPager->stmtJSize = 0; */
  31078. /* pPager->nPage = 0; */
  31079. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  31080. /* pPager->state = PAGER_UNLOCK; */
  31081. #if 0
  31082. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  31083. #endif
  31084. /* pPager->errMask = 0; */
  31085. pPager->tempFile = (u8)tempFile;
  31086. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  31087. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  31088. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  31089. pPager->exclusiveMode = (u8)tempFile;
  31090. pPager->changeCountDone = pPager->tempFile;
  31091. pPager->memDb = (u8)memDb;
  31092. pPager->readOnly = (u8)readOnly;
  31093. assert( useJournal || pPager->tempFile );
  31094. pPager->noSync = pPager->tempFile;
  31095. if( pPager->noSync ){
  31096. assert( pPager->fullSync==0 );
  31097. assert( pPager->syncFlags==0 );
  31098. assert( pPager->walSyncFlags==0 );
  31099. assert( pPager->ckptSyncFlags==0 );
  31100. }else{
  31101. pPager->fullSync = 1;
  31102. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  31103. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  31104. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  31105. }
  31106. /* pPager->pFirst = 0; */
  31107. /* pPager->pFirstSynced = 0; */
  31108. /* pPager->pLast = 0; */
  31109. pPager->nExtra = (u16)nExtra;
  31110. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  31111. assert( isOpen(pPager->fd) || tempFile );
  31112. setSectorSize(pPager);
  31113. if( !useJournal ){
  31114. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  31115. }else if( memDb ){
  31116. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  31117. }
  31118. /* pPager->xBusyHandler = 0; */
  31119. /* pPager->pBusyHandlerArg = 0; */
  31120. pPager->xReiniter = xReinit;
  31121. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  31122. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  31123. *ppPager = pPager;
  31124. return SQLITE_OK;
  31125. }
  31126. /*
  31127. ** This function is called after transitioning from PAGER_UNLOCK to
  31128. ** PAGER_SHARED state. It tests if there is a hot journal present in
  31129. ** the file-system for the given pager. A hot journal is one that
  31130. ** needs to be played back. According to this function, a hot-journal
  31131. ** file exists if the following criteria are met:
  31132. **
  31133. ** * The journal file exists in the file system, and
  31134. ** * No process holds a RESERVED or greater lock on the database file, and
  31135. ** * The database file itself is greater than 0 bytes in size, and
  31136. ** * The first byte of the journal file exists and is not 0x00.
  31137. **
  31138. ** If the current size of the database file is 0 but a journal file
  31139. ** exists, that is probably an old journal left over from a prior
  31140. ** database with the same name. In this case the journal file is
  31141. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  31142. ** is returned.
  31143. **
  31144. ** This routine does not check if there is a master journal filename
  31145. ** at the end of the file. If there is, and that master journal file
  31146. ** does not exist, then the journal file is not really hot. In this
  31147. ** case this routine will return a false-positive. The pager_playback()
  31148. ** routine will discover that the journal file is not really hot and
  31149. ** will not roll it back.
  31150. **
  31151. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  31152. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  31153. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  31154. ** to determine whether or not a hot-journal file exists, the IO error
  31155. ** code is returned and the value of *pExists is undefined.
  31156. */
  31157. static int hasHotJournal(Pager *pPager, int *pExists){
  31158. sqlite3_vfs * const pVfs = pPager->pVfs;
  31159. int rc = SQLITE_OK; /* Return code */
  31160. int exists = 1; /* True if a journal file is present */
  31161. int jrnlOpen = !!isOpen(pPager->jfd);
  31162. assert( pPager->useJournal );
  31163. assert( isOpen(pPager->fd) );
  31164. assert( pPager->eState==PAGER_OPEN );
  31165. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  31166. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  31167. ));
  31168. *pExists = 0;
  31169. if( !jrnlOpen ){
  31170. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  31171. }
  31172. if( rc==SQLITE_OK && exists ){
  31173. int locked = 0; /* True if some process holds a RESERVED lock */
  31174. /* Race condition here: Another process might have been holding the
  31175. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  31176. ** call above, but then delete the journal and drop the lock before
  31177. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  31178. ** is the case, this routine might think there is a hot journal when
  31179. ** in fact there is none. This results in a false-positive which will
  31180. ** be dealt with by the playback routine. Ticket #3883.
  31181. */
  31182. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  31183. if( rc==SQLITE_OK && !locked ){
  31184. Pgno nPage; /* Number of pages in database file */
  31185. /* Check the size of the database file. If it consists of 0 pages,
  31186. ** then delete the journal file. See the header comment above for
  31187. ** the reasoning here. Delete the obsolete journal file under
  31188. ** a RESERVED lock to avoid race conditions and to avoid violating
  31189. ** [H33020].
  31190. */
  31191. rc = pagerPagecount(pPager, &nPage);
  31192. if( rc==SQLITE_OK ){
  31193. if( nPage==0 ){
  31194. sqlite3BeginBenignMalloc();
  31195. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  31196. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  31197. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  31198. }
  31199. sqlite3EndBenignMalloc();
  31200. }else{
  31201. /* The journal file exists and no other connection has a reserved
  31202. ** or greater lock on the database file. Now check that there is
  31203. ** at least one non-zero bytes at the start of the journal file.
  31204. ** If there is, then we consider this journal to be hot. If not,
  31205. ** it can be ignored.
  31206. */
  31207. if( !jrnlOpen ){
  31208. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  31209. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  31210. }
  31211. if( rc==SQLITE_OK ){
  31212. u8 first = 0;
  31213. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  31214. if( rc==SQLITE_IOERR_SHORT_READ ){
  31215. rc = SQLITE_OK;
  31216. }
  31217. if( !jrnlOpen ){
  31218. sqlite3OsClose(pPager->jfd);
  31219. }
  31220. *pExists = (first!=0);
  31221. }else if( rc==SQLITE_CANTOPEN ){
  31222. /* If we cannot open the rollback journal file in order to see if
  31223. ** its has a zero header, that might be due to an I/O error, or
  31224. ** it might be due to the race condition described above and in
  31225. ** ticket #3883. Either way, assume that the journal is hot.
  31226. ** This might be a false positive. But if it is, then the
  31227. ** automatic journal playback and recovery mechanism will deal
  31228. ** with it under an EXCLUSIVE lock where we do not need to
  31229. ** worry so much with race conditions.
  31230. */
  31231. *pExists = 1;
  31232. rc = SQLITE_OK;
  31233. }
  31234. }
  31235. }
  31236. }
  31237. }
  31238. return rc;
  31239. }
  31240. /*
  31241. ** This function is called to obtain a shared lock on the database file.
  31242. ** It is illegal to call sqlite3PagerAcquire() until after this function
  31243. ** has been successfully called. If a shared-lock is already held when
  31244. ** this function is called, it is a no-op.
  31245. **
  31246. ** The following operations are also performed by this function.
  31247. **
  31248. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  31249. ** on the database file), then an attempt is made to obtain a
  31250. ** SHARED lock on the database file. Immediately after obtaining
  31251. ** the SHARED lock, the file-system is checked for a hot-journal,
  31252. ** which is played back if present. Following any hot-journal
  31253. ** rollback, the contents of the cache are validated by checking
  31254. ** the 'change-counter' field of the database file header and
  31255. ** discarded if they are found to be invalid.
  31256. **
  31257. ** 2) If the pager is running in exclusive-mode, and there are currently
  31258. ** no outstanding references to any pages, and is in the error state,
  31259. ** then an attempt is made to clear the error state by discarding
  31260. ** the contents of the page cache and rolling back any open journal
  31261. ** file.
  31262. **
  31263. ** If everything is successful, SQLITE_OK is returned. If an IO error
  31264. ** occurs while locking the database, checking for a hot-journal file or
  31265. ** rolling back a journal file, the IO error code is returned.
  31266. */
  31267. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  31268. int rc = SQLITE_OK; /* Return code */
  31269. /* This routine is only called from b-tree and only when there are no
  31270. ** outstanding pages. This implies that the pager state should either
  31271. ** be OPEN or READER. READER is only possible if the pager is or was in
  31272. ** exclusive access mode.
  31273. */
  31274. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  31275. assert( assert_pager_state(pPager) );
  31276. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  31277. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  31278. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  31279. int bHotJournal = 1; /* True if there exists a hot journal-file */
  31280. assert( !MEMDB );
  31281. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  31282. if( rc!=SQLITE_OK ){
  31283. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  31284. goto failed;
  31285. }
  31286. /* If a journal file exists, and there is no RESERVED lock on the
  31287. ** database file, then it either needs to be played back or deleted.
  31288. */
  31289. if( pPager->eLock<=SHARED_LOCK ){
  31290. rc = hasHotJournal(pPager, &bHotJournal);
  31291. }
  31292. if( rc!=SQLITE_OK ){
  31293. goto failed;
  31294. }
  31295. if( bHotJournal ){
  31296. if( pPager->readOnly ){
  31297. rc = SQLITE_READONLY_ROLLBACK;
  31298. goto failed;
  31299. }
  31300. /* Get an EXCLUSIVE lock on the database file. At this point it is
  31301. ** important that a RESERVED lock is not obtained on the way to the
  31302. ** EXCLUSIVE lock. If it were, another process might open the
  31303. ** database file, detect the RESERVED lock, and conclude that the
  31304. ** database is safe to read while this process is still rolling the
  31305. ** hot-journal back.
  31306. **
  31307. ** Because the intermediate RESERVED lock is not requested, any
  31308. ** other process attempting to access the database file will get to
  31309. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  31310. ** on the database file.
  31311. **
  31312. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  31313. ** downgraded to SHARED_LOCK before this function returns.
  31314. */
  31315. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  31316. if( rc!=SQLITE_OK ){
  31317. goto failed;
  31318. }
  31319. /* If it is not already open and the file exists on disk, open the
  31320. ** journal for read/write access. Write access is required because
  31321. ** in exclusive-access mode the file descriptor will be kept open
  31322. ** and possibly used for a transaction later on. Also, write-access
  31323. ** is usually required to finalize the journal in journal_mode=persist
  31324. ** mode (and also for journal_mode=truncate on some systems).
  31325. **
  31326. ** If the journal does not exist, it usually means that some
  31327. ** other connection managed to get in and roll it back before
  31328. ** this connection obtained the exclusive lock above. Or, it
  31329. ** may mean that the pager was in the error-state when this
  31330. ** function was called and the journal file does not exist.
  31331. */
  31332. if( !isOpen(pPager->jfd) ){
  31333. sqlite3_vfs * const pVfs = pPager->pVfs;
  31334. int bExists; /* True if journal file exists */
  31335. rc = sqlite3OsAccess(
  31336. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  31337. if( rc==SQLITE_OK && bExists ){
  31338. int fout = 0;
  31339. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  31340. assert( !pPager->tempFile );
  31341. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  31342. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31343. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  31344. rc = SQLITE_CANTOPEN_BKPT;
  31345. sqlite3OsClose(pPager->jfd);
  31346. }
  31347. }
  31348. }
  31349. /* Playback and delete the journal. Drop the database write
  31350. ** lock and reacquire the read lock. Purge the cache before
  31351. ** playing back the hot-journal so that we don't end up with
  31352. ** an inconsistent cache. Sync the hot journal before playing
  31353. ** it back since the process that crashed and left the hot journal
  31354. ** probably did not sync it and we are required to always sync
  31355. ** the journal before playing it back.
  31356. */
  31357. if( isOpen(pPager->jfd) ){
  31358. assert( rc==SQLITE_OK );
  31359. rc = pagerSyncHotJournal(pPager);
  31360. if( rc==SQLITE_OK ){
  31361. rc = pager_playback(pPager, 1);
  31362. pPager->eState = PAGER_OPEN;
  31363. }
  31364. }else if( !pPager->exclusiveMode ){
  31365. pagerUnlockDb(pPager, SHARED_LOCK);
  31366. }
  31367. if( rc!=SQLITE_OK ){
  31368. /* This branch is taken if an error occurs while trying to open
  31369. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  31370. ** pager_unlock() routine will be called before returning to unlock
  31371. ** the file. If the unlock attempt fails, then Pager.eLock must be
  31372. ** set to UNKNOWN_LOCK (see the comment above the #define for
  31373. ** UNKNOWN_LOCK above for an explanation).
  31374. **
  31375. ** In order to get pager_unlock() to do this, set Pager.eState to
  31376. ** PAGER_ERROR now. This is not actually counted as a transition
  31377. ** to ERROR state in the state diagram at the top of this file,
  31378. ** since we know that the same call to pager_unlock() will very
  31379. ** shortly transition the pager object to the OPEN state. Calling
  31380. ** assert_pager_state() would fail now, as it should not be possible
  31381. ** to be in ERROR state when there are zero outstanding page
  31382. ** references.
  31383. */
  31384. pager_error(pPager, rc);
  31385. goto failed;
  31386. }
  31387. assert( pPager->eState==PAGER_OPEN );
  31388. assert( (pPager->eLock==SHARED_LOCK)
  31389. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  31390. );
  31391. }
  31392. if( !pPager->tempFile && (
  31393. pPager->pBackup
  31394. || sqlite3PcachePagecount(pPager->pPCache)>0
  31395. || USEFETCH(pPager)
  31396. )){
  31397. /* The shared-lock has just been acquired on the database file
  31398. ** and there are already pages in the cache (from a previous
  31399. ** read or write transaction). Check to see if the database
  31400. ** has been modified. If the database has changed, flush the
  31401. ** cache.
  31402. **
  31403. ** Database changes is detected by looking at 15 bytes beginning
  31404. ** at offset 24 into the file. The first 4 of these 16 bytes are
  31405. ** a 32-bit counter that is incremented with each change. The
  31406. ** other bytes change randomly with each file change when
  31407. ** a codec is in use.
  31408. **
  31409. ** There is a vanishingly small chance that a change will not be
  31410. ** detected. The chance of an undetected change is so small that
  31411. ** it can be neglected.
  31412. */
  31413. Pgno nPage = 0;
  31414. char dbFileVers[sizeof(pPager->dbFileVers)];
  31415. rc = pagerPagecount(pPager, &nPage);
  31416. if( rc ) goto failed;
  31417. if( nPage>0 ){
  31418. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  31419. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  31420. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  31421. goto failed;
  31422. }
  31423. }else{
  31424. memset(dbFileVers, 0, sizeof(dbFileVers));
  31425. }
  31426. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  31427. pager_reset(pPager);
  31428. /* Unmap the database file. It is possible that external processes
  31429. ** may have truncated the database file and then extended it back
  31430. ** to its original size while this process was not holding a lock.
  31431. ** In this case there may exist a Pager.pMap mapping that appears
  31432. ** to be the right size but is not actually valid. Avoid this
  31433. ** possibility by unmapping the db here. */
  31434. if( USEFETCH(pPager) ){
  31435. sqlite3OsUnfetch(pPager->fd, 0, 0);
  31436. }
  31437. }
  31438. }
  31439. /* If there is a WAL file in the file-system, open this database in WAL
  31440. ** mode. Otherwise, the following function call is a no-op.
  31441. */
  31442. rc = pagerOpenWalIfPresent(pPager);
  31443. #ifndef SQLITE_OMIT_WAL
  31444. assert( pPager->pWal==0 || rc==SQLITE_OK );
  31445. #endif
  31446. }
  31447. if( pagerUseWal(pPager) ){
  31448. assert( rc==SQLITE_OK );
  31449. rc = pagerBeginReadTransaction(pPager);
  31450. }
  31451. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  31452. rc = pagerPagecount(pPager, &pPager->dbSize);
  31453. }
  31454. failed:
  31455. if( rc!=SQLITE_OK ){
  31456. assert( !MEMDB );
  31457. pager_unlock(pPager);
  31458. assert( pPager->eState==PAGER_OPEN );
  31459. }else{
  31460. pPager->eState = PAGER_READER;
  31461. }
  31462. return rc;
  31463. }
  31464. /*
  31465. ** If the reference count has reached zero, rollback any active
  31466. ** transaction and unlock the pager.
  31467. **
  31468. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  31469. ** the rollback journal, the unlock is not performed and there is
  31470. ** nothing to rollback, so this routine is a no-op.
  31471. */
  31472. static void pagerUnlockIfUnused(Pager *pPager){
  31473. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  31474. pagerUnlockAndRollback(pPager);
  31475. }
  31476. }
  31477. /*
  31478. ** Acquire a reference to page number pgno in pager pPager (a page
  31479. ** reference has type DbPage*). If the requested reference is
  31480. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  31481. **
  31482. ** If the requested page is already in the cache, it is returned.
  31483. ** Otherwise, a new page object is allocated and populated with data
  31484. ** read from the database file. In some cases, the pcache module may
  31485. ** choose not to allocate a new page object and may reuse an existing
  31486. ** object with no outstanding references.
  31487. **
  31488. ** The extra data appended to a page is always initialized to zeros the
  31489. ** first time a page is loaded into memory. If the page requested is
  31490. ** already in the cache when this function is called, then the extra
  31491. ** data is left as it was when the page object was last used.
  31492. **
  31493. ** If the database image is smaller than the requested page or if a
  31494. ** non-zero value is passed as the noContent parameter and the
  31495. ** requested page is not already stored in the cache, then no
  31496. ** actual disk read occurs. In this case the memory image of the
  31497. ** page is initialized to all zeros.
  31498. **
  31499. ** If noContent is true, it means that we do not care about the contents
  31500. ** of the page. This occurs in two scenarios:
  31501. **
  31502. ** a) When reading a free-list leaf page from the database, and
  31503. **
  31504. ** b) When a savepoint is being rolled back and we need to load
  31505. ** a new page into the cache to be filled with the data read
  31506. ** from the savepoint journal.
  31507. **
  31508. ** If noContent is true, then the data returned is zeroed instead of
  31509. ** being read from the database. Additionally, the bits corresponding
  31510. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  31511. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  31512. ** savepoints are set. This means if the page is made writable at any
  31513. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  31514. ** will not be journaled. This saves IO.
  31515. **
  31516. ** The acquisition might fail for several reasons. In all cases,
  31517. ** an appropriate error code is returned and *ppPage is set to NULL.
  31518. **
  31519. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  31520. ** to find a page in the in-memory cache first. If the page is not already
  31521. ** in memory, this routine goes to disk to read it in whereas Lookup()
  31522. ** just returns 0. This routine acquires a read-lock the first time it
  31523. ** has to go to disk, and could also playback an old journal if necessary.
  31524. ** Since Lookup() never goes to disk, it never has to deal with locks
  31525. ** or journal files.
  31526. */
  31527. SQLITE_PRIVATE int sqlite3PagerAcquire(
  31528. Pager *pPager, /* The pager open on the database file */
  31529. Pgno pgno, /* Page number to fetch */
  31530. DbPage **ppPage, /* Write a pointer to the page here */
  31531. int flags /* PAGER_GET_XXX flags */
  31532. ){
  31533. int rc = SQLITE_OK;
  31534. PgHdr *pPg = 0;
  31535. u32 iFrame = 0; /* Frame to read from WAL file */
  31536. const int noContent = (flags & PAGER_GET_NOCONTENT);
  31537. /* It is acceptable to use a read-only (mmap) page for any page except
  31538. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  31539. ** flag was specified by the caller. And so long as the db is not a
  31540. ** temporary or in-memory database. */
  31541. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  31542. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  31543. #ifdef SQLITE_HAS_CODEC
  31544. && pPager->xCodec==0
  31545. #endif
  31546. );
  31547. assert( pPager->eState>=PAGER_READER );
  31548. assert( assert_pager_state(pPager) );
  31549. assert( noContent==0 || bMmapOk==0 );
  31550. if( pgno==0 ){
  31551. return SQLITE_CORRUPT_BKPT;
  31552. }
  31553. /* If the pager is in the error state, return an error immediately.
  31554. ** Otherwise, request the page from the PCache layer. */
  31555. if( pPager->errCode!=SQLITE_OK ){
  31556. rc = pPager->errCode;
  31557. }else{
  31558. if( bMmapOk && pagerUseWal(pPager) ){
  31559. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  31560. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  31561. }
  31562. if( iFrame==0 && bMmapOk ){
  31563. void *pData = 0;
  31564. rc = sqlite3OsFetch(pPager->fd,
  31565. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  31566. );
  31567. if( rc==SQLITE_OK && pData ){
  31568. if( pPager->eState>PAGER_READER ){
  31569. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31570. }
  31571. if( pPg==0 ){
  31572. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  31573. }else{
  31574. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  31575. }
  31576. if( pPg ){
  31577. assert( rc==SQLITE_OK );
  31578. *ppPage = pPg;
  31579. return SQLITE_OK;
  31580. }
  31581. }
  31582. if( rc!=SQLITE_OK ){
  31583. goto pager_acquire_err;
  31584. }
  31585. }
  31586. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  31587. }
  31588. if( rc!=SQLITE_OK ){
  31589. /* Either the call to sqlite3PcacheFetch() returned an error or the
  31590. ** pager was already in the error-state when this function was called.
  31591. ** Set pPg to 0 and jump to the exception handler. */
  31592. pPg = 0;
  31593. goto pager_acquire_err;
  31594. }
  31595. assert( (*ppPage)->pgno==pgno );
  31596. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  31597. if( (*ppPage)->pPager && !noContent ){
  31598. /* In this case the pcache already contains an initialized copy of
  31599. ** the page. Return without further ado. */
  31600. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  31601. pPager->aStat[PAGER_STAT_HIT]++;
  31602. return SQLITE_OK;
  31603. }else{
  31604. /* The pager cache has created a new page. Its content needs to
  31605. ** be initialized. */
  31606. pPg = *ppPage;
  31607. pPg->pPager = pPager;
  31608. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  31609. ** number greater than this, or the unused locking-page, is requested. */
  31610. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  31611. rc = SQLITE_CORRUPT_BKPT;
  31612. goto pager_acquire_err;
  31613. }
  31614. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  31615. if( pgno>pPager->mxPgno ){
  31616. rc = SQLITE_FULL;
  31617. goto pager_acquire_err;
  31618. }
  31619. if( noContent ){
  31620. /* Failure to set the bits in the InJournal bit-vectors is benign.
  31621. ** It merely means that we might do some extra work to journal a
  31622. ** page that does not need to be journaled. Nevertheless, be sure
  31623. ** to test the case where a malloc error occurs while trying to set
  31624. ** a bit in a bit vector.
  31625. */
  31626. sqlite3BeginBenignMalloc();
  31627. if( pgno<=pPager->dbOrigSize ){
  31628. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  31629. testcase( rc==SQLITE_NOMEM );
  31630. }
  31631. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  31632. testcase( rc==SQLITE_NOMEM );
  31633. sqlite3EndBenignMalloc();
  31634. }
  31635. memset(pPg->pData, 0, pPager->pageSize);
  31636. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  31637. }else{
  31638. if( pagerUseWal(pPager) && bMmapOk==0 ){
  31639. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  31640. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  31641. }
  31642. assert( pPg->pPager==pPager );
  31643. pPager->aStat[PAGER_STAT_MISS]++;
  31644. rc = readDbPage(pPg, iFrame);
  31645. if( rc!=SQLITE_OK ){
  31646. goto pager_acquire_err;
  31647. }
  31648. }
  31649. pager_set_pagehash(pPg);
  31650. }
  31651. return SQLITE_OK;
  31652. pager_acquire_err:
  31653. assert( rc!=SQLITE_OK );
  31654. if( pPg ){
  31655. sqlite3PcacheDrop(pPg);
  31656. }
  31657. pagerUnlockIfUnused(pPager);
  31658. *ppPage = 0;
  31659. return rc;
  31660. }
  31661. /*
  31662. ** Acquire a page if it is already in the in-memory cache. Do
  31663. ** not read the page from disk. Return a pointer to the page,
  31664. ** or 0 if the page is not in cache.
  31665. **
  31666. ** See also sqlite3PagerGet(). The difference between this routine
  31667. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  31668. ** in the page if the page is not already in cache. This routine
  31669. ** returns NULL if the page is not in cache or if a disk I/O error
  31670. ** has ever happened.
  31671. */
  31672. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  31673. PgHdr *pPg = 0;
  31674. assert( pPager!=0 );
  31675. assert( pgno!=0 );
  31676. assert( pPager->pPCache!=0 );
  31677. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  31678. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31679. return pPg;
  31680. }
  31681. /*
  31682. ** Release a page reference.
  31683. **
  31684. ** If the number of references to the page drop to zero, then the
  31685. ** page is added to the LRU list. When all references to all pages
  31686. ** are released, a rollback occurs and the lock on the database is
  31687. ** removed.
  31688. */
  31689. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  31690. if( pPg ){
  31691. Pager *pPager = pPg->pPager;
  31692. if( pPg->flags & PGHDR_MMAP ){
  31693. pagerReleaseMapPage(pPg);
  31694. }else{
  31695. sqlite3PcacheRelease(pPg);
  31696. }
  31697. pagerUnlockIfUnused(pPager);
  31698. }
  31699. }
  31700. /*
  31701. ** This function is called at the start of every write transaction.
  31702. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  31703. ** file when this routine is called.
  31704. **
  31705. ** Open the journal file for pager pPager and write a journal header
  31706. ** to the start of it. If there are active savepoints, open the sub-journal
  31707. ** as well. This function is only used when the journal file is being
  31708. ** opened to write a rollback log for a transaction. It is not used
  31709. ** when opening a hot journal file to roll it back.
  31710. **
  31711. ** If the journal file is already open (as it may be in exclusive mode),
  31712. ** then this function just writes a journal header to the start of the
  31713. ** already open file.
  31714. **
  31715. ** Whether or not the journal file is opened by this function, the
  31716. ** Pager.pInJournal bitvec structure is allocated.
  31717. **
  31718. ** Return SQLITE_OK if everything is successful. Otherwise, return
  31719. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  31720. ** an IO error code if opening or writing the journal file fails.
  31721. */
  31722. static int pager_open_journal(Pager *pPager){
  31723. int rc = SQLITE_OK; /* Return code */
  31724. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  31725. assert( pPager->eState==PAGER_WRITER_LOCKED );
  31726. assert( assert_pager_state(pPager) );
  31727. assert( pPager->pInJournal==0 );
  31728. /* If already in the error state, this function is a no-op. But on
  31729. ** the other hand, this routine is never called if we are already in
  31730. ** an error state. */
  31731. if( NEVER(pPager->errCode) ) return pPager->errCode;
  31732. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  31733. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  31734. if( pPager->pInJournal==0 ){
  31735. return SQLITE_NOMEM;
  31736. }
  31737. /* Open the journal file if it is not already open. */
  31738. if( !isOpen(pPager->jfd) ){
  31739. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31740. sqlite3MemJournalOpen(pPager->jfd);
  31741. }else{
  31742. const int flags = /* VFS flags to open journal file */
  31743. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  31744. (pPager->tempFile ?
  31745. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  31746. (SQLITE_OPEN_MAIN_JOURNAL)
  31747. );
  31748. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31749. rc = sqlite3JournalOpen(
  31750. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  31751. );
  31752. #else
  31753. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  31754. #endif
  31755. }
  31756. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31757. }
  31758. /* Write the first journal header to the journal file and open
  31759. ** the sub-journal if necessary.
  31760. */
  31761. if( rc==SQLITE_OK ){
  31762. /* TODO: Check if all of these are really required. */
  31763. pPager->nRec = 0;
  31764. pPager->journalOff = 0;
  31765. pPager->setMaster = 0;
  31766. pPager->journalHdr = 0;
  31767. rc = writeJournalHdr(pPager);
  31768. }
  31769. }
  31770. if( rc!=SQLITE_OK ){
  31771. sqlite3BitvecDestroy(pPager->pInJournal);
  31772. pPager->pInJournal = 0;
  31773. }else{
  31774. assert( pPager->eState==PAGER_WRITER_LOCKED );
  31775. pPager->eState = PAGER_WRITER_CACHEMOD;
  31776. }
  31777. return rc;
  31778. }
  31779. /*
  31780. ** Begin a write-transaction on the specified pager object. If a
  31781. ** write-transaction has already been opened, this function is a no-op.
  31782. **
  31783. ** If the exFlag argument is false, then acquire at least a RESERVED
  31784. ** lock on the database file. If exFlag is true, then acquire at least
  31785. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  31786. ** functions need be called.
  31787. **
  31788. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  31789. ** within this transaction will be opened as an in-memory file. This
  31790. ** has no effect if the sub-journal is already opened (as it may be when
  31791. ** running in exclusive mode) or if the transaction does not require a
  31792. ** sub-journal. If the subjInMemory argument is zero, then any required
  31793. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  31794. ** or using a temporary file otherwise.
  31795. */
  31796. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  31797. int rc = SQLITE_OK;
  31798. if( pPager->errCode ) return pPager->errCode;
  31799. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  31800. pPager->subjInMemory = (u8)subjInMemory;
  31801. if( ALWAYS(pPager->eState==PAGER_READER) ){
  31802. assert( pPager->pInJournal==0 );
  31803. if( pagerUseWal(pPager) ){
  31804. /* If the pager is configured to use locking_mode=exclusive, and an
  31805. ** exclusive lock on the database is not already held, obtain it now.
  31806. */
  31807. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  31808. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  31809. if( rc!=SQLITE_OK ){
  31810. return rc;
  31811. }
  31812. sqlite3WalExclusiveMode(pPager->pWal, 1);
  31813. }
  31814. /* Grab the write lock on the log file. If successful, upgrade to
  31815. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  31816. ** The busy-handler is not invoked if another connection already
  31817. ** holds the write-lock. If possible, the upper layer will call it.
  31818. */
  31819. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  31820. }else{
  31821. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  31822. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  31823. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  31824. ** lock, but not when obtaining the RESERVED lock.
  31825. */
  31826. rc = pagerLockDb(pPager, RESERVED_LOCK);
  31827. if( rc==SQLITE_OK && exFlag ){
  31828. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  31829. }
  31830. }
  31831. if( rc==SQLITE_OK ){
  31832. /* Change to WRITER_LOCKED state.
  31833. **
  31834. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  31835. ** when it has an open transaction, but never to DBMOD or FINISHED.
  31836. ** This is because in those states the code to roll back savepoint
  31837. ** transactions may copy data from the sub-journal into the database
  31838. ** file as well as into the page cache. Which would be incorrect in
  31839. ** WAL mode.
  31840. */
  31841. pPager->eState = PAGER_WRITER_LOCKED;
  31842. pPager->dbHintSize = pPager->dbSize;
  31843. pPager->dbFileSize = pPager->dbSize;
  31844. pPager->dbOrigSize = pPager->dbSize;
  31845. pPager->journalOff = 0;
  31846. }
  31847. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  31848. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  31849. assert( assert_pager_state(pPager) );
  31850. }
  31851. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  31852. return rc;
  31853. }
  31854. /*
  31855. ** Mark a single data page as writeable. The page is written into the
  31856. ** main journal or sub-journal as required. If the page is written into
  31857. ** one of the journals, the corresponding bit is set in the
  31858. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  31859. ** of any open savepoints as appropriate.
  31860. */
  31861. static int pager_write(PgHdr *pPg){
  31862. void *pData = pPg->pData;
  31863. Pager *pPager = pPg->pPager;
  31864. int rc = SQLITE_OK;
  31865. /* This routine is not called unless a write-transaction has already
  31866. ** been started. The journal file may or may not be open at this point.
  31867. ** It is never called in the ERROR state.
  31868. */
  31869. assert( pPager->eState==PAGER_WRITER_LOCKED
  31870. || pPager->eState==PAGER_WRITER_CACHEMOD
  31871. || pPager->eState==PAGER_WRITER_DBMOD
  31872. );
  31873. assert( assert_pager_state(pPager) );
  31874. /* If an error has been previously detected, report the same error
  31875. ** again. This should not happen, but the check provides robustness. */
  31876. if( NEVER(pPager->errCode) ) return pPager->errCode;
  31877. /* Higher-level routines never call this function if database is not
  31878. ** writable. But check anyway, just for robustness. */
  31879. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  31880. CHECK_PAGE(pPg);
  31881. /* The journal file needs to be opened. Higher level routines have already
  31882. ** obtained the necessary locks to begin the write-transaction, but the
  31883. ** rollback journal might not yet be open. Open it now if this is the case.
  31884. **
  31885. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  31886. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  31887. ** an error might occur and the pager would end up in WRITER_LOCKED state
  31888. ** with pages marked as dirty in the cache.
  31889. */
  31890. if( pPager->eState==PAGER_WRITER_LOCKED ){
  31891. rc = pager_open_journal(pPager);
  31892. if( rc!=SQLITE_OK ) return rc;
  31893. }
  31894. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  31895. assert( assert_pager_state(pPager) );
  31896. /* Mark the page as dirty. If the page has already been written
  31897. ** to the journal then we can return right away.
  31898. */
  31899. sqlite3PcacheMakeDirty(pPg);
  31900. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  31901. assert( !pagerUseWal(pPager) );
  31902. }else{
  31903. /* The transaction journal now exists and we have a RESERVED or an
  31904. ** EXCLUSIVE lock on the main database file. Write the current page to
  31905. ** the transaction journal if it is not there already.
  31906. */
  31907. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  31908. assert( pagerUseWal(pPager)==0 );
  31909. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  31910. u32 cksum;
  31911. char *pData2;
  31912. i64 iOff = pPager->journalOff;
  31913. /* We should never write to the journal file the page that
  31914. ** contains the database locks. The following assert verifies
  31915. ** that we do not. */
  31916. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  31917. assert( pPager->journalHdr<=pPager->journalOff );
  31918. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  31919. cksum = pager_cksum(pPager, (u8*)pData2);
  31920. /* Even if an IO or diskfull error occurs while journalling the
  31921. ** page in the block above, set the need-sync flag for the page.
  31922. ** Otherwise, when the transaction is rolled back, the logic in
  31923. ** playback_one_page() will think that the page needs to be restored
  31924. ** in the database file. And if an IO error occurs while doing so,
  31925. ** then corruption may follow.
  31926. */
  31927. pPg->flags |= PGHDR_NEED_SYNC;
  31928. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  31929. if( rc!=SQLITE_OK ) return rc;
  31930. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  31931. if( rc!=SQLITE_OK ) return rc;
  31932. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  31933. if( rc!=SQLITE_OK ) return rc;
  31934. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  31935. pPager->journalOff, pPager->pageSize));
  31936. PAGER_INCR(sqlite3_pager_writej_count);
  31937. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  31938. PAGERID(pPager), pPg->pgno,
  31939. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  31940. pPager->journalOff += 8 + pPager->pageSize;
  31941. pPager->nRec++;
  31942. assert( pPager->pInJournal!=0 );
  31943. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  31944. testcase( rc==SQLITE_NOMEM );
  31945. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  31946. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  31947. if( rc!=SQLITE_OK ){
  31948. assert( rc==SQLITE_NOMEM );
  31949. return rc;
  31950. }
  31951. }else{
  31952. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  31953. pPg->flags |= PGHDR_NEED_SYNC;
  31954. }
  31955. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  31956. PAGERID(pPager), pPg->pgno,
  31957. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  31958. }
  31959. }
  31960. /* If the statement journal is open and the page is not in it,
  31961. ** then write the current page to the statement journal. Note that
  31962. ** the statement journal format differs from the standard journal format
  31963. ** in that it omits the checksums and the header.
  31964. */
  31965. if( subjRequiresPage(pPg) ){
  31966. rc = subjournalPage(pPg);
  31967. }
  31968. }
  31969. /* Update the database size and return.
  31970. */
  31971. if( pPager->dbSize<pPg->pgno ){
  31972. pPager->dbSize = pPg->pgno;
  31973. }
  31974. return rc;
  31975. }
  31976. /*
  31977. ** Mark a data page as writeable. This routine must be called before
  31978. ** making changes to a page. The caller must check the return value
  31979. ** of this function and be careful not to change any page data unless
  31980. ** this routine returns SQLITE_OK.
  31981. **
  31982. ** The difference between this function and pager_write() is that this
  31983. ** function also deals with the special case where 2 or more pages
  31984. ** fit on a single disk sector. In this case all co-resident pages
  31985. ** must have been written to the journal file before returning.
  31986. **
  31987. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  31988. ** as appropriate. Otherwise, SQLITE_OK.
  31989. */
  31990. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  31991. int rc = SQLITE_OK;
  31992. PgHdr *pPg = pDbPage;
  31993. Pager *pPager = pPg->pPager;
  31994. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  31995. assert( (pPg->flags & PGHDR_MMAP)==0 );
  31996. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  31997. assert( pPager->eState!=PAGER_ERROR );
  31998. assert( assert_pager_state(pPager) );
  31999. if( nPagePerSector>1 ){
  32000. Pgno nPageCount; /* Total number of pages in database file */
  32001. Pgno pg1; /* First page of the sector pPg is located on. */
  32002. int nPage = 0; /* Number of pages starting at pg1 to journal */
  32003. int ii; /* Loop counter */
  32004. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  32005. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  32006. ** a journal header to be written between the pages journaled by
  32007. ** this function.
  32008. */
  32009. assert( !MEMDB );
  32010. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  32011. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  32012. /* This trick assumes that both the page-size and sector-size are
  32013. ** an integer power of 2. It sets variable pg1 to the identifier
  32014. ** of the first page of the sector pPg is located on.
  32015. */
  32016. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  32017. nPageCount = pPager->dbSize;
  32018. if( pPg->pgno>nPageCount ){
  32019. nPage = (pPg->pgno - pg1)+1;
  32020. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  32021. nPage = nPageCount+1-pg1;
  32022. }else{
  32023. nPage = nPagePerSector;
  32024. }
  32025. assert(nPage>0);
  32026. assert(pg1<=pPg->pgno);
  32027. assert((pg1+nPage)>pPg->pgno);
  32028. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  32029. Pgno pg = pg1+ii;
  32030. PgHdr *pPage;
  32031. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  32032. if( pg!=PAGER_MJ_PGNO(pPager) ){
  32033. rc = sqlite3PagerGet(pPager, pg, &pPage);
  32034. if( rc==SQLITE_OK ){
  32035. rc = pager_write(pPage);
  32036. if( pPage->flags&PGHDR_NEED_SYNC ){
  32037. needSync = 1;
  32038. }
  32039. sqlite3PagerUnref(pPage);
  32040. }
  32041. }
  32042. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  32043. if( pPage->flags&PGHDR_NEED_SYNC ){
  32044. needSync = 1;
  32045. }
  32046. sqlite3PagerUnref(pPage);
  32047. }
  32048. }
  32049. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  32050. ** starting at pg1, then it needs to be set for all of them. Because
  32051. ** writing to any of these nPage pages may damage the others, the
  32052. ** journal file must contain sync()ed copies of all of them
  32053. ** before any of them can be written out to the database file.
  32054. */
  32055. if( rc==SQLITE_OK && needSync ){
  32056. assert( !MEMDB );
  32057. for(ii=0; ii<nPage; ii++){
  32058. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  32059. if( pPage ){
  32060. pPage->flags |= PGHDR_NEED_SYNC;
  32061. sqlite3PagerUnref(pPage);
  32062. }
  32063. }
  32064. }
  32065. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  32066. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  32067. }else{
  32068. rc = pager_write(pDbPage);
  32069. }
  32070. return rc;
  32071. }
  32072. /*
  32073. ** Return TRUE if the page given in the argument was previously passed
  32074. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  32075. ** to change the content of the page.
  32076. */
  32077. #ifndef NDEBUG
  32078. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  32079. return pPg->flags&PGHDR_DIRTY;
  32080. }
  32081. #endif
  32082. /*
  32083. ** A call to this routine tells the pager that it is not necessary to
  32084. ** write the information on page pPg back to the disk, even though
  32085. ** that page might be marked as dirty. This happens, for example, when
  32086. ** the page has been added as a leaf of the freelist and so its
  32087. ** content no longer matters.
  32088. **
  32089. ** The overlying software layer calls this routine when all of the data
  32090. ** on the given page is unused. The pager marks the page as clean so
  32091. ** that it does not get written to disk.
  32092. **
  32093. ** Tests show that this optimization can quadruple the speed of large
  32094. ** DELETE operations.
  32095. */
  32096. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  32097. Pager *pPager = pPg->pPager;
  32098. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  32099. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  32100. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  32101. pPg->flags |= PGHDR_DONT_WRITE;
  32102. pager_set_pagehash(pPg);
  32103. }
  32104. }
  32105. /*
  32106. ** This routine is called to increment the value of the database file
  32107. ** change-counter, stored as a 4-byte big-endian integer starting at
  32108. ** byte offset 24 of the pager file. The secondary change counter at
  32109. ** 92 is also updated, as is the SQLite version number at offset 96.
  32110. **
  32111. ** But this only happens if the pPager->changeCountDone flag is false.
  32112. ** To avoid excess churning of page 1, the update only happens once.
  32113. ** See also the pager_write_changecounter() routine that does an
  32114. ** unconditional update of the change counters.
  32115. **
  32116. ** If the isDirectMode flag is zero, then this is done by calling
  32117. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  32118. ** page data. In this case the file will be updated when the current
  32119. ** transaction is committed.
  32120. **
  32121. ** The isDirectMode flag may only be non-zero if the library was compiled
  32122. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  32123. ** if isDirect is non-zero, then the database file is updated directly
  32124. ** by writing an updated version of page 1 using a call to the
  32125. ** sqlite3OsWrite() function.
  32126. */
  32127. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  32128. int rc = SQLITE_OK;
  32129. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32130. || pPager->eState==PAGER_WRITER_DBMOD
  32131. );
  32132. assert( assert_pager_state(pPager) );
  32133. /* Declare and initialize constant integer 'isDirect'. If the
  32134. ** atomic-write optimization is enabled in this build, then isDirect
  32135. ** is initialized to the value passed as the isDirectMode parameter
  32136. ** to this function. Otherwise, it is always set to zero.
  32137. **
  32138. ** The idea is that if the atomic-write optimization is not
  32139. ** enabled at compile time, the compiler can omit the tests of
  32140. ** 'isDirect' below, as well as the block enclosed in the
  32141. ** "if( isDirect )" condition.
  32142. */
  32143. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  32144. # define DIRECT_MODE 0
  32145. assert( isDirectMode==0 );
  32146. UNUSED_PARAMETER(isDirectMode);
  32147. #else
  32148. # define DIRECT_MODE isDirectMode
  32149. #endif
  32150. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  32151. PgHdr *pPgHdr; /* Reference to page 1 */
  32152. assert( !pPager->tempFile && isOpen(pPager->fd) );
  32153. /* Open page 1 of the file for writing. */
  32154. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  32155. assert( pPgHdr==0 || rc==SQLITE_OK );
  32156. /* If page one was fetched successfully, and this function is not
  32157. ** operating in direct-mode, make page 1 writable. When not in
  32158. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  32159. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  32160. */
  32161. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  32162. rc = sqlite3PagerWrite(pPgHdr);
  32163. }
  32164. if( rc==SQLITE_OK ){
  32165. /* Actually do the update of the change counter */
  32166. pager_write_changecounter(pPgHdr);
  32167. /* If running in direct mode, write the contents of page 1 to the file. */
  32168. if( DIRECT_MODE ){
  32169. const void *zBuf;
  32170. assert( pPager->dbFileSize>0 );
  32171. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  32172. if( rc==SQLITE_OK ){
  32173. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  32174. pPager->aStat[PAGER_STAT_WRITE]++;
  32175. }
  32176. if( rc==SQLITE_OK ){
  32177. /* Update the pager's copy of the change-counter. Otherwise, the
  32178. ** next time a read transaction is opened the cache will be
  32179. ** flushed (as the change-counter values will not match). */
  32180. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  32181. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  32182. pPager->changeCountDone = 1;
  32183. }
  32184. }else{
  32185. pPager->changeCountDone = 1;
  32186. }
  32187. }
  32188. /* Release the page reference. */
  32189. sqlite3PagerUnref(pPgHdr);
  32190. }
  32191. return rc;
  32192. }
  32193. /*
  32194. ** Sync the database file to disk. This is a no-op for in-memory databases
  32195. ** or pages with the Pager.noSync flag set.
  32196. **
  32197. ** If successful, or if called on a pager for which it is a no-op, this
  32198. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  32199. */
  32200. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  32201. int rc = SQLITE_OK;
  32202. if( !pPager->noSync ){
  32203. assert( !MEMDB );
  32204. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  32205. }else if( isOpen(pPager->fd) ){
  32206. assert( !MEMDB );
  32207. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  32208. if( rc==SQLITE_NOTFOUND ){
  32209. rc = SQLITE_OK;
  32210. }
  32211. }
  32212. return rc;
  32213. }
  32214. /*
  32215. ** This function may only be called while a write-transaction is active in
  32216. ** rollback. If the connection is in WAL mode, this call is a no-op.
  32217. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  32218. ** the database file, an attempt is made to obtain one.
  32219. **
  32220. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  32221. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  32222. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  32223. ** returned.
  32224. */
  32225. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  32226. int rc = SQLITE_OK;
  32227. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32228. || pPager->eState==PAGER_WRITER_DBMOD
  32229. || pPager->eState==PAGER_WRITER_LOCKED
  32230. );
  32231. assert( assert_pager_state(pPager) );
  32232. if( 0==pagerUseWal(pPager) ){
  32233. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  32234. }
  32235. return rc;
  32236. }
  32237. /*
  32238. ** Sync the database file for the pager pPager. zMaster points to the name
  32239. ** of a master journal file that should be written into the individual
  32240. ** journal file. zMaster may be NULL, which is interpreted as no master
  32241. ** journal (a single database transaction).
  32242. **
  32243. ** This routine ensures that:
  32244. **
  32245. ** * The database file change-counter is updated,
  32246. ** * the journal is synced (unless the atomic-write optimization is used),
  32247. ** * all dirty pages are written to the database file,
  32248. ** * the database file is truncated (if required), and
  32249. ** * the database file synced.
  32250. **
  32251. ** The only thing that remains to commit the transaction is to finalize
  32252. ** (delete, truncate or zero the first part of) the journal file (or
  32253. ** delete the master journal file if specified).
  32254. **
  32255. ** Note that if zMaster==NULL, this does not overwrite a previous value
  32256. ** passed to an sqlite3PagerCommitPhaseOne() call.
  32257. **
  32258. ** If the final parameter - noSync - is true, then the database file itself
  32259. ** is not synced. The caller must call sqlite3PagerSync() directly to
  32260. ** sync the database file before calling CommitPhaseTwo() to delete the
  32261. ** journal file in this case.
  32262. */
  32263. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  32264. Pager *pPager, /* Pager object */
  32265. const char *zMaster, /* If not NULL, the master journal name */
  32266. int noSync /* True to omit the xSync on the db file */
  32267. ){
  32268. int rc = SQLITE_OK; /* Return code */
  32269. assert( pPager->eState==PAGER_WRITER_LOCKED
  32270. || pPager->eState==PAGER_WRITER_CACHEMOD
  32271. || pPager->eState==PAGER_WRITER_DBMOD
  32272. || pPager->eState==PAGER_ERROR
  32273. );
  32274. assert( assert_pager_state(pPager) );
  32275. /* If a prior error occurred, report that error again. */
  32276. if( NEVER(pPager->errCode) ) return pPager->errCode;
  32277. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  32278. pPager->zFilename, zMaster, pPager->dbSize));
  32279. /* If no database changes have been made, return early. */
  32280. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  32281. if( MEMDB ){
  32282. /* If this is an in-memory db, or no pages have been written to, or this
  32283. ** function has already been called, it is mostly a no-op. However, any
  32284. ** backup in progress needs to be restarted.
  32285. */
  32286. sqlite3BackupRestart(pPager->pBackup);
  32287. }else{
  32288. if( pagerUseWal(pPager) ){
  32289. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  32290. PgHdr *pPageOne = 0;
  32291. if( pList==0 ){
  32292. /* Must have at least one page for the WAL commit flag.
  32293. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  32294. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  32295. pList = pPageOne;
  32296. pList->pDirty = 0;
  32297. }
  32298. assert( rc==SQLITE_OK );
  32299. if( ALWAYS(pList) ){
  32300. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  32301. }
  32302. sqlite3PagerUnref(pPageOne);
  32303. if( rc==SQLITE_OK ){
  32304. sqlite3PcacheCleanAll(pPager->pPCache);
  32305. }
  32306. }else{
  32307. /* The following block updates the change-counter. Exactly how it
  32308. ** does this depends on whether or not the atomic-update optimization
  32309. ** was enabled at compile time, and if this transaction meets the
  32310. ** runtime criteria to use the operation:
  32311. **
  32312. ** * The file-system supports the atomic-write property for
  32313. ** blocks of size page-size, and
  32314. ** * This commit is not part of a multi-file transaction, and
  32315. ** * Exactly one page has been modified and store in the journal file.
  32316. **
  32317. ** If the optimization was not enabled at compile time, then the
  32318. ** pager_incr_changecounter() function is called to update the change
  32319. ** counter in 'indirect-mode'. If the optimization is compiled in but
  32320. ** is not applicable to this transaction, call sqlite3JournalCreate()
  32321. ** to make sure the journal file has actually been created, then call
  32322. ** pager_incr_changecounter() to update the change-counter in indirect
  32323. ** mode.
  32324. **
  32325. ** Otherwise, if the optimization is both enabled and applicable,
  32326. ** then call pager_incr_changecounter() to update the change-counter
  32327. ** in 'direct' mode. In this case the journal file will never be
  32328. ** created for this transaction.
  32329. */
  32330. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  32331. PgHdr *pPg;
  32332. assert( isOpen(pPager->jfd)
  32333. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  32334. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  32335. );
  32336. if( !zMaster && isOpen(pPager->jfd)
  32337. && pPager->journalOff==jrnlBufferSize(pPager)
  32338. && pPager->dbSize>=pPager->dbOrigSize
  32339. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  32340. ){
  32341. /* Update the db file change counter via the direct-write method. The
  32342. ** following call will modify the in-memory representation of page 1
  32343. ** to include the updated change counter and then write page 1
  32344. ** directly to the database file. Because of the atomic-write
  32345. ** property of the host file-system, this is safe.
  32346. */
  32347. rc = pager_incr_changecounter(pPager, 1);
  32348. }else{
  32349. rc = sqlite3JournalCreate(pPager->jfd);
  32350. if( rc==SQLITE_OK ){
  32351. rc = pager_incr_changecounter(pPager, 0);
  32352. }
  32353. }
  32354. #else
  32355. rc = pager_incr_changecounter(pPager, 0);
  32356. #endif
  32357. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32358. /* Write the master journal name into the journal file. If a master
  32359. ** journal file name has already been written to the journal file,
  32360. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  32361. */
  32362. rc = writeMasterJournal(pPager, zMaster);
  32363. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32364. /* Sync the journal file and write all dirty pages to the database.
  32365. ** If the atomic-update optimization is being used, this sync will not
  32366. ** create the journal file or perform any real IO.
  32367. **
  32368. ** Because the change-counter page was just modified, unless the
  32369. ** atomic-update optimization is used it is almost certain that the
  32370. ** journal requires a sync here. However, in locking_mode=exclusive
  32371. ** on a system under memory pressure it is just possible that this is
  32372. ** not the case. In this case it is likely enough that the redundant
  32373. ** xSync() call will be changed to a no-op by the OS anyhow.
  32374. */
  32375. rc = syncJournal(pPager, 0);
  32376. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32377. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  32378. if( rc!=SQLITE_OK ){
  32379. assert( rc!=SQLITE_IOERR_BLOCKED );
  32380. goto commit_phase_one_exit;
  32381. }
  32382. sqlite3PcacheCleanAll(pPager->pPCache);
  32383. /* If the file on disk is smaller than the database image, use
  32384. ** pager_truncate to grow the file here. This can happen if the database
  32385. ** image was extended as part of the current transaction and then the
  32386. ** last page in the db image moved to the free-list. In this case the
  32387. ** last page is never written out to disk, leaving the database file
  32388. ** undersized. Fix this now if it is the case. */
  32389. if( pPager->dbSize>pPager->dbFileSize ){
  32390. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  32391. assert( pPager->eState==PAGER_WRITER_DBMOD );
  32392. rc = pager_truncate(pPager, nNew);
  32393. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32394. }
  32395. /* Finally, sync the database file. */
  32396. if( !noSync ){
  32397. rc = sqlite3PagerSync(pPager);
  32398. }
  32399. IOTRACE(("DBSYNC %p\n", pPager))
  32400. }
  32401. }
  32402. commit_phase_one_exit:
  32403. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  32404. pPager->eState = PAGER_WRITER_FINISHED;
  32405. }
  32406. return rc;
  32407. }
  32408. /*
  32409. ** When this function is called, the database file has been completely
  32410. ** updated to reflect the changes made by the current transaction and
  32411. ** synced to disk. The journal file still exists in the file-system
  32412. ** though, and if a failure occurs at this point it will eventually
  32413. ** be used as a hot-journal and the current transaction rolled back.
  32414. **
  32415. ** This function finalizes the journal file, either by deleting,
  32416. ** truncating or partially zeroing it, so that it cannot be used
  32417. ** for hot-journal rollback. Once this is done the transaction is
  32418. ** irrevocably committed.
  32419. **
  32420. ** If an error occurs, an IO error code is returned and the pager
  32421. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  32422. */
  32423. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  32424. int rc = SQLITE_OK; /* Return code */
  32425. /* This routine should not be called if a prior error has occurred.
  32426. ** But if (due to a coding error elsewhere in the system) it does get
  32427. ** called, just return the same error code without doing anything. */
  32428. if( NEVER(pPager->errCode) ) return pPager->errCode;
  32429. assert( pPager->eState==PAGER_WRITER_LOCKED
  32430. || pPager->eState==PAGER_WRITER_FINISHED
  32431. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  32432. );
  32433. assert( assert_pager_state(pPager) );
  32434. /* An optimization. If the database was not actually modified during
  32435. ** this transaction, the pager is running in exclusive-mode and is
  32436. ** using persistent journals, then this function is a no-op.
  32437. **
  32438. ** The start of the journal file currently contains a single journal
  32439. ** header with the nRec field set to 0. If such a journal is used as
  32440. ** a hot-journal during hot-journal rollback, 0 changes will be made
  32441. ** to the database file. So there is no need to zero the journal
  32442. ** header. Since the pager is in exclusive mode, there is no need
  32443. ** to drop any locks either.
  32444. */
  32445. if( pPager->eState==PAGER_WRITER_LOCKED
  32446. && pPager->exclusiveMode
  32447. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  32448. ){
  32449. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  32450. pPager->eState = PAGER_READER;
  32451. return SQLITE_OK;
  32452. }
  32453. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  32454. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  32455. return pager_error(pPager, rc);
  32456. }
  32457. /*
  32458. ** If a write transaction is open, then all changes made within the
  32459. ** transaction are reverted and the current write-transaction is closed.
  32460. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  32461. ** state if an error occurs.
  32462. **
  32463. ** If the pager is already in PAGER_ERROR state when this function is called,
  32464. ** it returns Pager.errCode immediately. No work is performed in this case.
  32465. **
  32466. ** Otherwise, in rollback mode, this function performs two functions:
  32467. **
  32468. ** 1) It rolls back the journal file, restoring all database file and
  32469. ** in-memory cache pages to the state they were in when the transaction
  32470. ** was opened, and
  32471. **
  32472. ** 2) It finalizes the journal file, so that it is not used for hot
  32473. ** rollback at any point in the future.
  32474. **
  32475. ** Finalization of the journal file (task 2) is only performed if the
  32476. ** rollback is successful.
  32477. **
  32478. ** In WAL mode, all cache-entries containing data modified within the
  32479. ** current transaction are either expelled from the cache or reverted to
  32480. ** their pre-transaction state by re-reading data from the database or
  32481. ** WAL files. The WAL transaction is then closed.
  32482. */
  32483. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  32484. int rc = SQLITE_OK; /* Return code */
  32485. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  32486. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  32487. ** the pager is already in the ERROR state, the rollback is not
  32488. ** attempted here. Instead, the error code is returned to the caller.
  32489. */
  32490. assert( assert_pager_state(pPager) );
  32491. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  32492. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  32493. if( pagerUseWal(pPager) ){
  32494. int rc2;
  32495. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  32496. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  32497. if( rc==SQLITE_OK ) rc = rc2;
  32498. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  32499. int eState = pPager->eState;
  32500. rc = pager_end_transaction(pPager, 0, 0);
  32501. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  32502. /* This can happen using journal_mode=off. Move the pager to the error
  32503. ** state to indicate that the contents of the cache may not be trusted.
  32504. ** Any active readers will get SQLITE_ABORT.
  32505. */
  32506. pPager->errCode = SQLITE_ABORT;
  32507. pPager->eState = PAGER_ERROR;
  32508. return rc;
  32509. }
  32510. }else{
  32511. rc = pager_playback(pPager, 0);
  32512. }
  32513. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  32514. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  32515. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  32516. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  32517. ** cache. So call pager_error() on the way out to make any error persistent.
  32518. */
  32519. return pager_error(pPager, rc);
  32520. }
  32521. /*
  32522. ** Return TRUE if the database file is opened read-only. Return FALSE
  32523. ** if the database is (in theory) writable.
  32524. */
  32525. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  32526. return pPager->readOnly;
  32527. }
  32528. /*
  32529. ** Return the number of references to the pager.
  32530. */
  32531. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  32532. return sqlite3PcacheRefCount(pPager->pPCache);
  32533. }
  32534. /*
  32535. ** Return the approximate number of bytes of memory currently
  32536. ** used by the pager and its associated cache.
  32537. */
  32538. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  32539. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  32540. + 5*sizeof(void*);
  32541. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  32542. + sqlite3MallocSize(pPager)
  32543. + pPager->pageSize;
  32544. }
  32545. /*
  32546. ** Return the number of references to the specified page.
  32547. */
  32548. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  32549. return sqlite3PcachePageRefcount(pPage);
  32550. }
  32551. #ifdef SQLITE_TEST
  32552. /*
  32553. ** This routine is used for testing and analysis only.
  32554. */
  32555. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  32556. static int a[11];
  32557. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  32558. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  32559. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  32560. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  32561. a[4] = pPager->eState;
  32562. a[5] = pPager->errCode;
  32563. a[6] = pPager->aStat[PAGER_STAT_HIT];
  32564. a[7] = pPager->aStat[PAGER_STAT_MISS];
  32565. a[8] = 0; /* Used to be pPager->nOvfl */
  32566. a[9] = pPager->nRead;
  32567. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  32568. return a;
  32569. }
  32570. #endif
  32571. /*
  32572. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  32573. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  32574. ** current cache hit or miss count, according to the value of eStat. If the
  32575. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  32576. ** returning.
  32577. */
  32578. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  32579. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  32580. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  32581. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  32582. );
  32583. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  32584. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  32585. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  32586. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  32587. if( reset ){
  32588. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  32589. }
  32590. }
  32591. /*
  32592. ** Return true if this is an in-memory pager.
  32593. */
  32594. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  32595. return MEMDB;
  32596. }
  32597. /*
  32598. ** Check that there are at least nSavepoint savepoints open. If there are
  32599. ** currently less than nSavepoints open, then open one or more savepoints
  32600. ** to make up the difference. If the number of savepoints is already
  32601. ** equal to nSavepoint, then this function is a no-op.
  32602. **
  32603. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  32604. ** occurs while opening the sub-journal file, then an IO error code is
  32605. ** returned. Otherwise, SQLITE_OK.
  32606. */
  32607. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  32608. int rc = SQLITE_OK; /* Return code */
  32609. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  32610. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  32611. assert( assert_pager_state(pPager) );
  32612. if( nSavepoint>nCurrent && pPager->useJournal ){
  32613. int ii; /* Iterator variable */
  32614. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  32615. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  32616. ** if the allocation fails. Otherwise, zero the new portion in case a
  32617. ** malloc failure occurs while populating it in the for(...) loop below.
  32618. */
  32619. aNew = (PagerSavepoint *)sqlite3Realloc(
  32620. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  32621. );
  32622. if( !aNew ){
  32623. return SQLITE_NOMEM;
  32624. }
  32625. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  32626. pPager->aSavepoint = aNew;
  32627. /* Populate the PagerSavepoint structures just allocated. */
  32628. for(ii=nCurrent; ii<nSavepoint; ii++){
  32629. aNew[ii].nOrig = pPager->dbSize;
  32630. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  32631. aNew[ii].iOffset = pPager->journalOff;
  32632. }else{
  32633. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  32634. }
  32635. aNew[ii].iSubRec = pPager->nSubRec;
  32636. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  32637. if( !aNew[ii].pInSavepoint ){
  32638. return SQLITE_NOMEM;
  32639. }
  32640. if( pagerUseWal(pPager) ){
  32641. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  32642. }
  32643. pPager->nSavepoint = ii+1;
  32644. }
  32645. assert( pPager->nSavepoint==nSavepoint );
  32646. assertTruncateConstraint(pPager);
  32647. }
  32648. return rc;
  32649. }
  32650. /*
  32651. ** This function is called to rollback or release (commit) a savepoint.
  32652. ** The savepoint to release or rollback need not be the most recently
  32653. ** created savepoint.
  32654. **
  32655. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  32656. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  32657. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  32658. ** that have occurred since the specified savepoint was created.
  32659. **
  32660. ** The savepoint to rollback or release is identified by parameter
  32661. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  32662. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  32663. ** on the most recently created savepoint. If iSavepoint is greater than
  32664. ** (Pager.nSavepoint-1), then this function is a no-op.
  32665. **
  32666. ** If a negative value is passed to this function, then the current
  32667. ** transaction is rolled back. This is different to calling
  32668. ** sqlite3PagerRollback() because this function does not terminate
  32669. ** the transaction or unlock the database, it just restores the
  32670. ** contents of the database to its original state.
  32671. **
  32672. ** In any case, all savepoints with an index greater than iSavepoint
  32673. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  32674. ** then savepoint iSavepoint is also destroyed.
  32675. **
  32676. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  32677. ** or an IO error code if an IO error occurs while rolling back a
  32678. ** savepoint. If no errors occur, SQLITE_OK is returned.
  32679. */
  32680. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  32681. int rc = pPager->errCode; /* Return code */
  32682. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  32683. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  32684. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  32685. int ii; /* Iterator variable */
  32686. int nNew; /* Number of remaining savepoints after this op. */
  32687. /* Figure out how many savepoints will still be active after this
  32688. ** operation. Store this value in nNew. Then free resources associated
  32689. ** with any savepoints that are destroyed by this operation.
  32690. */
  32691. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  32692. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  32693. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  32694. }
  32695. pPager->nSavepoint = nNew;
  32696. /* If this is a release of the outermost savepoint, truncate
  32697. ** the sub-journal to zero bytes in size. */
  32698. if( op==SAVEPOINT_RELEASE ){
  32699. if( nNew==0 && isOpen(pPager->sjfd) ){
  32700. /* Only truncate if it is an in-memory sub-journal. */
  32701. if( sqlite3IsMemJournal(pPager->sjfd) ){
  32702. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  32703. assert( rc==SQLITE_OK );
  32704. }
  32705. pPager->nSubRec = 0;
  32706. }
  32707. }
  32708. /* Else this is a rollback operation, playback the specified savepoint.
  32709. ** If this is a temp-file, it is possible that the journal file has
  32710. ** not yet been opened. In this case there have been no changes to
  32711. ** the database file, so the playback operation can be skipped.
  32712. */
  32713. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  32714. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  32715. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  32716. assert(rc!=SQLITE_DONE);
  32717. }
  32718. }
  32719. return rc;
  32720. }
  32721. /*
  32722. ** Return the full pathname of the database file.
  32723. **
  32724. ** Except, if the pager is in-memory only, then return an empty string if
  32725. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  32726. ** used to report the filename to the user, for compatibility with legacy
  32727. ** behavior. But when the Btree needs to know the filename for matching to
  32728. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  32729. ** participate in shared-cache.
  32730. */
  32731. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  32732. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  32733. }
  32734. /*
  32735. ** Return the VFS structure for the pager.
  32736. */
  32737. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  32738. return pPager->pVfs;
  32739. }
  32740. /*
  32741. ** Return the file handle for the database file associated
  32742. ** with the pager. This might return NULL if the file has
  32743. ** not yet been opened.
  32744. */
  32745. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  32746. return pPager->fd;
  32747. }
  32748. /*
  32749. ** Return the full pathname of the journal file.
  32750. */
  32751. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  32752. return pPager->zJournal;
  32753. }
  32754. /*
  32755. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  32756. ** if fsync()s are executed normally.
  32757. */
  32758. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  32759. return pPager->noSync;
  32760. }
  32761. #ifdef SQLITE_HAS_CODEC
  32762. /*
  32763. ** Set or retrieve the codec for this pager
  32764. */
  32765. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  32766. Pager *pPager,
  32767. void *(*xCodec)(void*,void*,Pgno,int),
  32768. void (*xCodecSizeChng)(void*,int,int),
  32769. void (*xCodecFree)(void*),
  32770. void *pCodec
  32771. ){
  32772. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  32773. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  32774. pPager->xCodecSizeChng = xCodecSizeChng;
  32775. pPager->xCodecFree = xCodecFree;
  32776. pPager->pCodec = pCodec;
  32777. pagerReportSize(pPager);
  32778. }
  32779. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  32780. return pPager->pCodec;
  32781. }
  32782. /*
  32783. ** This function is called by the wal module when writing page content
  32784. ** into the log file.
  32785. **
  32786. ** This function returns a pointer to a buffer containing the encrypted
  32787. ** page content. If a malloc fails, this function may return NULL.
  32788. */
  32789. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  32790. void *aData = 0;
  32791. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  32792. return aData;
  32793. }
  32794. /*
  32795. ** Return the current pager state
  32796. */
  32797. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  32798. return pPager->eState;
  32799. }
  32800. #endif /* SQLITE_HAS_CODEC */
  32801. #ifndef SQLITE_OMIT_AUTOVACUUM
  32802. /*
  32803. ** Move the page pPg to location pgno in the file.
  32804. **
  32805. ** There must be no references to the page previously located at
  32806. ** pgno (which we call pPgOld) though that page is allowed to be
  32807. ** in cache. If the page previously located at pgno is not already
  32808. ** in the rollback journal, it is not put there by by this routine.
  32809. **
  32810. ** References to the page pPg remain valid. Updating any
  32811. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  32812. ** allocated along with the page) is the responsibility of the caller.
  32813. **
  32814. ** A transaction must be active when this routine is called. It used to be
  32815. ** required that a statement transaction was not active, but this restriction
  32816. ** has been removed (CREATE INDEX needs to move a page when a statement
  32817. ** transaction is active).
  32818. **
  32819. ** If the fourth argument, isCommit, is non-zero, then this page is being
  32820. ** moved as part of a database reorganization just before the transaction
  32821. ** is being committed. In this case, it is guaranteed that the database page
  32822. ** pPg refers to will not be written to again within this transaction.
  32823. **
  32824. ** This function may return SQLITE_NOMEM or an IO error code if an error
  32825. ** occurs. Otherwise, it returns SQLITE_OK.
  32826. */
  32827. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  32828. PgHdr *pPgOld; /* The page being overwritten. */
  32829. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  32830. int rc; /* Return code */
  32831. Pgno origPgno; /* The original page number */
  32832. assert( pPg->nRef>0 );
  32833. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32834. || pPager->eState==PAGER_WRITER_DBMOD
  32835. );
  32836. assert( assert_pager_state(pPager) );
  32837. /* In order to be able to rollback, an in-memory database must journal
  32838. ** the page we are moving from.
  32839. */
  32840. if( MEMDB ){
  32841. rc = sqlite3PagerWrite(pPg);
  32842. if( rc ) return rc;
  32843. }
  32844. /* If the page being moved is dirty and has not been saved by the latest
  32845. ** savepoint, then save the current contents of the page into the
  32846. ** sub-journal now. This is required to handle the following scenario:
  32847. **
  32848. ** BEGIN;
  32849. ** <journal page X, then modify it in memory>
  32850. ** SAVEPOINT one;
  32851. ** <Move page X to location Y>
  32852. ** ROLLBACK TO one;
  32853. **
  32854. ** If page X were not written to the sub-journal here, it would not
  32855. ** be possible to restore its contents when the "ROLLBACK TO one"
  32856. ** statement were is processed.
  32857. **
  32858. ** subjournalPage() may need to allocate space to store pPg->pgno into
  32859. ** one or more savepoint bitvecs. This is the reason this function
  32860. ** may return SQLITE_NOMEM.
  32861. */
  32862. if( pPg->flags&PGHDR_DIRTY
  32863. && subjRequiresPage(pPg)
  32864. && SQLITE_OK!=(rc = subjournalPage(pPg))
  32865. ){
  32866. return rc;
  32867. }
  32868. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  32869. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  32870. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  32871. /* If the journal needs to be sync()ed before page pPg->pgno can
  32872. ** be written to, store pPg->pgno in local variable needSyncPgno.
  32873. **
  32874. ** If the isCommit flag is set, there is no need to remember that
  32875. ** the journal needs to be sync()ed before database page pPg->pgno
  32876. ** can be written to. The caller has already promised not to write to it.
  32877. */
  32878. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  32879. needSyncPgno = pPg->pgno;
  32880. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  32881. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  32882. assert( pPg->flags&PGHDR_DIRTY );
  32883. }
  32884. /* If the cache contains a page with page-number pgno, remove it
  32885. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  32886. ** page pgno before the 'move' operation, it needs to be retained
  32887. ** for the page moved there.
  32888. */
  32889. pPg->flags &= ~PGHDR_NEED_SYNC;
  32890. pPgOld = pager_lookup(pPager, pgno);
  32891. assert( !pPgOld || pPgOld->nRef==1 );
  32892. if( pPgOld ){
  32893. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  32894. if( MEMDB ){
  32895. /* Do not discard pages from an in-memory database since we might
  32896. ** need to rollback later. Just move the page out of the way. */
  32897. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  32898. }else{
  32899. sqlite3PcacheDrop(pPgOld);
  32900. }
  32901. }
  32902. origPgno = pPg->pgno;
  32903. sqlite3PcacheMove(pPg, pgno);
  32904. sqlite3PcacheMakeDirty(pPg);
  32905. /* For an in-memory database, make sure the original page continues
  32906. ** to exist, in case the transaction needs to roll back. Use pPgOld
  32907. ** as the original page since it has already been allocated.
  32908. */
  32909. if( MEMDB ){
  32910. assert( pPgOld );
  32911. sqlite3PcacheMove(pPgOld, origPgno);
  32912. sqlite3PagerUnref(pPgOld);
  32913. }
  32914. if( needSyncPgno ){
  32915. /* If needSyncPgno is non-zero, then the journal file needs to be
  32916. ** sync()ed before any data is written to database file page needSyncPgno.
  32917. ** Currently, no such page exists in the page-cache and the
  32918. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  32919. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  32920. ** flag.
  32921. **
  32922. ** If the attempt to load the page into the page-cache fails, (due
  32923. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  32924. ** array. Otherwise, if the page is loaded and written again in
  32925. ** this transaction, it may be written to the database file before
  32926. ** it is synced into the journal file. This way, it may end up in
  32927. ** the journal file twice, but that is not a problem.
  32928. */
  32929. PgHdr *pPgHdr;
  32930. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  32931. if( rc!=SQLITE_OK ){
  32932. if( needSyncPgno<=pPager->dbOrigSize ){
  32933. assert( pPager->pTmpSpace!=0 );
  32934. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  32935. }
  32936. return rc;
  32937. }
  32938. pPgHdr->flags |= PGHDR_NEED_SYNC;
  32939. sqlite3PcacheMakeDirty(pPgHdr);
  32940. sqlite3PagerUnref(pPgHdr);
  32941. }
  32942. return SQLITE_OK;
  32943. }
  32944. #endif
  32945. /*
  32946. ** Return a pointer to the data for the specified page.
  32947. */
  32948. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  32949. assert( pPg->nRef>0 || pPg->pPager->memDb );
  32950. return pPg->pData;
  32951. }
  32952. /*
  32953. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  32954. ** allocated along with the specified page.
  32955. */
  32956. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  32957. return pPg->pExtra;
  32958. }
  32959. /*
  32960. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  32961. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  32962. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  32963. ** the locking-mode is set to the value specified.
  32964. **
  32965. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  32966. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  32967. ** locking-mode.
  32968. */
  32969. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  32970. assert( eMode==PAGER_LOCKINGMODE_QUERY
  32971. || eMode==PAGER_LOCKINGMODE_NORMAL
  32972. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  32973. assert( PAGER_LOCKINGMODE_QUERY<0 );
  32974. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  32975. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  32976. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  32977. pPager->exclusiveMode = (u8)eMode;
  32978. }
  32979. return (int)pPager->exclusiveMode;
  32980. }
  32981. /*
  32982. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  32983. **
  32984. ** PAGER_JOURNALMODE_DELETE
  32985. ** PAGER_JOURNALMODE_TRUNCATE
  32986. ** PAGER_JOURNALMODE_PERSIST
  32987. ** PAGER_JOURNALMODE_OFF
  32988. ** PAGER_JOURNALMODE_MEMORY
  32989. ** PAGER_JOURNALMODE_WAL
  32990. **
  32991. ** The journalmode is set to the value specified if the change is allowed.
  32992. ** The change may be disallowed for the following reasons:
  32993. **
  32994. ** * An in-memory database can only have its journal_mode set to _OFF
  32995. ** or _MEMORY.
  32996. **
  32997. ** * Temporary databases cannot have _WAL journalmode.
  32998. **
  32999. ** The returned indicate the current (possibly updated) journal-mode.
  33000. */
  33001. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  33002. u8 eOld = pPager->journalMode; /* Prior journalmode */
  33003. #ifdef SQLITE_DEBUG
  33004. /* The print_pager_state() routine is intended to be used by the debugger
  33005. ** only. We invoke it once here to suppress a compiler warning. */
  33006. print_pager_state(pPager);
  33007. #endif
  33008. /* The eMode parameter is always valid */
  33009. assert( eMode==PAGER_JOURNALMODE_DELETE
  33010. || eMode==PAGER_JOURNALMODE_TRUNCATE
  33011. || eMode==PAGER_JOURNALMODE_PERSIST
  33012. || eMode==PAGER_JOURNALMODE_OFF
  33013. || eMode==PAGER_JOURNALMODE_WAL
  33014. || eMode==PAGER_JOURNALMODE_MEMORY );
  33015. /* This routine is only called from the OP_JournalMode opcode, and
  33016. ** the logic there will never allow a temporary file to be changed
  33017. ** to WAL mode.
  33018. */
  33019. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  33020. /* Do allow the journalmode of an in-memory database to be set to
  33021. ** anything other than MEMORY or OFF
  33022. */
  33023. if( MEMDB ){
  33024. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  33025. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  33026. eMode = eOld;
  33027. }
  33028. }
  33029. if( eMode!=eOld ){
  33030. /* Change the journal mode. */
  33031. assert( pPager->eState!=PAGER_ERROR );
  33032. pPager->journalMode = (u8)eMode;
  33033. /* When transistioning from TRUNCATE or PERSIST to any other journal
  33034. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  33035. ** delete the journal file.
  33036. */
  33037. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  33038. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  33039. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  33040. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  33041. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  33042. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  33043. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  33044. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  33045. /* In this case we would like to delete the journal file. If it is
  33046. ** not possible, then that is not a problem. Deleting the journal file
  33047. ** here is an optimization only.
  33048. **
  33049. ** Before deleting the journal file, obtain a RESERVED lock on the
  33050. ** database file. This ensures that the journal file is not deleted
  33051. ** while it is in use by some other client.
  33052. */
  33053. sqlite3OsClose(pPager->jfd);
  33054. if( pPager->eLock>=RESERVED_LOCK ){
  33055. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  33056. }else{
  33057. int rc = SQLITE_OK;
  33058. int state = pPager->eState;
  33059. assert( state==PAGER_OPEN || state==PAGER_READER );
  33060. if( state==PAGER_OPEN ){
  33061. rc = sqlite3PagerSharedLock(pPager);
  33062. }
  33063. if( pPager->eState==PAGER_READER ){
  33064. assert( rc==SQLITE_OK );
  33065. rc = pagerLockDb(pPager, RESERVED_LOCK);
  33066. }
  33067. if( rc==SQLITE_OK ){
  33068. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  33069. }
  33070. if( rc==SQLITE_OK && state==PAGER_READER ){
  33071. pagerUnlockDb(pPager, SHARED_LOCK);
  33072. }else if( state==PAGER_OPEN ){
  33073. pager_unlock(pPager);
  33074. }
  33075. assert( state==pPager->eState );
  33076. }
  33077. }
  33078. }
  33079. /* Return the new journal mode */
  33080. return (int)pPager->journalMode;
  33081. }
  33082. /*
  33083. ** Return the current journal mode.
  33084. */
  33085. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  33086. return (int)pPager->journalMode;
  33087. }
  33088. /*
  33089. ** Return TRUE if the pager is in a state where it is OK to change the
  33090. ** journalmode. Journalmode changes can only happen when the database
  33091. ** is unmodified.
  33092. */
  33093. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  33094. assert( assert_pager_state(pPager) );
  33095. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  33096. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  33097. return 1;
  33098. }
  33099. /*
  33100. ** Get/set the size-limit used for persistent journal files.
  33101. **
  33102. ** Setting the size limit to -1 means no limit is enforced.
  33103. ** An attempt to set a limit smaller than -1 is a no-op.
  33104. */
  33105. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  33106. if( iLimit>=-1 ){
  33107. pPager->journalSizeLimit = iLimit;
  33108. sqlite3WalLimit(pPager->pWal, iLimit);
  33109. }
  33110. return pPager->journalSizeLimit;
  33111. }
  33112. /*
  33113. ** Return a pointer to the pPager->pBackup variable. The backup module
  33114. ** in backup.c maintains the content of this variable. This module
  33115. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  33116. ** sqlite3BackupUpdate() only.
  33117. */
  33118. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  33119. return &pPager->pBackup;
  33120. }
  33121. #ifndef SQLITE_OMIT_VACUUM
  33122. /*
  33123. ** Unless this is an in-memory or temporary database, clear the pager cache.
  33124. */
  33125. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  33126. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  33127. }
  33128. #endif
  33129. #ifndef SQLITE_OMIT_WAL
  33130. /*
  33131. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  33132. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  33133. ** or wal_blocking_checkpoint() API functions.
  33134. **
  33135. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  33136. */
  33137. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  33138. int rc = SQLITE_OK;
  33139. if( pPager->pWal ){
  33140. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  33141. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  33142. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  33143. pnLog, pnCkpt
  33144. );
  33145. }
  33146. return rc;
  33147. }
  33148. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  33149. return sqlite3WalCallback(pPager->pWal);
  33150. }
  33151. /*
  33152. ** Return true if the underlying VFS for the given pager supports the
  33153. ** primitives necessary for write-ahead logging.
  33154. */
  33155. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  33156. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  33157. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  33158. }
  33159. /*
  33160. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  33161. ** is obtained instead, immediately release it.
  33162. */
  33163. static int pagerExclusiveLock(Pager *pPager){
  33164. int rc; /* Return code */
  33165. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  33166. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  33167. if( rc!=SQLITE_OK ){
  33168. /* If the attempt to grab the exclusive lock failed, release the
  33169. ** pending lock that may have been obtained instead. */
  33170. pagerUnlockDb(pPager, SHARED_LOCK);
  33171. }
  33172. return rc;
  33173. }
  33174. /*
  33175. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  33176. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  33177. ** lock on the database file and use heap-memory to store the wal-index
  33178. ** in. Otherwise, use the normal shared-memory.
  33179. */
  33180. static int pagerOpenWal(Pager *pPager){
  33181. int rc = SQLITE_OK;
  33182. assert( pPager->pWal==0 && pPager->tempFile==0 );
  33183. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  33184. /* If the pager is already in exclusive-mode, the WAL module will use
  33185. ** heap-memory for the wal-index instead of the VFS shared-memory
  33186. ** implementation. Take the exclusive lock now, before opening the WAL
  33187. ** file, to make sure this is safe.
  33188. */
  33189. if( pPager->exclusiveMode ){
  33190. rc = pagerExclusiveLock(pPager);
  33191. }
  33192. /* Open the connection to the log file. If this operation fails,
  33193. ** (e.g. due to malloc() failure), return an error code.
  33194. */
  33195. if( rc==SQLITE_OK ){
  33196. rc = sqlite3WalOpen(pPager->pVfs,
  33197. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  33198. pPager->journalSizeLimit, &pPager->pWal
  33199. );
  33200. }
  33201. pagerFixMaplimit(pPager);
  33202. return rc;
  33203. }
  33204. /*
  33205. ** The caller must be holding a SHARED lock on the database file to call
  33206. ** this function.
  33207. **
  33208. ** If the pager passed as the first argument is open on a real database
  33209. ** file (not a temp file or an in-memory database), and the WAL file
  33210. ** is not already open, make an attempt to open it now. If successful,
  33211. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  33212. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  33213. ** not modified in either case.
  33214. **
  33215. ** If the pager is open on a temp-file (or in-memory database), or if
  33216. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  33217. ** without doing anything.
  33218. */
  33219. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  33220. Pager *pPager, /* Pager object */
  33221. int *pbOpen /* OUT: Set to true if call is a no-op */
  33222. ){
  33223. int rc = SQLITE_OK; /* Return code */
  33224. assert( assert_pager_state(pPager) );
  33225. assert( pPager->eState==PAGER_OPEN || pbOpen );
  33226. assert( pPager->eState==PAGER_READER || !pbOpen );
  33227. assert( pbOpen==0 || *pbOpen==0 );
  33228. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  33229. if( !pPager->tempFile && !pPager->pWal ){
  33230. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  33231. /* Close any rollback journal previously open */
  33232. sqlite3OsClose(pPager->jfd);
  33233. rc = pagerOpenWal(pPager);
  33234. if( rc==SQLITE_OK ){
  33235. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  33236. pPager->eState = PAGER_OPEN;
  33237. }
  33238. }else{
  33239. *pbOpen = 1;
  33240. }
  33241. return rc;
  33242. }
  33243. /*
  33244. ** This function is called to close the connection to the log file prior
  33245. ** to switching from WAL to rollback mode.
  33246. **
  33247. ** Before closing the log file, this function attempts to take an
  33248. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  33249. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  33250. ** If successful, the EXCLUSIVE lock is not released before returning.
  33251. */
  33252. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  33253. int rc = SQLITE_OK;
  33254. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  33255. /* If the log file is not already open, but does exist in the file-system,
  33256. ** it may need to be checkpointed before the connection can switch to
  33257. ** rollback mode. Open it now so this can happen.
  33258. */
  33259. if( !pPager->pWal ){
  33260. int logexists = 0;
  33261. rc = pagerLockDb(pPager, SHARED_LOCK);
  33262. if( rc==SQLITE_OK ){
  33263. rc = sqlite3OsAccess(
  33264. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  33265. );
  33266. }
  33267. if( rc==SQLITE_OK && logexists ){
  33268. rc = pagerOpenWal(pPager);
  33269. }
  33270. }
  33271. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  33272. ** the database file, the log and log-summary files will be deleted.
  33273. */
  33274. if( rc==SQLITE_OK && pPager->pWal ){
  33275. rc = pagerExclusiveLock(pPager);
  33276. if( rc==SQLITE_OK ){
  33277. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  33278. pPager->pageSize, (u8*)pPager->pTmpSpace);
  33279. pPager->pWal = 0;
  33280. pagerFixMaplimit(pPager);
  33281. }
  33282. }
  33283. return rc;
  33284. }
  33285. #endif /* !SQLITE_OMIT_WAL */
  33286. #ifdef SQLITE_ENABLE_ZIPVFS
  33287. /*
  33288. ** A read-lock must be held on the pager when this function is called. If
  33289. ** the pager is in WAL mode and the WAL file currently contains one or more
  33290. ** frames, return the size in bytes of the page images stored within the
  33291. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  33292. ** is empty, return 0.
  33293. */
  33294. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  33295. assert( pPager->eState==PAGER_READER );
  33296. return sqlite3WalFramesize(pPager->pWal);
  33297. }
  33298. #endif
  33299. #endif /* SQLITE_OMIT_DISKIO */
  33300. /************** End of pager.c ***********************************************/
  33301. /************** Begin file wal.c *********************************************/
  33302. /*
  33303. ** 2010 February 1
  33304. **
  33305. ** The author disclaims copyright to this source code. In place of
  33306. ** a legal notice, here is a blessing:
  33307. **
  33308. ** May you do good and not evil.
  33309. ** May you find forgiveness for yourself and forgive others.
  33310. ** May you share freely, never taking more than you give.
  33311. **
  33312. *************************************************************************
  33313. **
  33314. ** This file contains the implementation of a write-ahead log (WAL) used in
  33315. ** "journal_mode=WAL" mode.
  33316. **
  33317. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  33318. **
  33319. ** A WAL file consists of a header followed by zero or more "frames".
  33320. ** Each frame records the revised content of a single page from the
  33321. ** database file. All changes to the database are recorded by writing
  33322. ** frames into the WAL. Transactions commit when a frame is written that
  33323. ** contains a commit marker. A single WAL can and usually does record
  33324. ** multiple transactions. Periodically, the content of the WAL is
  33325. ** transferred back into the database file in an operation called a
  33326. ** "checkpoint".
  33327. **
  33328. ** A single WAL file can be used multiple times. In other words, the
  33329. ** WAL can fill up with frames and then be checkpointed and then new
  33330. ** frames can overwrite the old ones. A WAL always grows from beginning
  33331. ** toward the end. Checksums and counters attached to each frame are
  33332. ** used to determine which frames within the WAL are valid and which
  33333. ** are leftovers from prior checkpoints.
  33334. **
  33335. ** The WAL header is 32 bytes in size and consists of the following eight
  33336. ** big-endian 32-bit unsigned integer values:
  33337. **
  33338. ** 0: Magic number. 0x377f0682 or 0x377f0683
  33339. ** 4: File format version. Currently 3007000
  33340. ** 8: Database page size. Example: 1024
  33341. ** 12: Checkpoint sequence number
  33342. ** 16: Salt-1, random integer incremented with each checkpoint
  33343. ** 20: Salt-2, a different random integer changing with each ckpt
  33344. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  33345. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  33346. **
  33347. ** Immediately following the wal-header are zero or more frames. Each
  33348. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  33349. ** of page data. The frame-header is six big-endian 32-bit unsigned
  33350. ** integer values, as follows:
  33351. **
  33352. ** 0: Page number.
  33353. ** 4: For commit records, the size of the database image in pages
  33354. ** after the commit. For all other records, zero.
  33355. ** 8: Salt-1 (copied from the header)
  33356. ** 12: Salt-2 (copied from the header)
  33357. ** 16: Checksum-1.
  33358. ** 20: Checksum-2.
  33359. **
  33360. ** A frame is considered valid if and only if the following conditions are
  33361. ** true:
  33362. **
  33363. ** (1) The salt-1 and salt-2 values in the frame-header match
  33364. ** salt values in the wal-header
  33365. **
  33366. ** (2) The checksum values in the final 8 bytes of the frame-header
  33367. ** exactly match the checksum computed consecutively on the
  33368. ** WAL header and the first 8 bytes and the content of all frames
  33369. ** up to and including the current frame.
  33370. **
  33371. ** The checksum is computed using 32-bit big-endian integers if the
  33372. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  33373. ** is computed using little-endian if the magic number is 0x377f0682.
  33374. ** The checksum values are always stored in the frame header in a
  33375. ** big-endian format regardless of which byte order is used to compute
  33376. ** the checksum. The checksum is computed by interpreting the input as
  33377. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  33378. ** algorithm used for the checksum is as follows:
  33379. **
  33380. ** for i from 0 to n-1 step 2:
  33381. ** s0 += x[i] + s1;
  33382. ** s1 += x[i+1] + s0;
  33383. ** endfor
  33384. **
  33385. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  33386. ** in reverse order (the largest fibonacci weight occurs on the first element
  33387. ** of the sequence being summed.) The s1 value spans all 32-bit
  33388. ** terms of the sequence whereas s0 omits the final term.
  33389. **
  33390. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  33391. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  33392. ** The VFS.xSync operations serve as write barriers - all writes launched
  33393. ** before the xSync must complete before any write that launches after the
  33394. ** xSync begins.
  33395. **
  33396. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  33397. ** value is randomized. This prevents old and new frames in the WAL from
  33398. ** being considered valid at the same time and being checkpointing together
  33399. ** following a crash.
  33400. **
  33401. ** READER ALGORITHM
  33402. **
  33403. ** To read a page from the database (call it page number P), a reader
  33404. ** first checks the WAL to see if it contains page P. If so, then the
  33405. ** last valid instance of page P that is a followed by a commit frame
  33406. ** or is a commit frame itself becomes the value read. If the WAL
  33407. ** contains no copies of page P that are valid and which are a commit
  33408. ** frame or are followed by a commit frame, then page P is read from
  33409. ** the database file.
  33410. **
  33411. ** To start a read transaction, the reader records the index of the last
  33412. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  33413. ** for all subsequent read operations. New transactions can be appended
  33414. ** to the WAL, but as long as the reader uses its original mxFrame value
  33415. ** and ignores the newly appended content, it will see a consistent snapshot
  33416. ** of the database from a single point in time. This technique allows
  33417. ** multiple concurrent readers to view different versions of the database
  33418. ** content simultaneously.
  33419. **
  33420. ** The reader algorithm in the previous paragraphs works correctly, but
  33421. ** because frames for page P can appear anywhere within the WAL, the
  33422. ** reader has to scan the entire WAL looking for page P frames. If the
  33423. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  33424. ** and read performance suffers. To overcome this problem, a separate
  33425. ** data structure called the wal-index is maintained to expedite the
  33426. ** search for frames of a particular page.
  33427. **
  33428. ** WAL-INDEX FORMAT
  33429. **
  33430. ** Conceptually, the wal-index is shared memory, though VFS implementations
  33431. ** might choose to implement the wal-index using a mmapped file. Because
  33432. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  33433. ** on a network filesystem. All users of the database must be able to
  33434. ** share memory.
  33435. **
  33436. ** The wal-index is transient. After a crash, the wal-index can (and should
  33437. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  33438. ** to either truncate or zero the header of the wal-index when the last
  33439. ** connection to it closes. Because the wal-index is transient, it can
  33440. ** use an architecture-specific format; it does not have to be cross-platform.
  33441. ** Hence, unlike the database and WAL file formats which store all values
  33442. ** as big endian, the wal-index can store multi-byte values in the native
  33443. ** byte order of the host computer.
  33444. **
  33445. ** The purpose of the wal-index is to answer this question quickly: Given
  33446. ** a page number P and a maximum frame index M, return the index of the
  33447. ** last frame in the wal before frame M for page P in the WAL, or return
  33448. ** NULL if there are no frames for page P in the WAL prior to M.
  33449. **
  33450. ** The wal-index consists of a header region, followed by an one or
  33451. ** more index blocks.
  33452. **
  33453. ** The wal-index header contains the total number of frames within the WAL
  33454. ** in the mxFrame field.
  33455. **
  33456. ** Each index block except for the first contains information on
  33457. ** HASHTABLE_NPAGE frames. The first index block contains information on
  33458. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  33459. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  33460. ** first index block are the same size as all other index blocks in the
  33461. ** wal-index.
  33462. **
  33463. ** Each index block contains two sections, a page-mapping that contains the
  33464. ** database page number associated with each wal frame, and a hash-table
  33465. ** that allows readers to query an index block for a specific page number.
  33466. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  33467. ** for the first index block) 32-bit page numbers. The first entry in the
  33468. ** first index-block contains the database page number corresponding to the
  33469. ** first frame in the WAL file. The first entry in the second index block
  33470. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  33471. ** the log, and so on.
  33472. **
  33473. ** The last index block in a wal-index usually contains less than the full
  33474. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  33475. ** depending on the contents of the WAL file. This does not change the
  33476. ** allocated size of the page-mapping array - the page-mapping array merely
  33477. ** contains unused entries.
  33478. **
  33479. ** Even without using the hash table, the last frame for page P
  33480. ** can be found by scanning the page-mapping sections of each index block
  33481. ** starting with the last index block and moving toward the first, and
  33482. ** within each index block, starting at the end and moving toward the
  33483. ** beginning. The first entry that equals P corresponds to the frame
  33484. ** holding the content for that page.
  33485. **
  33486. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  33487. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  33488. ** hash table for each page number in the mapping section, so the hash
  33489. ** table is never more than half full. The expected number of collisions
  33490. ** prior to finding a match is 1. Each entry of the hash table is an
  33491. ** 1-based index of an entry in the mapping section of the same
  33492. ** index block. Let K be the 1-based index of the largest entry in
  33493. ** the mapping section. (For index blocks other than the last, K will
  33494. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  33495. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  33496. ** contain a value of 0.
  33497. **
  33498. ** To look for page P in the hash table, first compute a hash iKey on
  33499. ** P as follows:
  33500. **
  33501. ** iKey = (P * 383) % HASHTABLE_NSLOT
  33502. **
  33503. ** Then start scanning entries of the hash table, starting with iKey
  33504. ** (wrapping around to the beginning when the end of the hash table is
  33505. ** reached) until an unused hash slot is found. Let the first unused slot
  33506. ** be at index iUnused. (iUnused might be less than iKey if there was
  33507. ** wrap-around.) Because the hash table is never more than half full,
  33508. ** the search is guaranteed to eventually hit an unused entry. Let
  33509. ** iMax be the value between iKey and iUnused, closest to iUnused,
  33510. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  33511. ** no hash slot such that aHash[i]==p) then page P is not in the
  33512. ** current index block. Otherwise the iMax-th mapping entry of the
  33513. ** current index block corresponds to the last entry that references
  33514. ** page P.
  33515. **
  33516. ** A hash search begins with the last index block and moves toward the
  33517. ** first index block, looking for entries corresponding to page P. On
  33518. ** average, only two or three slots in each index block need to be
  33519. ** examined in order to either find the last entry for page P, or to
  33520. ** establish that no such entry exists in the block. Each index block
  33521. ** holds over 4000 entries. So two or three index blocks are sufficient
  33522. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  33523. ** comparisons (on average) suffice to either locate a frame in the
  33524. ** WAL or to establish that the frame does not exist in the WAL. This
  33525. ** is much faster than scanning the entire 10MB WAL.
  33526. **
  33527. ** Note that entries are added in order of increasing K. Hence, one
  33528. ** reader might be using some value K0 and a second reader that started
  33529. ** at a later time (after additional transactions were added to the WAL
  33530. ** and to the wal-index) might be using a different value K1, where K1>K0.
  33531. ** Both readers can use the same hash table and mapping section to get
  33532. ** the correct result. There may be entries in the hash table with
  33533. ** K>K0 but to the first reader, those entries will appear to be unused
  33534. ** slots in the hash table and so the first reader will get an answer as
  33535. ** if no values greater than K0 had ever been inserted into the hash table
  33536. ** in the first place - which is what reader one wants. Meanwhile, the
  33537. ** second reader using K1 will see additional values that were inserted
  33538. ** later, which is exactly what reader two wants.
  33539. **
  33540. ** When a rollback occurs, the value of K is decreased. Hash table entries
  33541. ** that correspond to frames greater than the new K value are removed
  33542. ** from the hash table at this point.
  33543. */
  33544. #ifndef SQLITE_OMIT_WAL
  33545. /*
  33546. ** Trace output macros
  33547. */
  33548. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  33549. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  33550. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  33551. #else
  33552. # define WALTRACE(X)
  33553. #endif
  33554. /*
  33555. ** The maximum (and only) versions of the wal and wal-index formats
  33556. ** that may be interpreted by this version of SQLite.
  33557. **
  33558. ** If a client begins recovering a WAL file and finds that (a) the checksum
  33559. ** values in the wal-header are correct and (b) the version field is not
  33560. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  33561. **
  33562. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  33563. ** checksum test is successful) and finds that the version field is not
  33564. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  33565. ** returns SQLITE_CANTOPEN.
  33566. */
  33567. #define WAL_MAX_VERSION 3007000
  33568. #define WALINDEX_MAX_VERSION 3007000
  33569. /*
  33570. ** Indices of various locking bytes. WAL_NREADER is the number
  33571. ** of available reader locks and should be at least 3.
  33572. */
  33573. #define WAL_WRITE_LOCK 0
  33574. #define WAL_ALL_BUT_WRITE 1
  33575. #define WAL_CKPT_LOCK 1
  33576. #define WAL_RECOVER_LOCK 2
  33577. #define WAL_READ_LOCK(I) (3+(I))
  33578. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  33579. /* Object declarations */
  33580. typedef struct WalIndexHdr WalIndexHdr;
  33581. typedef struct WalIterator WalIterator;
  33582. typedef struct WalCkptInfo WalCkptInfo;
  33583. /*
  33584. ** The following object holds a copy of the wal-index header content.
  33585. **
  33586. ** The actual header in the wal-index consists of two copies of this
  33587. ** object.
  33588. **
  33589. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  33590. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  33591. ** added in 3.7.1 when support for 64K pages was added.
  33592. */
  33593. struct WalIndexHdr {
  33594. u32 iVersion; /* Wal-index version */
  33595. u32 unused; /* Unused (padding) field */
  33596. u32 iChange; /* Counter incremented each transaction */
  33597. u8 isInit; /* 1 when initialized */
  33598. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  33599. u16 szPage; /* Database page size in bytes. 1==64K */
  33600. u32 mxFrame; /* Index of last valid frame in the WAL */
  33601. u32 nPage; /* Size of database in pages */
  33602. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  33603. u32 aSalt[2]; /* Two salt values copied from WAL header */
  33604. u32 aCksum[2]; /* Checksum over all prior fields */
  33605. };
  33606. /*
  33607. ** A copy of the following object occurs in the wal-index immediately
  33608. ** following the second copy of the WalIndexHdr. This object stores
  33609. ** information used by checkpoint.
  33610. **
  33611. ** nBackfill is the number of frames in the WAL that have been written
  33612. ** back into the database. (We call the act of moving content from WAL to
  33613. ** database "backfilling".) The nBackfill number is never greater than
  33614. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  33615. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  33616. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  33617. ** mxFrame back to zero when the WAL is reset.
  33618. **
  33619. ** There is one entry in aReadMark[] for each reader lock. If a reader
  33620. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  33621. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  33622. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  33623. ** a special case; its value is never used and it exists as a place-holder
  33624. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  33625. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  33626. ** directly from the database.
  33627. **
  33628. ** The value of aReadMark[K] may only be changed by a thread that
  33629. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  33630. ** aReadMark[K] cannot changed while there is a reader is using that mark
  33631. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  33632. **
  33633. ** The checkpointer may only transfer frames from WAL to database where
  33634. ** the frame numbers are less than or equal to every aReadMark[] that is
  33635. ** in use (that is, every aReadMark[j] for which there is a corresponding
  33636. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  33637. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  33638. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  33639. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  33640. ** in the WAL has been backfilled into the database) then new readers
  33641. ** will choose aReadMark[0] which has value 0 and hence such reader will
  33642. ** get all their all content directly from the database file and ignore
  33643. ** the WAL.
  33644. **
  33645. ** Writers normally append new frames to the end of the WAL. However,
  33646. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  33647. ** written back into the database) and if no readers are using the WAL
  33648. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  33649. ** the writer will first "reset" the WAL back to the beginning and start
  33650. ** writing new content beginning at frame 1.
  33651. **
  33652. ** We assume that 32-bit loads are atomic and so no locks are needed in
  33653. ** order to read from any aReadMark[] entries.
  33654. */
  33655. struct WalCkptInfo {
  33656. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  33657. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  33658. };
  33659. #define READMARK_NOT_USED 0xffffffff
  33660. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  33661. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  33662. ** only support mandatory file-locks, we do not read or write data
  33663. ** from the region of the file on which locks are applied.
  33664. */
  33665. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  33666. #define WALINDEX_LOCK_RESERVED 16
  33667. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  33668. /* Size of header before each frame in wal */
  33669. #define WAL_FRAME_HDRSIZE 24
  33670. /* Size of write ahead log header, including checksum. */
  33671. /* #define WAL_HDRSIZE 24 */
  33672. #define WAL_HDRSIZE 32
  33673. /* WAL magic value. Either this value, or the same value with the least
  33674. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  33675. ** big-endian format in the first 4 bytes of a WAL file.
  33676. **
  33677. ** If the LSB is set, then the checksums for each frame within the WAL
  33678. ** file are calculated by treating all data as an array of 32-bit
  33679. ** big-endian words. Otherwise, they are calculated by interpreting
  33680. ** all data as 32-bit little-endian words.
  33681. */
  33682. #define WAL_MAGIC 0x377f0682
  33683. /*
  33684. ** Return the offset of frame iFrame in the write-ahead log file,
  33685. ** assuming a database page size of szPage bytes. The offset returned
  33686. ** is to the start of the write-ahead log frame-header.
  33687. */
  33688. #define walFrameOffset(iFrame, szPage) ( \
  33689. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  33690. )
  33691. /*
  33692. ** An open write-ahead log file is represented by an instance of the
  33693. ** following object.
  33694. */
  33695. struct Wal {
  33696. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  33697. sqlite3_file *pDbFd; /* File handle for the database file */
  33698. sqlite3_file *pWalFd; /* File handle for WAL file */
  33699. u32 iCallback; /* Value to pass to log callback (or 0) */
  33700. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  33701. int nWiData; /* Size of array apWiData */
  33702. int szFirstBlock; /* Size of first block written to WAL file */
  33703. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  33704. u32 szPage; /* Database page size */
  33705. i16 readLock; /* Which read lock is being held. -1 for none */
  33706. u8 syncFlags; /* Flags to use to sync header writes */
  33707. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  33708. u8 writeLock; /* True if in a write transaction */
  33709. u8 ckptLock; /* True if holding a checkpoint lock */
  33710. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  33711. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  33712. u8 syncHeader; /* Fsync the WAL header if true */
  33713. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  33714. WalIndexHdr hdr; /* Wal-index header for current transaction */
  33715. const char *zWalName; /* Name of WAL file */
  33716. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  33717. #ifdef SQLITE_DEBUG
  33718. u8 lockError; /* True if a locking error has occurred */
  33719. #endif
  33720. };
  33721. /*
  33722. ** Candidate values for Wal.exclusiveMode.
  33723. */
  33724. #define WAL_NORMAL_MODE 0
  33725. #define WAL_EXCLUSIVE_MODE 1
  33726. #define WAL_HEAPMEMORY_MODE 2
  33727. /*
  33728. ** Possible values for WAL.readOnly
  33729. */
  33730. #define WAL_RDWR 0 /* Normal read/write connection */
  33731. #define WAL_RDONLY 1 /* The WAL file is readonly */
  33732. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  33733. /*
  33734. ** Each page of the wal-index mapping contains a hash-table made up of
  33735. ** an array of HASHTABLE_NSLOT elements of the following type.
  33736. */
  33737. typedef u16 ht_slot;
  33738. /*
  33739. ** This structure is used to implement an iterator that loops through
  33740. ** all frames in the WAL in database page order. Where two or more frames
  33741. ** correspond to the same database page, the iterator visits only the
  33742. ** frame most recently written to the WAL (in other words, the frame with
  33743. ** the largest index).
  33744. **
  33745. ** The internals of this structure are only accessed by:
  33746. **
  33747. ** walIteratorInit() - Create a new iterator,
  33748. ** walIteratorNext() - Step an iterator,
  33749. ** walIteratorFree() - Free an iterator.
  33750. **
  33751. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  33752. */
  33753. struct WalIterator {
  33754. int iPrior; /* Last result returned from the iterator */
  33755. int nSegment; /* Number of entries in aSegment[] */
  33756. struct WalSegment {
  33757. int iNext; /* Next slot in aIndex[] not yet returned */
  33758. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  33759. u32 *aPgno; /* Array of page numbers. */
  33760. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  33761. int iZero; /* Frame number associated with aPgno[0] */
  33762. } aSegment[1]; /* One for every 32KB page in the wal-index */
  33763. };
  33764. /*
  33765. ** Define the parameters of the hash tables in the wal-index file. There
  33766. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  33767. ** wal-index.
  33768. **
  33769. ** Changing any of these constants will alter the wal-index format and
  33770. ** create incompatibilities.
  33771. */
  33772. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  33773. #define HASHTABLE_HASH_1 383 /* Should be prime */
  33774. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  33775. /*
  33776. ** The block of page numbers associated with the first hash-table in a
  33777. ** wal-index is smaller than usual. This is so that there is a complete
  33778. ** hash-table on each aligned 32KB page of the wal-index.
  33779. */
  33780. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  33781. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  33782. #define WALINDEX_PGSZ ( \
  33783. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  33784. )
  33785. /*
  33786. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  33787. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  33788. ** numbered from zero.
  33789. **
  33790. ** If this call is successful, *ppPage is set to point to the wal-index
  33791. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  33792. ** then an SQLite error code is returned and *ppPage is set to 0.
  33793. */
  33794. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  33795. int rc = SQLITE_OK;
  33796. /* Enlarge the pWal->apWiData[] array if required */
  33797. if( pWal->nWiData<=iPage ){
  33798. int nByte = sizeof(u32*)*(iPage+1);
  33799. volatile u32 **apNew;
  33800. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  33801. if( !apNew ){
  33802. *ppPage = 0;
  33803. return SQLITE_NOMEM;
  33804. }
  33805. memset((void*)&apNew[pWal->nWiData], 0,
  33806. sizeof(u32*)*(iPage+1-pWal->nWiData));
  33807. pWal->apWiData = apNew;
  33808. pWal->nWiData = iPage+1;
  33809. }
  33810. /* Request a pointer to the required page from the VFS */
  33811. if( pWal->apWiData[iPage]==0 ){
  33812. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  33813. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  33814. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  33815. }else{
  33816. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  33817. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  33818. );
  33819. if( rc==SQLITE_READONLY ){
  33820. pWal->readOnly |= WAL_SHM_RDONLY;
  33821. rc = SQLITE_OK;
  33822. }
  33823. }
  33824. }
  33825. *ppPage = pWal->apWiData[iPage];
  33826. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  33827. return rc;
  33828. }
  33829. /*
  33830. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  33831. */
  33832. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  33833. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  33834. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  33835. }
  33836. /*
  33837. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  33838. */
  33839. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  33840. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  33841. return (volatile WalIndexHdr*)pWal->apWiData[0];
  33842. }
  33843. /*
  33844. ** The argument to this macro must be of type u32. On a little-endian
  33845. ** architecture, it returns the u32 value that results from interpreting
  33846. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  33847. ** returns the value that would be produced by intepreting the 4 bytes
  33848. ** of the input value as a little-endian integer.
  33849. */
  33850. #define BYTESWAP32(x) ( \
  33851. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  33852. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  33853. )
  33854. /*
  33855. ** Generate or extend an 8 byte checksum based on the data in
  33856. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  33857. ** initial values of 0 and 0 if aIn==NULL).
  33858. **
  33859. ** The checksum is written back into aOut[] before returning.
  33860. **
  33861. ** nByte must be a positive multiple of 8.
  33862. */
  33863. static void walChecksumBytes(
  33864. int nativeCksum, /* True for native byte-order, false for non-native */
  33865. u8 *a, /* Content to be checksummed */
  33866. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  33867. const u32 *aIn, /* Initial checksum value input */
  33868. u32 *aOut /* OUT: Final checksum value output */
  33869. ){
  33870. u32 s1, s2;
  33871. u32 *aData = (u32 *)a;
  33872. u32 *aEnd = (u32 *)&a[nByte];
  33873. if( aIn ){
  33874. s1 = aIn[0];
  33875. s2 = aIn[1];
  33876. }else{
  33877. s1 = s2 = 0;
  33878. }
  33879. assert( nByte>=8 );
  33880. assert( (nByte&0x00000007)==0 );
  33881. if( nativeCksum ){
  33882. do {
  33883. s1 += *aData++ + s2;
  33884. s2 += *aData++ + s1;
  33885. }while( aData<aEnd );
  33886. }else{
  33887. do {
  33888. s1 += BYTESWAP32(aData[0]) + s2;
  33889. s2 += BYTESWAP32(aData[1]) + s1;
  33890. aData += 2;
  33891. }while( aData<aEnd );
  33892. }
  33893. aOut[0] = s1;
  33894. aOut[1] = s2;
  33895. }
  33896. static void walShmBarrier(Wal *pWal){
  33897. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  33898. sqlite3OsShmBarrier(pWal->pDbFd);
  33899. }
  33900. }
  33901. /*
  33902. ** Write the header information in pWal->hdr into the wal-index.
  33903. **
  33904. ** The checksum on pWal->hdr is updated before it is written.
  33905. */
  33906. static void walIndexWriteHdr(Wal *pWal){
  33907. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  33908. const int nCksum = offsetof(WalIndexHdr, aCksum);
  33909. assert( pWal->writeLock );
  33910. pWal->hdr.isInit = 1;
  33911. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  33912. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  33913. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  33914. walShmBarrier(pWal);
  33915. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  33916. }
  33917. /*
  33918. ** This function encodes a single frame header and writes it to a buffer
  33919. ** supplied by the caller. A frame-header is made up of a series of
  33920. ** 4-byte big-endian integers, as follows:
  33921. **
  33922. ** 0: Page number.
  33923. ** 4: For commit records, the size of the database image in pages
  33924. ** after the commit. For all other records, zero.
  33925. ** 8: Salt-1 (copied from the wal-header)
  33926. ** 12: Salt-2 (copied from the wal-header)
  33927. ** 16: Checksum-1.
  33928. ** 20: Checksum-2.
  33929. */
  33930. static void walEncodeFrame(
  33931. Wal *pWal, /* The write-ahead log */
  33932. u32 iPage, /* Database page number for frame */
  33933. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  33934. u8 *aData, /* Pointer to page data */
  33935. u8 *aFrame /* OUT: Write encoded frame here */
  33936. ){
  33937. int nativeCksum; /* True for native byte-order checksums */
  33938. u32 *aCksum = pWal->hdr.aFrameCksum;
  33939. assert( WAL_FRAME_HDRSIZE==24 );
  33940. sqlite3Put4byte(&aFrame[0], iPage);
  33941. sqlite3Put4byte(&aFrame[4], nTruncate);
  33942. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  33943. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  33944. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  33945. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  33946. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  33947. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  33948. }
  33949. /*
  33950. ** Check to see if the frame with header in aFrame[] and content
  33951. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  33952. ** *pnTruncate and return true. Return if the frame is not valid.
  33953. */
  33954. static int walDecodeFrame(
  33955. Wal *pWal, /* The write-ahead log */
  33956. u32 *piPage, /* OUT: Database page number for frame */
  33957. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  33958. u8 *aData, /* Pointer to page data (for checksum) */
  33959. u8 *aFrame /* Frame data */
  33960. ){
  33961. int nativeCksum; /* True for native byte-order checksums */
  33962. u32 *aCksum = pWal->hdr.aFrameCksum;
  33963. u32 pgno; /* Page number of the frame */
  33964. assert( WAL_FRAME_HDRSIZE==24 );
  33965. /* A frame is only valid if the salt values in the frame-header
  33966. ** match the salt values in the wal-header.
  33967. */
  33968. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  33969. return 0;
  33970. }
  33971. /* A frame is only valid if the page number is creater than zero.
  33972. */
  33973. pgno = sqlite3Get4byte(&aFrame[0]);
  33974. if( pgno==0 ){
  33975. return 0;
  33976. }
  33977. /* A frame is only valid if a checksum of the WAL header,
  33978. ** all prior frams, the first 16 bytes of this frame-header,
  33979. ** and the frame-data matches the checksum in the last 8
  33980. ** bytes of this frame-header.
  33981. */
  33982. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  33983. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  33984. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  33985. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  33986. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  33987. ){
  33988. /* Checksum failed. */
  33989. return 0;
  33990. }
  33991. /* If we reach this point, the frame is valid. Return the page number
  33992. ** and the new database size.
  33993. */
  33994. *piPage = pgno;
  33995. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  33996. return 1;
  33997. }
  33998. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  33999. /*
  34000. ** Names of locks. This routine is used to provide debugging output and is not
  34001. ** a part of an ordinary build.
  34002. */
  34003. static const char *walLockName(int lockIdx){
  34004. if( lockIdx==WAL_WRITE_LOCK ){
  34005. return "WRITE-LOCK";
  34006. }else if( lockIdx==WAL_CKPT_LOCK ){
  34007. return "CKPT-LOCK";
  34008. }else if( lockIdx==WAL_RECOVER_LOCK ){
  34009. return "RECOVER-LOCK";
  34010. }else{
  34011. static char zName[15];
  34012. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  34013. lockIdx-WAL_READ_LOCK(0));
  34014. return zName;
  34015. }
  34016. }
  34017. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  34018. /*
  34019. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  34020. ** A lock cannot be moved directly between shared and exclusive - it must go
  34021. ** through the unlocked state first.
  34022. **
  34023. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  34024. */
  34025. static int walLockShared(Wal *pWal, int lockIdx){
  34026. int rc;
  34027. if( pWal->exclusiveMode ) return SQLITE_OK;
  34028. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  34029. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  34030. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  34031. walLockName(lockIdx), rc ? "failed" : "ok"));
  34032. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  34033. return rc;
  34034. }
  34035. static void walUnlockShared(Wal *pWal, int lockIdx){
  34036. if( pWal->exclusiveMode ) return;
  34037. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  34038. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  34039. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  34040. }
  34041. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  34042. int rc;
  34043. if( pWal->exclusiveMode ) return SQLITE_OK;
  34044. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  34045. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  34046. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  34047. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  34048. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  34049. return rc;
  34050. }
  34051. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  34052. if( pWal->exclusiveMode ) return;
  34053. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  34054. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  34055. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  34056. walLockName(lockIdx), n));
  34057. }
  34058. /*
  34059. ** Compute a hash on a page number. The resulting hash value must land
  34060. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  34061. ** the hash to the next value in the event of a collision.
  34062. */
  34063. static int walHash(u32 iPage){
  34064. assert( iPage>0 );
  34065. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  34066. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  34067. }
  34068. static int walNextHash(int iPriorHash){
  34069. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  34070. }
  34071. /*
  34072. ** Return pointers to the hash table and page number array stored on
  34073. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  34074. ** numbered starting from 0.
  34075. **
  34076. ** Set output variable *paHash to point to the start of the hash table
  34077. ** in the wal-index file. Set *piZero to one less than the frame
  34078. ** number of the first frame indexed by this hash table. If a
  34079. ** slot in the hash table is set to N, it refers to frame number
  34080. ** (*piZero+N) in the log.
  34081. **
  34082. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  34083. ** first frame indexed by the hash table, frame (*piZero+1).
  34084. */
  34085. static int walHashGet(
  34086. Wal *pWal, /* WAL handle */
  34087. int iHash, /* Find the iHash'th table */
  34088. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  34089. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  34090. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  34091. ){
  34092. int rc; /* Return code */
  34093. volatile u32 *aPgno;
  34094. rc = walIndexPage(pWal, iHash, &aPgno);
  34095. assert( rc==SQLITE_OK || iHash>0 );
  34096. if( rc==SQLITE_OK ){
  34097. u32 iZero;
  34098. volatile ht_slot *aHash;
  34099. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  34100. if( iHash==0 ){
  34101. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  34102. iZero = 0;
  34103. }else{
  34104. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  34105. }
  34106. *paPgno = &aPgno[-1];
  34107. *paHash = aHash;
  34108. *piZero = iZero;
  34109. }
  34110. return rc;
  34111. }
  34112. /*
  34113. ** Return the number of the wal-index page that contains the hash-table
  34114. ** and page-number array that contain entries corresponding to WAL frame
  34115. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  34116. ** are numbered starting from 0.
  34117. */
  34118. static int walFramePage(u32 iFrame){
  34119. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  34120. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  34121. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  34122. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  34123. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  34124. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  34125. );
  34126. return iHash;
  34127. }
  34128. /*
  34129. ** Return the page number associated with frame iFrame in this WAL.
  34130. */
  34131. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  34132. int iHash = walFramePage(iFrame);
  34133. if( iHash==0 ){
  34134. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  34135. }
  34136. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  34137. }
  34138. /*
  34139. ** Remove entries from the hash table that point to WAL slots greater
  34140. ** than pWal->hdr.mxFrame.
  34141. **
  34142. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  34143. ** to a rollback or savepoint.
  34144. **
  34145. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  34146. ** updated. Any later hash tables will be automatically cleared when
  34147. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  34148. ** actually needed.
  34149. */
  34150. static void walCleanupHash(Wal *pWal){
  34151. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  34152. volatile u32 *aPgno = 0; /* Page number array for hash table */
  34153. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  34154. int iLimit = 0; /* Zero values greater than this */
  34155. int nByte; /* Number of bytes to zero in aPgno[] */
  34156. int i; /* Used to iterate through aHash[] */
  34157. assert( pWal->writeLock );
  34158. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  34159. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  34160. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  34161. if( pWal->hdr.mxFrame==0 ) return;
  34162. /* Obtain pointers to the hash-table and page-number array containing
  34163. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  34164. ** that the page said hash-table and array reside on is already mapped.
  34165. */
  34166. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  34167. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  34168. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  34169. /* Zero all hash-table entries that correspond to frame numbers greater
  34170. ** than pWal->hdr.mxFrame.
  34171. */
  34172. iLimit = pWal->hdr.mxFrame - iZero;
  34173. assert( iLimit>0 );
  34174. for(i=0; i<HASHTABLE_NSLOT; i++){
  34175. if( aHash[i]>iLimit ){
  34176. aHash[i] = 0;
  34177. }
  34178. }
  34179. /* Zero the entries in the aPgno array that correspond to frames with
  34180. ** frame numbers greater than pWal->hdr.mxFrame.
  34181. */
  34182. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  34183. memset((void *)&aPgno[iLimit+1], 0, nByte);
  34184. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  34185. /* Verify that the every entry in the mapping region is still reachable
  34186. ** via the hash table even after the cleanup.
  34187. */
  34188. if( iLimit ){
  34189. int i; /* Loop counter */
  34190. int iKey; /* Hash key */
  34191. for(i=1; i<=iLimit; i++){
  34192. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  34193. if( aHash[iKey]==i ) break;
  34194. }
  34195. assert( aHash[iKey]==i );
  34196. }
  34197. }
  34198. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  34199. }
  34200. /*
  34201. ** Set an entry in the wal-index that will map database page number
  34202. ** pPage into WAL frame iFrame.
  34203. */
  34204. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  34205. int rc; /* Return code */
  34206. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  34207. volatile u32 *aPgno = 0; /* Page number array */
  34208. volatile ht_slot *aHash = 0; /* Hash table */
  34209. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  34210. /* Assuming the wal-index file was successfully mapped, populate the
  34211. ** page number array and hash table entry.
  34212. */
  34213. if( rc==SQLITE_OK ){
  34214. int iKey; /* Hash table key */
  34215. int idx; /* Value to write to hash-table slot */
  34216. int nCollide; /* Number of hash collisions */
  34217. idx = iFrame - iZero;
  34218. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  34219. /* If this is the first entry to be added to this hash-table, zero the
  34220. ** entire hash table and aPgno[] array before proceding.
  34221. */
  34222. if( idx==1 ){
  34223. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  34224. memset((void*)&aPgno[1], 0, nByte);
  34225. }
  34226. /* If the entry in aPgno[] is already set, then the previous writer
  34227. ** must have exited unexpectedly in the middle of a transaction (after
  34228. ** writing one or more dirty pages to the WAL to free up memory).
  34229. ** Remove the remnants of that writers uncommitted transaction from
  34230. ** the hash-table before writing any new entries.
  34231. */
  34232. if( aPgno[idx] ){
  34233. walCleanupHash(pWal);
  34234. assert( !aPgno[idx] );
  34235. }
  34236. /* Write the aPgno[] array entry and the hash-table slot. */
  34237. nCollide = idx;
  34238. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  34239. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  34240. }
  34241. aPgno[idx] = iPage;
  34242. aHash[iKey] = (ht_slot)idx;
  34243. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  34244. /* Verify that the number of entries in the hash table exactly equals
  34245. ** the number of entries in the mapping region.
  34246. */
  34247. {
  34248. int i; /* Loop counter */
  34249. int nEntry = 0; /* Number of entries in the hash table */
  34250. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  34251. assert( nEntry==idx );
  34252. }
  34253. /* Verify that the every entry in the mapping region is reachable
  34254. ** via the hash table. This turns out to be a really, really expensive
  34255. ** thing to check, so only do this occasionally - not on every
  34256. ** iteration.
  34257. */
  34258. if( (idx&0x3ff)==0 ){
  34259. int i; /* Loop counter */
  34260. for(i=1; i<=idx; i++){
  34261. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  34262. if( aHash[iKey]==i ) break;
  34263. }
  34264. assert( aHash[iKey]==i );
  34265. }
  34266. }
  34267. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  34268. }
  34269. return rc;
  34270. }
  34271. /*
  34272. ** Recover the wal-index by reading the write-ahead log file.
  34273. **
  34274. ** This routine first tries to establish an exclusive lock on the
  34275. ** wal-index to prevent other threads/processes from doing anything
  34276. ** with the WAL or wal-index while recovery is running. The
  34277. ** WAL_RECOVER_LOCK is also held so that other threads will know
  34278. ** that this thread is running recovery. If unable to establish
  34279. ** the necessary locks, this routine returns SQLITE_BUSY.
  34280. */
  34281. static int walIndexRecover(Wal *pWal){
  34282. int rc; /* Return Code */
  34283. i64 nSize; /* Size of log file */
  34284. u32 aFrameCksum[2] = {0, 0};
  34285. int iLock; /* Lock offset to lock for checkpoint */
  34286. int nLock; /* Number of locks to hold */
  34287. /* Obtain an exclusive lock on all byte in the locking range not already
  34288. ** locked by the caller. The caller is guaranteed to have locked the
  34289. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  34290. ** If successful, the same bytes that are locked here are unlocked before
  34291. ** this function returns.
  34292. */
  34293. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  34294. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  34295. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  34296. assert( pWal->writeLock );
  34297. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  34298. nLock = SQLITE_SHM_NLOCK - iLock;
  34299. rc = walLockExclusive(pWal, iLock, nLock);
  34300. if( rc ){
  34301. return rc;
  34302. }
  34303. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  34304. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  34305. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  34306. if( rc!=SQLITE_OK ){
  34307. goto recovery_error;
  34308. }
  34309. if( nSize>WAL_HDRSIZE ){
  34310. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  34311. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  34312. int szFrame; /* Number of bytes in buffer aFrame[] */
  34313. u8 *aData; /* Pointer to data part of aFrame buffer */
  34314. int iFrame; /* Index of last frame read */
  34315. i64 iOffset; /* Next offset to read from log file */
  34316. int szPage; /* Page size according to the log */
  34317. u32 magic; /* Magic value read from WAL header */
  34318. u32 version; /* Magic value read from WAL header */
  34319. int isValid; /* True if this frame is valid */
  34320. /* Read in the WAL header. */
  34321. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  34322. if( rc!=SQLITE_OK ){
  34323. goto recovery_error;
  34324. }
  34325. /* If the database page size is not a power of two, or is greater than
  34326. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  34327. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  34328. ** WAL file.
  34329. */
  34330. magic = sqlite3Get4byte(&aBuf[0]);
  34331. szPage = sqlite3Get4byte(&aBuf[8]);
  34332. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  34333. || szPage&(szPage-1)
  34334. || szPage>SQLITE_MAX_PAGE_SIZE
  34335. || szPage<512
  34336. ){
  34337. goto finished;
  34338. }
  34339. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  34340. pWal->szPage = szPage;
  34341. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  34342. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  34343. /* Verify that the WAL header checksum is correct */
  34344. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  34345. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  34346. );
  34347. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  34348. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  34349. ){
  34350. goto finished;
  34351. }
  34352. /* Verify that the version number on the WAL format is one that
  34353. ** are able to understand */
  34354. version = sqlite3Get4byte(&aBuf[4]);
  34355. if( version!=WAL_MAX_VERSION ){
  34356. rc = SQLITE_CANTOPEN_BKPT;
  34357. goto finished;
  34358. }
  34359. /* Malloc a buffer to read frames into. */
  34360. szFrame = szPage + WAL_FRAME_HDRSIZE;
  34361. aFrame = (u8 *)sqlite3_malloc(szFrame);
  34362. if( !aFrame ){
  34363. rc = SQLITE_NOMEM;
  34364. goto recovery_error;
  34365. }
  34366. aData = &aFrame[WAL_FRAME_HDRSIZE];
  34367. /* Read all frames from the log file. */
  34368. iFrame = 0;
  34369. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  34370. u32 pgno; /* Database page number for frame */
  34371. u32 nTruncate; /* dbsize field from frame header */
  34372. /* Read and decode the next log frame. */
  34373. iFrame++;
  34374. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  34375. if( rc!=SQLITE_OK ) break;
  34376. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  34377. if( !isValid ) break;
  34378. rc = walIndexAppend(pWal, iFrame, pgno);
  34379. if( rc!=SQLITE_OK ) break;
  34380. /* If nTruncate is non-zero, this is a commit record. */
  34381. if( nTruncate ){
  34382. pWal->hdr.mxFrame = iFrame;
  34383. pWal->hdr.nPage = nTruncate;
  34384. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  34385. testcase( szPage<=32768 );
  34386. testcase( szPage>=65536 );
  34387. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  34388. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  34389. }
  34390. }
  34391. sqlite3_free(aFrame);
  34392. }
  34393. finished:
  34394. if( rc==SQLITE_OK ){
  34395. volatile WalCkptInfo *pInfo;
  34396. int i;
  34397. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  34398. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  34399. walIndexWriteHdr(pWal);
  34400. /* Reset the checkpoint-header. This is safe because this thread is
  34401. ** currently holding locks that exclude all other readers, writers and
  34402. ** checkpointers.
  34403. */
  34404. pInfo = walCkptInfo(pWal);
  34405. pInfo->nBackfill = 0;
  34406. pInfo->aReadMark[0] = 0;
  34407. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  34408. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  34409. /* If more than one frame was recovered from the log file, report an
  34410. ** event via sqlite3_log(). This is to help with identifying performance
  34411. ** problems caused by applications routinely shutting down without
  34412. ** checkpointing the log file.
  34413. */
  34414. if( pWal->hdr.nPage ){
  34415. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  34416. "recovered %d frames from WAL file %s",
  34417. pWal->hdr.mxFrame, pWal->zWalName
  34418. );
  34419. }
  34420. }
  34421. recovery_error:
  34422. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  34423. walUnlockExclusive(pWal, iLock, nLock);
  34424. return rc;
  34425. }
  34426. /*
  34427. ** Close an open wal-index.
  34428. */
  34429. static void walIndexClose(Wal *pWal, int isDelete){
  34430. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  34431. int i;
  34432. for(i=0; i<pWal->nWiData; i++){
  34433. sqlite3_free((void *)pWal->apWiData[i]);
  34434. pWal->apWiData[i] = 0;
  34435. }
  34436. }else{
  34437. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  34438. }
  34439. }
  34440. /*
  34441. ** Open a connection to the WAL file zWalName. The database file must
  34442. ** already be opened on connection pDbFd. The buffer that zWalName points
  34443. ** to must remain valid for the lifetime of the returned Wal* handle.
  34444. **
  34445. ** A SHARED lock should be held on the database file when this function
  34446. ** is called. The purpose of this SHARED lock is to prevent any other
  34447. ** client from unlinking the WAL or wal-index file. If another process
  34448. ** were to do this just after this client opened one of these files, the
  34449. ** system would be badly broken.
  34450. **
  34451. ** If the log file is successfully opened, SQLITE_OK is returned and
  34452. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  34453. ** an SQLite error code is returned and *ppWal is left unmodified.
  34454. */
  34455. SQLITE_PRIVATE int sqlite3WalOpen(
  34456. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  34457. sqlite3_file *pDbFd, /* The open database file */
  34458. const char *zWalName, /* Name of the WAL file */
  34459. int bNoShm, /* True to run in heap-memory mode */
  34460. i64 mxWalSize, /* Truncate WAL to this size on reset */
  34461. Wal **ppWal /* OUT: Allocated Wal handle */
  34462. ){
  34463. int rc; /* Return Code */
  34464. Wal *pRet; /* Object to allocate and return */
  34465. int flags; /* Flags passed to OsOpen() */
  34466. assert( zWalName && zWalName[0] );
  34467. assert( pDbFd );
  34468. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  34469. ** this source file. Verify that the #defines of the locking byte offsets
  34470. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  34471. */
  34472. #ifdef WIN_SHM_BASE
  34473. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  34474. #endif
  34475. #ifdef UNIX_SHM_BASE
  34476. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  34477. #endif
  34478. /* Allocate an instance of struct Wal to return. */
  34479. *ppWal = 0;
  34480. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  34481. if( !pRet ){
  34482. return SQLITE_NOMEM;
  34483. }
  34484. pRet->pVfs = pVfs;
  34485. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  34486. pRet->pDbFd = pDbFd;
  34487. pRet->readLock = -1;
  34488. pRet->mxWalSize = mxWalSize;
  34489. pRet->zWalName = zWalName;
  34490. pRet->syncHeader = 1;
  34491. pRet->padToSectorBoundary = 1;
  34492. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  34493. /* Open file handle on the write-ahead log file. */
  34494. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  34495. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  34496. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  34497. pRet->readOnly = WAL_RDONLY;
  34498. }
  34499. if( rc!=SQLITE_OK ){
  34500. walIndexClose(pRet, 0);
  34501. sqlite3OsClose(pRet->pWalFd);
  34502. sqlite3_free(pRet);
  34503. }else{
  34504. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  34505. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  34506. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  34507. pRet->padToSectorBoundary = 0;
  34508. }
  34509. *ppWal = pRet;
  34510. WALTRACE(("WAL%d: opened\n", pRet));
  34511. }
  34512. return rc;
  34513. }
  34514. /*
  34515. ** Change the size to which the WAL file is trucated on each reset.
  34516. */
  34517. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  34518. if( pWal ) pWal->mxWalSize = iLimit;
  34519. }
  34520. /*
  34521. ** Find the smallest page number out of all pages held in the WAL that
  34522. ** has not been returned by any prior invocation of this method on the
  34523. ** same WalIterator object. Write into *piFrame the frame index where
  34524. ** that page was last written into the WAL. Write into *piPage the page
  34525. ** number.
  34526. **
  34527. ** Return 0 on success. If there are no pages in the WAL with a page
  34528. ** number larger than *piPage, then return 1.
  34529. */
  34530. static int walIteratorNext(
  34531. WalIterator *p, /* Iterator */
  34532. u32 *piPage, /* OUT: The page number of the next page */
  34533. u32 *piFrame /* OUT: Wal frame index of next page */
  34534. ){
  34535. u32 iMin; /* Result pgno must be greater than iMin */
  34536. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  34537. int i; /* For looping through segments */
  34538. iMin = p->iPrior;
  34539. assert( iMin<0xffffffff );
  34540. for(i=p->nSegment-1; i>=0; i--){
  34541. struct WalSegment *pSegment = &p->aSegment[i];
  34542. while( pSegment->iNext<pSegment->nEntry ){
  34543. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  34544. if( iPg>iMin ){
  34545. if( iPg<iRet ){
  34546. iRet = iPg;
  34547. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  34548. }
  34549. break;
  34550. }
  34551. pSegment->iNext++;
  34552. }
  34553. }
  34554. *piPage = p->iPrior = iRet;
  34555. return (iRet==0xFFFFFFFF);
  34556. }
  34557. /*
  34558. ** This function merges two sorted lists into a single sorted list.
  34559. **
  34560. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  34561. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  34562. ** is guaranteed for all J<K:
  34563. **
  34564. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  34565. ** aContent[aRight[J]] < aContent[aRight[K]]
  34566. **
  34567. ** This routine overwrites aRight[] with a new (probably longer) sequence
  34568. ** of indices such that the aRight[] contains every index that appears in
  34569. ** either aLeft[] or the old aRight[] and such that the second condition
  34570. ** above is still met.
  34571. **
  34572. ** The aContent[aLeft[X]] values will be unique for all X. And the
  34573. ** aContent[aRight[X]] values will be unique too. But there might be
  34574. ** one or more combinations of X and Y such that
  34575. **
  34576. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  34577. **
  34578. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  34579. */
  34580. static void walMerge(
  34581. const u32 *aContent, /* Pages in wal - keys for the sort */
  34582. ht_slot *aLeft, /* IN: Left hand input list */
  34583. int nLeft, /* IN: Elements in array *paLeft */
  34584. ht_slot **paRight, /* IN/OUT: Right hand input list */
  34585. int *pnRight, /* IN/OUT: Elements in *paRight */
  34586. ht_slot *aTmp /* Temporary buffer */
  34587. ){
  34588. int iLeft = 0; /* Current index in aLeft */
  34589. int iRight = 0; /* Current index in aRight */
  34590. int iOut = 0; /* Current index in output buffer */
  34591. int nRight = *pnRight;
  34592. ht_slot *aRight = *paRight;
  34593. assert( nLeft>0 && nRight>0 );
  34594. while( iRight<nRight || iLeft<nLeft ){
  34595. ht_slot logpage;
  34596. Pgno dbpage;
  34597. if( (iLeft<nLeft)
  34598. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  34599. ){
  34600. logpage = aLeft[iLeft++];
  34601. }else{
  34602. logpage = aRight[iRight++];
  34603. }
  34604. dbpage = aContent[logpage];
  34605. aTmp[iOut++] = logpage;
  34606. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  34607. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  34608. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  34609. }
  34610. *paRight = aLeft;
  34611. *pnRight = iOut;
  34612. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  34613. }
  34614. /*
  34615. ** Sort the elements in list aList using aContent[] as the sort key.
  34616. ** Remove elements with duplicate keys, preferring to keep the
  34617. ** larger aList[] values.
  34618. **
  34619. ** The aList[] entries are indices into aContent[]. The values in
  34620. ** aList[] are to be sorted so that for all J<K:
  34621. **
  34622. ** aContent[aList[J]] < aContent[aList[K]]
  34623. **
  34624. ** For any X and Y such that
  34625. **
  34626. ** aContent[aList[X]] == aContent[aList[Y]]
  34627. **
  34628. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  34629. ** the smaller.
  34630. */
  34631. static void walMergesort(
  34632. const u32 *aContent, /* Pages in wal */
  34633. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  34634. ht_slot *aList, /* IN/OUT: List to sort */
  34635. int *pnList /* IN/OUT: Number of elements in aList[] */
  34636. ){
  34637. struct Sublist {
  34638. int nList; /* Number of elements in aList */
  34639. ht_slot *aList; /* Pointer to sub-list content */
  34640. };
  34641. const int nList = *pnList; /* Size of input list */
  34642. int nMerge = 0; /* Number of elements in list aMerge */
  34643. ht_slot *aMerge = 0; /* List to be merged */
  34644. int iList; /* Index into input list */
  34645. int iSub = 0; /* Index into aSub array */
  34646. struct Sublist aSub[13]; /* Array of sub-lists */
  34647. memset(aSub, 0, sizeof(aSub));
  34648. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  34649. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  34650. for(iList=0; iList<nList; iList++){
  34651. nMerge = 1;
  34652. aMerge = &aList[iList];
  34653. for(iSub=0; iList & (1<<iSub); iSub++){
  34654. struct Sublist *p = &aSub[iSub];
  34655. assert( p->aList && p->nList<=(1<<iSub) );
  34656. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  34657. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  34658. }
  34659. aSub[iSub].aList = aMerge;
  34660. aSub[iSub].nList = nMerge;
  34661. }
  34662. for(iSub++; iSub<ArraySize(aSub); iSub++){
  34663. if( nList & (1<<iSub) ){
  34664. struct Sublist *p = &aSub[iSub];
  34665. assert( p->nList<=(1<<iSub) );
  34666. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  34667. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  34668. }
  34669. }
  34670. assert( aMerge==aList );
  34671. *pnList = nMerge;
  34672. #ifdef SQLITE_DEBUG
  34673. {
  34674. int i;
  34675. for(i=1; i<*pnList; i++){
  34676. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  34677. }
  34678. }
  34679. #endif
  34680. }
  34681. /*
  34682. ** Free an iterator allocated by walIteratorInit().
  34683. */
  34684. static void walIteratorFree(WalIterator *p){
  34685. sqlite3ScratchFree(p);
  34686. }
  34687. /*
  34688. ** Construct a WalInterator object that can be used to loop over all
  34689. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  34690. ** lock.
  34691. **
  34692. ** On success, make *pp point to the newly allocated WalInterator object
  34693. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  34694. ** returns an error, the value of *pp is undefined.
  34695. **
  34696. ** The calling routine should invoke walIteratorFree() to destroy the
  34697. ** WalIterator object when it has finished with it.
  34698. */
  34699. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  34700. WalIterator *p; /* Return value */
  34701. int nSegment; /* Number of segments to merge */
  34702. u32 iLast; /* Last frame in log */
  34703. int nByte; /* Number of bytes to allocate */
  34704. int i; /* Iterator variable */
  34705. ht_slot *aTmp; /* Temp space used by merge-sort */
  34706. int rc = SQLITE_OK; /* Return Code */
  34707. /* This routine only runs while holding the checkpoint lock. And
  34708. ** it only runs if there is actually content in the log (mxFrame>0).
  34709. */
  34710. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  34711. iLast = pWal->hdr.mxFrame;
  34712. /* Allocate space for the WalIterator object. */
  34713. nSegment = walFramePage(iLast) + 1;
  34714. nByte = sizeof(WalIterator)
  34715. + (nSegment-1)*sizeof(struct WalSegment)
  34716. + iLast*sizeof(ht_slot);
  34717. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  34718. if( !p ){
  34719. return SQLITE_NOMEM;
  34720. }
  34721. memset(p, 0, nByte);
  34722. p->nSegment = nSegment;
  34723. /* Allocate temporary space used by the merge-sort routine. This block
  34724. ** of memory will be freed before this function returns.
  34725. */
  34726. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  34727. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  34728. );
  34729. if( !aTmp ){
  34730. rc = SQLITE_NOMEM;
  34731. }
  34732. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  34733. volatile ht_slot *aHash;
  34734. u32 iZero;
  34735. volatile u32 *aPgno;
  34736. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  34737. if( rc==SQLITE_OK ){
  34738. int j; /* Counter variable */
  34739. int nEntry; /* Number of entries in this segment */
  34740. ht_slot *aIndex; /* Sorted index for this segment */
  34741. aPgno++;
  34742. if( (i+1)==nSegment ){
  34743. nEntry = (int)(iLast - iZero);
  34744. }else{
  34745. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  34746. }
  34747. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  34748. iZero++;
  34749. for(j=0; j<nEntry; j++){
  34750. aIndex[j] = (ht_slot)j;
  34751. }
  34752. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  34753. p->aSegment[i].iZero = iZero;
  34754. p->aSegment[i].nEntry = nEntry;
  34755. p->aSegment[i].aIndex = aIndex;
  34756. p->aSegment[i].aPgno = (u32 *)aPgno;
  34757. }
  34758. }
  34759. sqlite3ScratchFree(aTmp);
  34760. if( rc!=SQLITE_OK ){
  34761. walIteratorFree(p);
  34762. }
  34763. *pp = p;
  34764. return rc;
  34765. }
  34766. /*
  34767. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  34768. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  34769. ** busy-handler function. Invoke it and retry the lock until either the
  34770. ** lock is successfully obtained or the busy-handler returns 0.
  34771. */
  34772. static int walBusyLock(
  34773. Wal *pWal, /* WAL connection */
  34774. int (*xBusy)(void*), /* Function to call when busy */
  34775. void *pBusyArg, /* Context argument for xBusyHandler */
  34776. int lockIdx, /* Offset of first byte to lock */
  34777. int n /* Number of bytes to lock */
  34778. ){
  34779. int rc;
  34780. do {
  34781. rc = walLockExclusive(pWal, lockIdx, n);
  34782. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  34783. return rc;
  34784. }
  34785. /*
  34786. ** The cache of the wal-index header must be valid to call this function.
  34787. ** Return the page-size in bytes used by the database.
  34788. */
  34789. static int walPagesize(Wal *pWal){
  34790. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  34791. }
  34792. /*
  34793. ** Copy as much content as we can from the WAL back into the database file
  34794. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  34795. **
  34796. ** The amount of information copies from WAL to database might be limited
  34797. ** by active readers. This routine will never overwrite a database page
  34798. ** that a concurrent reader might be using.
  34799. **
  34800. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  34801. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  34802. ** checkpoints are always run by a background thread or background
  34803. ** process, foreground threads will never block on a lengthy fsync call.
  34804. **
  34805. ** Fsync is called on the WAL before writing content out of the WAL and
  34806. ** into the database. This ensures that if the new content is persistent
  34807. ** in the WAL and can be recovered following a power-loss or hard reset.
  34808. **
  34809. ** Fsync is also called on the database file if (and only if) the entire
  34810. ** WAL content is copied into the database file. This second fsync makes
  34811. ** it safe to delete the WAL since the new content will persist in the
  34812. ** database file.
  34813. **
  34814. ** This routine uses and updates the nBackfill field of the wal-index header.
  34815. ** This is the only routine tha will increase the value of nBackfill.
  34816. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  34817. ** its value.)
  34818. **
  34819. ** The caller must be holding sufficient locks to ensure that no other
  34820. ** checkpoint is running (in any other thread or process) at the same
  34821. ** time.
  34822. */
  34823. static int walCheckpoint(
  34824. Wal *pWal, /* Wal connection */
  34825. int eMode, /* One of PASSIVE, FULL or RESTART */
  34826. int (*xBusyCall)(void*), /* Function to call when busy */
  34827. void *pBusyArg, /* Context argument for xBusyHandler */
  34828. int sync_flags, /* Flags for OsSync() (or 0) */
  34829. u8 *zBuf /* Temporary buffer to use */
  34830. ){
  34831. int rc; /* Return code */
  34832. int szPage; /* Database page-size */
  34833. WalIterator *pIter = 0; /* Wal iterator context */
  34834. u32 iDbpage = 0; /* Next database page to write */
  34835. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  34836. u32 mxSafeFrame; /* Max frame that can be backfilled */
  34837. u32 mxPage; /* Max database page to write */
  34838. int i; /* Loop counter */
  34839. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  34840. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  34841. szPage = walPagesize(pWal);
  34842. testcase( szPage<=32768 );
  34843. testcase( szPage>=65536 );
  34844. pInfo = walCkptInfo(pWal);
  34845. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  34846. /* Allocate the iterator */
  34847. rc = walIteratorInit(pWal, &pIter);
  34848. if( rc!=SQLITE_OK ){
  34849. return rc;
  34850. }
  34851. assert( pIter );
  34852. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  34853. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  34854. ** safe to write into the database. Frames beyond mxSafeFrame might
  34855. ** overwrite database pages that are in use by active readers and thus
  34856. ** cannot be backfilled from the WAL.
  34857. */
  34858. mxSafeFrame = pWal->hdr.mxFrame;
  34859. mxPage = pWal->hdr.nPage;
  34860. for(i=1; i<WAL_NREADER; i++){
  34861. u32 y = pInfo->aReadMark[i];
  34862. if( mxSafeFrame>y ){
  34863. assert( y<=pWal->hdr.mxFrame );
  34864. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  34865. if( rc==SQLITE_OK ){
  34866. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  34867. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  34868. }else if( rc==SQLITE_BUSY ){
  34869. mxSafeFrame = y;
  34870. xBusy = 0;
  34871. }else{
  34872. goto walcheckpoint_out;
  34873. }
  34874. }
  34875. }
  34876. if( pInfo->nBackfill<mxSafeFrame
  34877. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  34878. ){
  34879. i64 nSize; /* Current size of database file */
  34880. u32 nBackfill = pInfo->nBackfill;
  34881. /* Sync the WAL to disk */
  34882. if( sync_flags ){
  34883. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  34884. }
  34885. /* If the database may grow as a result of this checkpoint, hint
  34886. ** about the eventual size of the db file to the VFS layer.
  34887. */
  34888. if( rc==SQLITE_OK ){
  34889. i64 nReq = ((i64)mxPage * szPage);
  34890. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  34891. if( rc==SQLITE_OK && nSize<nReq ){
  34892. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  34893. }
  34894. }
  34895. /* Iterate through the contents of the WAL, copying data to the db file. */
  34896. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  34897. i64 iOffset;
  34898. assert( walFramePgno(pWal, iFrame)==iDbpage );
  34899. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  34900. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  34901. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  34902. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  34903. if( rc!=SQLITE_OK ) break;
  34904. iOffset = (iDbpage-1)*(i64)szPage;
  34905. testcase( IS_BIG_INT(iOffset) );
  34906. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  34907. if( rc!=SQLITE_OK ) break;
  34908. }
  34909. /* If work was actually accomplished... */
  34910. if( rc==SQLITE_OK ){
  34911. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  34912. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  34913. testcase( IS_BIG_INT(szDb) );
  34914. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  34915. if( rc==SQLITE_OK && sync_flags ){
  34916. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  34917. }
  34918. }
  34919. if( rc==SQLITE_OK ){
  34920. pInfo->nBackfill = mxSafeFrame;
  34921. }
  34922. }
  34923. /* Release the reader lock held while backfilling */
  34924. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  34925. }
  34926. if( rc==SQLITE_BUSY ){
  34927. /* Reset the return code so as not to report a checkpoint failure
  34928. ** just because there are active readers. */
  34929. rc = SQLITE_OK;
  34930. }
  34931. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  34932. ** file has been copied into the database file, then block until all
  34933. ** readers have finished using the wal file. This ensures that the next
  34934. ** process to write to the database restarts the wal file.
  34935. */
  34936. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  34937. assert( pWal->writeLock );
  34938. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  34939. rc = SQLITE_BUSY;
  34940. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  34941. assert( mxSafeFrame==pWal->hdr.mxFrame );
  34942. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  34943. if( rc==SQLITE_OK ){
  34944. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  34945. }
  34946. }
  34947. }
  34948. walcheckpoint_out:
  34949. walIteratorFree(pIter);
  34950. return rc;
  34951. }
  34952. /*
  34953. ** If the WAL file is currently larger than nMax bytes in size, truncate
  34954. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  34955. */
  34956. static void walLimitSize(Wal *pWal, i64 nMax){
  34957. i64 sz;
  34958. int rx;
  34959. sqlite3BeginBenignMalloc();
  34960. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  34961. if( rx==SQLITE_OK && (sz > nMax ) ){
  34962. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  34963. }
  34964. sqlite3EndBenignMalloc();
  34965. if( rx ){
  34966. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  34967. }
  34968. }
  34969. /*
  34970. ** Close a connection to a log file.
  34971. */
  34972. SQLITE_PRIVATE int sqlite3WalClose(
  34973. Wal *pWal, /* Wal to close */
  34974. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  34975. int nBuf,
  34976. u8 *zBuf /* Buffer of at least nBuf bytes */
  34977. ){
  34978. int rc = SQLITE_OK;
  34979. if( pWal ){
  34980. int isDelete = 0; /* True to unlink wal and wal-index files */
  34981. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  34982. ** ordinary, rollback-mode locking methods, this guarantees that the
  34983. ** connection associated with this log file is the only connection to
  34984. ** the database. In this case checkpoint the database and unlink both
  34985. ** the wal and wal-index files.
  34986. **
  34987. ** The EXCLUSIVE lock is not released before returning.
  34988. */
  34989. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  34990. if( rc==SQLITE_OK ){
  34991. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  34992. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  34993. }
  34994. rc = sqlite3WalCheckpoint(
  34995. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  34996. );
  34997. if( rc==SQLITE_OK ){
  34998. int bPersist = -1;
  34999. sqlite3OsFileControlHint(
  35000. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  35001. );
  35002. if( bPersist!=1 ){
  35003. /* Try to delete the WAL file if the checkpoint completed and
  35004. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  35005. ** mode (!bPersist) */
  35006. isDelete = 1;
  35007. }else if( pWal->mxWalSize>=0 ){
  35008. /* Try to truncate the WAL file to zero bytes if the checkpoint
  35009. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  35010. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  35011. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  35012. ** to zero bytes as truncating to the journal_size_limit might
  35013. ** leave a corrupt WAL file on disk. */
  35014. walLimitSize(pWal, 0);
  35015. }
  35016. }
  35017. }
  35018. walIndexClose(pWal, isDelete);
  35019. sqlite3OsClose(pWal->pWalFd);
  35020. if( isDelete ){
  35021. sqlite3BeginBenignMalloc();
  35022. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  35023. sqlite3EndBenignMalloc();
  35024. }
  35025. WALTRACE(("WAL%p: closed\n", pWal));
  35026. sqlite3_free((void *)pWal->apWiData);
  35027. sqlite3_free(pWal);
  35028. }
  35029. return rc;
  35030. }
  35031. /*
  35032. ** Try to read the wal-index header. Return 0 on success and 1 if
  35033. ** there is a problem.
  35034. **
  35035. ** The wal-index is in shared memory. Another thread or process might
  35036. ** be writing the header at the same time this procedure is trying to
  35037. ** read it, which might result in inconsistency. A dirty read is detected
  35038. ** by verifying that both copies of the header are the same and also by
  35039. ** a checksum on the header.
  35040. **
  35041. ** If and only if the read is consistent and the header is different from
  35042. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  35043. ** and *pChanged is set to 1.
  35044. **
  35045. ** If the checksum cannot be verified return non-zero. If the header
  35046. ** is read successfully and the checksum verified, return zero.
  35047. */
  35048. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  35049. u32 aCksum[2]; /* Checksum on the header content */
  35050. WalIndexHdr h1, h2; /* Two copies of the header content */
  35051. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  35052. /* The first page of the wal-index must be mapped at this point. */
  35053. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  35054. /* Read the header. This might happen concurrently with a write to the
  35055. ** same area of shared memory on a different CPU in a SMP,
  35056. ** meaning it is possible that an inconsistent snapshot is read
  35057. ** from the file. If this happens, return non-zero.
  35058. **
  35059. ** There are two copies of the header at the beginning of the wal-index.
  35060. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  35061. ** Memory barriers are used to prevent the compiler or the hardware from
  35062. ** reordering the reads and writes.
  35063. */
  35064. aHdr = walIndexHdr(pWal);
  35065. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  35066. walShmBarrier(pWal);
  35067. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  35068. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  35069. return 1; /* Dirty read */
  35070. }
  35071. if( h1.isInit==0 ){
  35072. return 1; /* Malformed header - probably all zeros */
  35073. }
  35074. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  35075. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  35076. return 1; /* Checksum does not match */
  35077. }
  35078. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  35079. *pChanged = 1;
  35080. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  35081. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  35082. testcase( pWal->szPage<=32768 );
  35083. testcase( pWal->szPage>=65536 );
  35084. }
  35085. /* The header was successfully read. Return zero. */
  35086. return 0;
  35087. }
  35088. /*
  35089. ** Read the wal-index header from the wal-index and into pWal->hdr.
  35090. ** If the wal-header appears to be corrupt, try to reconstruct the
  35091. ** wal-index from the WAL before returning.
  35092. **
  35093. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  35094. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  35095. ** to 0.
  35096. **
  35097. ** If the wal-index header is successfully read, return SQLITE_OK.
  35098. ** Otherwise an SQLite error code.
  35099. */
  35100. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  35101. int rc; /* Return code */
  35102. int badHdr; /* True if a header read failed */
  35103. volatile u32 *page0; /* Chunk of wal-index containing header */
  35104. /* Ensure that page 0 of the wal-index (the page that contains the
  35105. ** wal-index header) is mapped. Return early if an error occurs here.
  35106. */
  35107. assert( pChanged );
  35108. rc = walIndexPage(pWal, 0, &page0);
  35109. if( rc!=SQLITE_OK ){
  35110. return rc;
  35111. };
  35112. assert( page0 || pWal->writeLock==0 );
  35113. /* If the first page of the wal-index has been mapped, try to read the
  35114. ** wal-index header immediately, without holding any lock. This usually
  35115. ** works, but may fail if the wal-index header is corrupt or currently
  35116. ** being modified by another thread or process.
  35117. */
  35118. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  35119. /* If the first attempt failed, it might have been due to a race
  35120. ** with a writer. So get a WRITE lock and try again.
  35121. */
  35122. assert( badHdr==0 || pWal->writeLock==0 );
  35123. if( badHdr ){
  35124. if( pWal->readOnly & WAL_SHM_RDONLY ){
  35125. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  35126. walUnlockShared(pWal, WAL_WRITE_LOCK);
  35127. rc = SQLITE_READONLY_RECOVERY;
  35128. }
  35129. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  35130. pWal->writeLock = 1;
  35131. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  35132. badHdr = walIndexTryHdr(pWal, pChanged);
  35133. if( badHdr ){
  35134. /* If the wal-index header is still malformed even while holding
  35135. ** a WRITE lock, it can only mean that the header is corrupted and
  35136. ** needs to be reconstructed. So run recovery to do exactly that.
  35137. */
  35138. rc = walIndexRecover(pWal);
  35139. *pChanged = 1;
  35140. }
  35141. }
  35142. pWal->writeLock = 0;
  35143. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35144. }
  35145. }
  35146. /* If the header is read successfully, check the version number to make
  35147. ** sure the wal-index was not constructed with some future format that
  35148. ** this version of SQLite cannot understand.
  35149. */
  35150. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  35151. rc = SQLITE_CANTOPEN_BKPT;
  35152. }
  35153. return rc;
  35154. }
  35155. /*
  35156. ** This is the value that walTryBeginRead returns when it needs to
  35157. ** be retried.
  35158. */
  35159. #define WAL_RETRY (-1)
  35160. /*
  35161. ** Attempt to start a read transaction. This might fail due to a race or
  35162. ** other transient condition. When that happens, it returns WAL_RETRY to
  35163. ** indicate to the caller that it is safe to retry immediately.
  35164. **
  35165. ** On success return SQLITE_OK. On a permanent failure (such an
  35166. ** I/O error or an SQLITE_BUSY because another process is running
  35167. ** recovery) return a positive error code.
  35168. **
  35169. ** The useWal parameter is true to force the use of the WAL and disable
  35170. ** the case where the WAL is bypassed because it has been completely
  35171. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  35172. ** to make a copy of the wal-index header into pWal->hdr. If the
  35173. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  35174. ** to the caller that the local paget cache is obsolete and needs to be
  35175. ** flushed.) When useWal==1, the wal-index header is assumed to already
  35176. ** be loaded and the pChanged parameter is unused.
  35177. **
  35178. ** The caller must set the cnt parameter to the number of prior calls to
  35179. ** this routine during the current read attempt that returned WAL_RETRY.
  35180. ** This routine will start taking more aggressive measures to clear the
  35181. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  35182. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  35183. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  35184. ** and is not honoring the locking protocol. There is a vanishingly small
  35185. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  35186. ** bad luck when there is lots of contention for the wal-index, but that
  35187. ** possibility is so small that it can be safely neglected, we believe.
  35188. **
  35189. ** On success, this routine obtains a read lock on
  35190. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  35191. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  35192. ** that means the Wal does not hold any read lock. The reader must not
  35193. ** access any database page that is modified by a WAL frame up to and
  35194. ** including frame number aReadMark[pWal->readLock]. The reader will
  35195. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  35196. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  35197. ** completely and get all content directly from the database file.
  35198. ** If the useWal parameter is 1 then the WAL will never be ignored and
  35199. ** this routine will always set pWal->readLock>0 on success.
  35200. ** When the read transaction is completed, the caller must release the
  35201. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  35202. **
  35203. ** This routine uses the nBackfill and aReadMark[] fields of the header
  35204. ** to select a particular WAL_READ_LOCK() that strives to let the
  35205. ** checkpoint process do as much work as possible. This routine might
  35206. ** update values of the aReadMark[] array in the header, but if it does
  35207. ** so it takes care to hold an exclusive lock on the corresponding
  35208. ** WAL_READ_LOCK() while changing values.
  35209. */
  35210. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  35211. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  35212. u32 mxReadMark; /* Largest aReadMark[] value */
  35213. int mxI; /* Index of largest aReadMark[] value */
  35214. int i; /* Loop counter */
  35215. int rc = SQLITE_OK; /* Return code */
  35216. assert( pWal->readLock<0 ); /* Not currently locked */
  35217. /* Take steps to avoid spinning forever if there is a protocol error.
  35218. **
  35219. ** Circumstances that cause a RETRY should only last for the briefest
  35220. ** instances of time. No I/O or other system calls are done while the
  35221. ** locks are held, so the locks should not be held for very long. But
  35222. ** if we are unlucky, another process that is holding a lock might get
  35223. ** paged out or take a page-fault that is time-consuming to resolve,
  35224. ** during the few nanoseconds that it is holding the lock. In that case,
  35225. ** it might take longer than normal for the lock to free.
  35226. **
  35227. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  35228. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  35229. ** is more of a scheduler yield than an actual delay. But on the 10th
  35230. ** an subsequent retries, the delays start becoming longer and longer,
  35231. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  35232. ** The total delay time before giving up is less than 1 second.
  35233. */
  35234. if( cnt>5 ){
  35235. int nDelay = 1; /* Pause time in microseconds */
  35236. if( cnt>100 ){
  35237. VVA_ONLY( pWal->lockError = 1; )
  35238. return SQLITE_PROTOCOL;
  35239. }
  35240. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  35241. sqlite3OsSleep(pWal->pVfs, nDelay);
  35242. }
  35243. if( !useWal ){
  35244. rc = walIndexReadHdr(pWal, pChanged);
  35245. if( rc==SQLITE_BUSY ){
  35246. /* If there is not a recovery running in another thread or process
  35247. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  35248. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  35249. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  35250. ** would be technically correct. But the race is benign since with
  35251. ** WAL_RETRY this routine will be called again and will probably be
  35252. ** right on the second iteration.
  35253. */
  35254. if( pWal->apWiData[0]==0 ){
  35255. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  35256. ** We assume this is a transient condition, so return WAL_RETRY. The
  35257. ** xShmMap() implementation used by the default unix and win32 VFS
  35258. ** modules may return SQLITE_BUSY due to a race condition in the
  35259. ** code that determines whether or not the shared-memory region
  35260. ** must be zeroed before the requested page is returned.
  35261. */
  35262. rc = WAL_RETRY;
  35263. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  35264. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  35265. rc = WAL_RETRY;
  35266. }else if( rc==SQLITE_BUSY ){
  35267. rc = SQLITE_BUSY_RECOVERY;
  35268. }
  35269. }
  35270. if( rc!=SQLITE_OK ){
  35271. return rc;
  35272. }
  35273. }
  35274. pInfo = walCkptInfo(pWal);
  35275. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  35276. /* The WAL has been completely backfilled (or it is empty).
  35277. ** and can be safely ignored.
  35278. */
  35279. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  35280. walShmBarrier(pWal);
  35281. if( rc==SQLITE_OK ){
  35282. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  35283. /* It is not safe to allow the reader to continue here if frames
  35284. ** may have been appended to the log before READ_LOCK(0) was obtained.
  35285. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  35286. ** which implies that the database file contains a trustworthy
  35287. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  35288. ** happening, this is usually correct.
  35289. **
  35290. ** However, if frames have been appended to the log (or if the log
  35291. ** is wrapped and written for that matter) before the READ_LOCK(0)
  35292. ** is obtained, that is not necessarily true. A checkpointer may
  35293. ** have started to backfill the appended frames but crashed before
  35294. ** it finished. Leaving a corrupt image in the database file.
  35295. */
  35296. walUnlockShared(pWal, WAL_READ_LOCK(0));
  35297. return WAL_RETRY;
  35298. }
  35299. pWal->readLock = 0;
  35300. return SQLITE_OK;
  35301. }else if( rc!=SQLITE_BUSY ){
  35302. return rc;
  35303. }
  35304. }
  35305. /* If we get this far, it means that the reader will want to use
  35306. ** the WAL to get at content from recent commits. The job now is
  35307. ** to select one of the aReadMark[] entries that is closest to
  35308. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  35309. */
  35310. mxReadMark = 0;
  35311. mxI = 0;
  35312. for(i=1; i<WAL_NREADER; i++){
  35313. u32 thisMark = pInfo->aReadMark[i];
  35314. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  35315. assert( thisMark!=READMARK_NOT_USED );
  35316. mxReadMark = thisMark;
  35317. mxI = i;
  35318. }
  35319. }
  35320. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  35321. {
  35322. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  35323. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  35324. ){
  35325. for(i=1; i<WAL_NREADER; i++){
  35326. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  35327. if( rc==SQLITE_OK ){
  35328. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  35329. mxI = i;
  35330. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  35331. break;
  35332. }else if( rc!=SQLITE_BUSY ){
  35333. return rc;
  35334. }
  35335. }
  35336. }
  35337. if( mxI==0 ){
  35338. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  35339. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  35340. }
  35341. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  35342. if( rc ){
  35343. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  35344. }
  35345. /* Now that the read-lock has been obtained, check that neither the
  35346. ** value in the aReadMark[] array or the contents of the wal-index
  35347. ** header have changed.
  35348. **
  35349. ** It is necessary to check that the wal-index header did not change
  35350. ** between the time it was read and when the shared-lock was obtained
  35351. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  35352. ** that the log file may have been wrapped by a writer, or that frames
  35353. ** that occur later in the log than pWal->hdr.mxFrame may have been
  35354. ** copied into the database by a checkpointer. If either of these things
  35355. ** happened, then reading the database with the current value of
  35356. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  35357. ** instead.
  35358. **
  35359. ** This does not guarantee that the copy of the wal-index header is up to
  35360. ** date before proceeding. That would not be possible without somehow
  35361. ** blocking writers. It only guarantees that a dangerous checkpoint or
  35362. ** log-wrap (either of which would require an exclusive lock on
  35363. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  35364. */
  35365. walShmBarrier(pWal);
  35366. if( pInfo->aReadMark[mxI]!=mxReadMark
  35367. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  35368. ){
  35369. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  35370. return WAL_RETRY;
  35371. }else{
  35372. assert( mxReadMark<=pWal->hdr.mxFrame );
  35373. pWal->readLock = (i16)mxI;
  35374. }
  35375. }
  35376. return rc;
  35377. }
  35378. /*
  35379. ** Begin a read transaction on the database.
  35380. **
  35381. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  35382. ** it takes a snapshot of the state of the WAL and wal-index for the current
  35383. ** instant in time. The current thread will continue to use this snapshot.
  35384. ** Other threads might append new content to the WAL and wal-index but
  35385. ** that extra content is ignored by the current thread.
  35386. **
  35387. ** If the database contents have changes since the previous read
  35388. ** transaction, then *pChanged is set to 1 before returning. The
  35389. ** Pager layer will use this to know that is cache is stale and
  35390. ** needs to be flushed.
  35391. */
  35392. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  35393. int rc; /* Return code */
  35394. int cnt = 0; /* Number of TryBeginRead attempts */
  35395. do{
  35396. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  35397. }while( rc==WAL_RETRY );
  35398. testcase( (rc&0xff)==SQLITE_BUSY );
  35399. testcase( (rc&0xff)==SQLITE_IOERR );
  35400. testcase( rc==SQLITE_PROTOCOL );
  35401. testcase( rc==SQLITE_OK );
  35402. return rc;
  35403. }
  35404. /*
  35405. ** Finish with a read transaction. All this does is release the
  35406. ** read-lock.
  35407. */
  35408. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  35409. sqlite3WalEndWriteTransaction(pWal);
  35410. if( pWal->readLock>=0 ){
  35411. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  35412. pWal->readLock = -1;
  35413. }
  35414. }
  35415. /*
  35416. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  35417. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  35418. ** to zero.
  35419. **
  35420. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  35421. ** error does occur, the final value of *piRead is undefined.
  35422. */
  35423. SQLITE_PRIVATE int sqlite3WalFindFrame(
  35424. Wal *pWal, /* WAL handle */
  35425. Pgno pgno, /* Database page number to read data for */
  35426. u32 *piRead /* OUT: Frame number (or zero) */
  35427. ){
  35428. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  35429. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  35430. int iHash; /* Used to loop through N hash tables */
  35431. /* This routine is only be called from within a read transaction. */
  35432. assert( pWal->readLock>=0 || pWal->lockError );
  35433. /* If the "last page" field of the wal-index header snapshot is 0, then
  35434. ** no data will be read from the wal under any circumstances. Return early
  35435. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  35436. ** then the WAL is ignored by the reader so return early, as if the
  35437. ** WAL were empty.
  35438. */
  35439. if( iLast==0 || pWal->readLock==0 ){
  35440. *piRead = 0;
  35441. return SQLITE_OK;
  35442. }
  35443. /* Search the hash table or tables for an entry matching page number
  35444. ** pgno. Each iteration of the following for() loop searches one
  35445. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  35446. **
  35447. ** This code might run concurrently to the code in walIndexAppend()
  35448. ** that adds entries to the wal-index (and possibly to this hash
  35449. ** table). This means the value just read from the hash
  35450. ** slot (aHash[iKey]) may have been added before or after the
  35451. ** current read transaction was opened. Values added after the
  35452. ** read transaction was opened may have been written incorrectly -
  35453. ** i.e. these slots may contain garbage data. However, we assume
  35454. ** that any slots written before the current read transaction was
  35455. ** opened remain unmodified.
  35456. **
  35457. ** For the reasons above, the if(...) condition featured in the inner
  35458. ** loop of the following block is more stringent that would be required
  35459. ** if we had exclusive access to the hash-table:
  35460. **
  35461. ** (aPgno[iFrame]==pgno):
  35462. ** This condition filters out normal hash-table collisions.
  35463. **
  35464. ** (iFrame<=iLast):
  35465. ** This condition filters out entries that were added to the hash
  35466. ** table after the current read-transaction had started.
  35467. */
  35468. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  35469. volatile ht_slot *aHash; /* Pointer to hash table */
  35470. volatile u32 *aPgno; /* Pointer to array of page numbers */
  35471. u32 iZero; /* Frame number corresponding to aPgno[0] */
  35472. int iKey; /* Hash slot index */
  35473. int nCollide; /* Number of hash collisions remaining */
  35474. int rc; /* Error code */
  35475. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  35476. if( rc!=SQLITE_OK ){
  35477. return rc;
  35478. }
  35479. nCollide = HASHTABLE_NSLOT;
  35480. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  35481. u32 iFrame = aHash[iKey] + iZero;
  35482. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  35483. /* assert( iFrame>iRead ); -- not true if there is corruption */
  35484. iRead = iFrame;
  35485. }
  35486. if( (nCollide--)==0 ){
  35487. return SQLITE_CORRUPT_BKPT;
  35488. }
  35489. }
  35490. }
  35491. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  35492. /* If expensive assert() statements are available, do a linear search
  35493. ** of the wal-index file content. Make sure the results agree with the
  35494. ** result obtained using the hash indexes above. */
  35495. {
  35496. u32 iRead2 = 0;
  35497. u32 iTest;
  35498. for(iTest=iLast; iTest>0; iTest--){
  35499. if( walFramePgno(pWal, iTest)==pgno ){
  35500. iRead2 = iTest;
  35501. break;
  35502. }
  35503. }
  35504. assert( iRead==iRead2 );
  35505. }
  35506. #endif
  35507. *piRead = iRead;
  35508. return SQLITE_OK;
  35509. }
  35510. /*
  35511. ** Read the contents of frame iRead from the wal file into buffer pOut
  35512. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  35513. ** error code otherwise.
  35514. */
  35515. SQLITE_PRIVATE int sqlite3WalReadFrame(
  35516. Wal *pWal, /* WAL handle */
  35517. u32 iRead, /* Frame to read */
  35518. int nOut, /* Size of buffer pOut in bytes */
  35519. u8 *pOut /* Buffer to write page data to */
  35520. ){
  35521. int sz;
  35522. i64 iOffset;
  35523. sz = pWal->hdr.szPage;
  35524. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  35525. testcase( sz<=32768 );
  35526. testcase( sz>=65536 );
  35527. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  35528. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  35529. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  35530. }
  35531. /*
  35532. ** Return the size of the database in pages (or zero, if unknown).
  35533. */
  35534. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  35535. if( pWal && ALWAYS(pWal->readLock>=0) ){
  35536. return pWal->hdr.nPage;
  35537. }
  35538. return 0;
  35539. }
  35540. /*
  35541. ** This function starts a write transaction on the WAL.
  35542. **
  35543. ** A read transaction must have already been started by a prior call
  35544. ** to sqlite3WalBeginReadTransaction().
  35545. **
  35546. ** If another thread or process has written into the database since
  35547. ** the read transaction was started, then it is not possible for this
  35548. ** thread to write as doing so would cause a fork. So this routine
  35549. ** returns SQLITE_BUSY in that case and no write transaction is started.
  35550. **
  35551. ** There can only be a single writer active at a time.
  35552. */
  35553. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  35554. int rc;
  35555. /* Cannot start a write transaction without first holding a read
  35556. ** transaction. */
  35557. assert( pWal->readLock>=0 );
  35558. if( pWal->readOnly ){
  35559. return SQLITE_READONLY;
  35560. }
  35561. /* Only one writer allowed at a time. Get the write lock. Return
  35562. ** SQLITE_BUSY if unable.
  35563. */
  35564. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35565. if( rc ){
  35566. return rc;
  35567. }
  35568. pWal->writeLock = 1;
  35569. /* If another connection has written to the database file since the
  35570. ** time the read transaction on this connection was started, then
  35571. ** the write is disallowed.
  35572. */
  35573. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  35574. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35575. pWal->writeLock = 0;
  35576. rc = SQLITE_BUSY_SNAPSHOT;
  35577. }
  35578. return rc;
  35579. }
  35580. /*
  35581. ** End a write transaction. The commit has already been done. This
  35582. ** routine merely releases the lock.
  35583. */
  35584. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  35585. if( pWal->writeLock ){
  35586. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35587. pWal->writeLock = 0;
  35588. pWal->truncateOnCommit = 0;
  35589. }
  35590. return SQLITE_OK;
  35591. }
  35592. /*
  35593. ** If any data has been written (but not committed) to the log file, this
  35594. ** function moves the write-pointer back to the start of the transaction.
  35595. **
  35596. ** Additionally, the callback function is invoked for each frame written
  35597. ** to the WAL since the start of the transaction. If the callback returns
  35598. ** other than SQLITE_OK, it is not invoked again and the error code is
  35599. ** returned to the caller.
  35600. **
  35601. ** Otherwise, if the callback function does not return an error, this
  35602. ** function returns SQLITE_OK.
  35603. */
  35604. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  35605. int rc = SQLITE_OK;
  35606. if( ALWAYS(pWal->writeLock) ){
  35607. Pgno iMax = pWal->hdr.mxFrame;
  35608. Pgno iFrame;
  35609. /* Restore the clients cache of the wal-index header to the state it
  35610. ** was in before the client began writing to the database.
  35611. */
  35612. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  35613. for(iFrame=pWal->hdr.mxFrame+1;
  35614. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  35615. iFrame++
  35616. ){
  35617. /* This call cannot fail. Unless the page for which the page number
  35618. ** is passed as the second argument is (a) in the cache and
  35619. ** (b) has an outstanding reference, then xUndo is either a no-op
  35620. ** (if (a) is false) or simply expels the page from the cache (if (b)
  35621. ** is false).
  35622. **
  35623. ** If the upper layer is doing a rollback, it is guaranteed that there
  35624. ** are no outstanding references to any page other than page 1. And
  35625. ** page 1 is never written to the log until the transaction is
  35626. ** committed. As a result, the call to xUndo may not fail.
  35627. */
  35628. assert( walFramePgno(pWal, iFrame)!=1 );
  35629. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  35630. }
  35631. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  35632. }
  35633. assert( rc==SQLITE_OK );
  35634. return rc;
  35635. }
  35636. /*
  35637. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  35638. ** values. This function populates the array with values required to
  35639. ** "rollback" the write position of the WAL handle back to the current
  35640. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  35641. */
  35642. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  35643. assert( pWal->writeLock );
  35644. aWalData[0] = pWal->hdr.mxFrame;
  35645. aWalData[1] = pWal->hdr.aFrameCksum[0];
  35646. aWalData[2] = pWal->hdr.aFrameCksum[1];
  35647. aWalData[3] = pWal->nCkpt;
  35648. }
  35649. /*
  35650. ** Move the write position of the WAL back to the point identified by
  35651. ** the values in the aWalData[] array. aWalData must point to an array
  35652. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  35653. ** by a call to WalSavepoint().
  35654. */
  35655. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  35656. int rc = SQLITE_OK;
  35657. assert( pWal->writeLock );
  35658. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  35659. if( aWalData[3]!=pWal->nCkpt ){
  35660. /* This savepoint was opened immediately after the write-transaction
  35661. ** was started. Right after that, the writer decided to wrap around
  35662. ** to the start of the log. Update the savepoint values to match.
  35663. */
  35664. aWalData[0] = 0;
  35665. aWalData[3] = pWal->nCkpt;
  35666. }
  35667. if( aWalData[0]<pWal->hdr.mxFrame ){
  35668. pWal->hdr.mxFrame = aWalData[0];
  35669. pWal->hdr.aFrameCksum[0] = aWalData[1];
  35670. pWal->hdr.aFrameCksum[1] = aWalData[2];
  35671. walCleanupHash(pWal);
  35672. }
  35673. return rc;
  35674. }
  35675. /*
  35676. ** This function is called just before writing a set of frames to the log
  35677. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  35678. ** to the current log file, it is possible to overwrite the start of the
  35679. ** existing log file with the new frames (i.e. "reset" the log). If so,
  35680. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  35681. ** unchanged.
  35682. **
  35683. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  35684. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  35685. ** if an error occurs.
  35686. */
  35687. static int walRestartLog(Wal *pWal){
  35688. int rc = SQLITE_OK;
  35689. int cnt;
  35690. if( pWal->readLock==0 ){
  35691. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  35692. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  35693. if( pInfo->nBackfill>0 ){
  35694. u32 salt1;
  35695. sqlite3_randomness(4, &salt1);
  35696. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  35697. if( rc==SQLITE_OK ){
  35698. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  35699. ** readers are currently using the WAL), then the transactions
  35700. ** frames will overwrite the start of the existing log. Update the
  35701. ** wal-index header to reflect this.
  35702. **
  35703. ** In theory it would be Ok to update the cache of the header only
  35704. ** at this point. But updating the actual wal-index header is also
  35705. ** safe and means there is no special case for sqlite3WalUndo()
  35706. ** to handle if this transaction is rolled back.
  35707. */
  35708. int i; /* Loop counter */
  35709. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  35710. pWal->nCkpt++;
  35711. pWal->hdr.mxFrame = 0;
  35712. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  35713. aSalt[1] = salt1;
  35714. walIndexWriteHdr(pWal);
  35715. pInfo->nBackfill = 0;
  35716. pInfo->aReadMark[1] = 0;
  35717. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  35718. assert( pInfo->aReadMark[0]==0 );
  35719. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  35720. }else if( rc!=SQLITE_BUSY ){
  35721. return rc;
  35722. }
  35723. }
  35724. walUnlockShared(pWal, WAL_READ_LOCK(0));
  35725. pWal->readLock = -1;
  35726. cnt = 0;
  35727. do{
  35728. int notUsed;
  35729. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  35730. }while( rc==WAL_RETRY );
  35731. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  35732. testcase( (rc&0xff)==SQLITE_IOERR );
  35733. testcase( rc==SQLITE_PROTOCOL );
  35734. testcase( rc==SQLITE_OK );
  35735. }
  35736. return rc;
  35737. }
  35738. /*
  35739. ** Information about the current state of the WAL file and where
  35740. ** the next fsync should occur - passed from sqlite3WalFrames() into
  35741. ** walWriteToLog().
  35742. */
  35743. typedef struct WalWriter {
  35744. Wal *pWal; /* The complete WAL information */
  35745. sqlite3_file *pFd; /* The WAL file to which we write */
  35746. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  35747. int syncFlags; /* Flags for the fsync */
  35748. int szPage; /* Size of one page */
  35749. } WalWriter;
  35750. /*
  35751. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  35752. ** Do a sync when crossing the p->iSyncPoint boundary.
  35753. **
  35754. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  35755. ** first write the part before iSyncPoint, then sync, then write the
  35756. ** rest.
  35757. */
  35758. static int walWriteToLog(
  35759. WalWriter *p, /* WAL to write to */
  35760. void *pContent, /* Content to be written */
  35761. int iAmt, /* Number of bytes to write */
  35762. sqlite3_int64 iOffset /* Start writing at this offset */
  35763. ){
  35764. int rc;
  35765. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  35766. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  35767. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  35768. if( rc ) return rc;
  35769. iOffset += iFirstAmt;
  35770. iAmt -= iFirstAmt;
  35771. pContent = (void*)(iFirstAmt + (char*)pContent);
  35772. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  35773. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  35774. if( iAmt==0 || rc ) return rc;
  35775. }
  35776. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  35777. return rc;
  35778. }
  35779. /*
  35780. ** Write out a single frame of the WAL
  35781. */
  35782. static int walWriteOneFrame(
  35783. WalWriter *p, /* Where to write the frame */
  35784. PgHdr *pPage, /* The page of the frame to be written */
  35785. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  35786. sqlite3_int64 iOffset /* Byte offset at which to write */
  35787. ){
  35788. int rc; /* Result code from subfunctions */
  35789. void *pData; /* Data actually written */
  35790. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  35791. #if defined(SQLITE_HAS_CODEC)
  35792. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  35793. #else
  35794. pData = pPage->pData;
  35795. #endif
  35796. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  35797. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  35798. if( rc ) return rc;
  35799. /* Write the page data */
  35800. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  35801. return rc;
  35802. }
  35803. /*
  35804. ** Write a set of frames to the log. The caller must hold the write-lock
  35805. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  35806. */
  35807. SQLITE_PRIVATE int sqlite3WalFrames(
  35808. Wal *pWal, /* Wal handle to write to */
  35809. int szPage, /* Database page-size in bytes */
  35810. PgHdr *pList, /* List of dirty pages to write */
  35811. Pgno nTruncate, /* Database size after this commit */
  35812. int isCommit, /* True if this is a commit */
  35813. int sync_flags /* Flags to pass to OsSync() (or 0) */
  35814. ){
  35815. int rc; /* Used to catch return codes */
  35816. u32 iFrame; /* Next frame address */
  35817. PgHdr *p; /* Iterator to run through pList with. */
  35818. PgHdr *pLast = 0; /* Last frame in list */
  35819. int nExtra = 0; /* Number of extra copies of last page */
  35820. int szFrame; /* The size of a single frame */
  35821. i64 iOffset; /* Next byte to write in WAL file */
  35822. WalWriter w; /* The writer */
  35823. assert( pList );
  35824. assert( pWal->writeLock );
  35825. /* If this frame set completes a transaction, then nTruncate>0. If
  35826. ** nTruncate==0 then this frame set does not complete the transaction. */
  35827. assert( (isCommit!=0)==(nTruncate!=0) );
  35828. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  35829. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  35830. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  35831. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  35832. }
  35833. #endif
  35834. /* See if it is possible to write these frames into the start of the
  35835. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  35836. */
  35837. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  35838. return rc;
  35839. }
  35840. /* If this is the first frame written into the log, write the WAL
  35841. ** header to the start of the WAL file. See comments at the top of
  35842. ** this source file for a description of the WAL header format.
  35843. */
  35844. iFrame = pWal->hdr.mxFrame;
  35845. if( iFrame==0 ){
  35846. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  35847. u32 aCksum[2]; /* Checksum for wal-header */
  35848. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  35849. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  35850. sqlite3Put4byte(&aWalHdr[8], szPage);
  35851. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  35852. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  35853. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  35854. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  35855. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  35856. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  35857. pWal->szPage = szPage;
  35858. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  35859. pWal->hdr.aFrameCksum[0] = aCksum[0];
  35860. pWal->hdr.aFrameCksum[1] = aCksum[1];
  35861. pWal->truncateOnCommit = 1;
  35862. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  35863. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  35864. if( rc!=SQLITE_OK ){
  35865. return rc;
  35866. }
  35867. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  35868. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  35869. ** an out-of-order write following a WAL restart could result in
  35870. ** database corruption. See the ticket:
  35871. **
  35872. ** http://localhost:591/sqlite/info/ff5be73dee
  35873. */
  35874. if( pWal->syncHeader && sync_flags ){
  35875. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  35876. if( rc ) return rc;
  35877. }
  35878. }
  35879. assert( (int)pWal->szPage==szPage );
  35880. /* Setup information needed to write frames into the WAL */
  35881. w.pWal = pWal;
  35882. w.pFd = pWal->pWalFd;
  35883. w.iSyncPoint = 0;
  35884. w.syncFlags = sync_flags;
  35885. w.szPage = szPage;
  35886. iOffset = walFrameOffset(iFrame+1, szPage);
  35887. szFrame = szPage + WAL_FRAME_HDRSIZE;
  35888. /* Write all frames into the log file exactly once */
  35889. for(p=pList; p; p=p->pDirty){
  35890. int nDbSize; /* 0 normally. Positive == commit flag */
  35891. iFrame++;
  35892. assert( iOffset==walFrameOffset(iFrame, szPage) );
  35893. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  35894. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  35895. if( rc ) return rc;
  35896. pLast = p;
  35897. iOffset += szFrame;
  35898. }
  35899. /* If this is the end of a transaction, then we might need to pad
  35900. ** the transaction and/or sync the WAL file.
  35901. **
  35902. ** Padding and syncing only occur if this set of frames complete a
  35903. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  35904. ** or synchonous==OFF, then no padding or syncing are needed.
  35905. **
  35906. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  35907. ** needed and only the sync is done. If padding is needed, then the
  35908. ** final frame is repeated (with its commit mark) until the next sector
  35909. ** boundary is crossed. Only the part of the WAL prior to the last
  35910. ** sector boundary is synced; the part of the last frame that extends
  35911. ** past the sector boundary is written after the sync.
  35912. */
  35913. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  35914. if( pWal->padToSectorBoundary ){
  35915. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  35916. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  35917. while( iOffset<w.iSyncPoint ){
  35918. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  35919. if( rc ) return rc;
  35920. iOffset += szFrame;
  35921. nExtra++;
  35922. }
  35923. }else{
  35924. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  35925. }
  35926. }
  35927. /* If this frame set completes the first transaction in the WAL and
  35928. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  35929. ** journal size limit, if possible.
  35930. */
  35931. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  35932. i64 sz = pWal->mxWalSize;
  35933. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  35934. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  35935. }
  35936. walLimitSize(pWal, sz);
  35937. pWal->truncateOnCommit = 0;
  35938. }
  35939. /* Append data to the wal-index. It is not necessary to lock the
  35940. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  35941. ** guarantees that there are no other writers, and no data that may
  35942. ** be in use by existing readers is being overwritten.
  35943. */
  35944. iFrame = pWal->hdr.mxFrame;
  35945. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  35946. iFrame++;
  35947. rc = walIndexAppend(pWal, iFrame, p->pgno);
  35948. }
  35949. while( rc==SQLITE_OK && nExtra>0 ){
  35950. iFrame++;
  35951. nExtra--;
  35952. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  35953. }
  35954. if( rc==SQLITE_OK ){
  35955. /* Update the private copy of the header. */
  35956. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  35957. testcase( szPage<=32768 );
  35958. testcase( szPage>=65536 );
  35959. pWal->hdr.mxFrame = iFrame;
  35960. if( isCommit ){
  35961. pWal->hdr.iChange++;
  35962. pWal->hdr.nPage = nTruncate;
  35963. }
  35964. /* If this is a commit, update the wal-index header too. */
  35965. if( isCommit ){
  35966. walIndexWriteHdr(pWal);
  35967. pWal->iCallback = iFrame;
  35968. }
  35969. }
  35970. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  35971. return rc;
  35972. }
  35973. /*
  35974. ** This routine is called to implement sqlite3_wal_checkpoint() and
  35975. ** related interfaces.
  35976. **
  35977. ** Obtain a CHECKPOINT lock and then backfill as much information as
  35978. ** we can from WAL into the database.
  35979. **
  35980. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  35981. ** callback. In this case this function runs a blocking checkpoint.
  35982. */
  35983. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  35984. Wal *pWal, /* Wal connection */
  35985. int eMode, /* PASSIVE, FULL or RESTART */
  35986. int (*xBusy)(void*), /* Function to call when busy */
  35987. void *pBusyArg, /* Context argument for xBusyHandler */
  35988. int sync_flags, /* Flags to sync db file with (or 0) */
  35989. int nBuf, /* Size of temporary buffer */
  35990. u8 *zBuf, /* Temporary buffer to use */
  35991. int *pnLog, /* OUT: Number of frames in WAL */
  35992. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  35993. ){
  35994. int rc; /* Return code */
  35995. int isChanged = 0; /* True if a new wal-index header is loaded */
  35996. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  35997. assert( pWal->ckptLock==0 );
  35998. assert( pWal->writeLock==0 );
  35999. if( pWal->readOnly ) return SQLITE_READONLY;
  36000. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  36001. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  36002. if( rc ){
  36003. /* Usually this is SQLITE_BUSY meaning that another thread or process
  36004. ** is already running a checkpoint, or maybe a recovery. But it might
  36005. ** also be SQLITE_IOERR. */
  36006. return rc;
  36007. }
  36008. pWal->ckptLock = 1;
  36009. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  36010. ** to prevent any writers from running while the checkpoint is underway.
  36011. ** This has to be done before the call to walIndexReadHdr() below.
  36012. **
  36013. ** If the writer lock cannot be obtained, then a passive checkpoint is
  36014. ** run instead. Since the checkpointer is not holding the writer lock,
  36015. ** there is no point in blocking waiting for any readers. Assuming no
  36016. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  36017. */
  36018. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  36019. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  36020. if( rc==SQLITE_OK ){
  36021. pWal->writeLock = 1;
  36022. }else if( rc==SQLITE_BUSY ){
  36023. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  36024. rc = SQLITE_OK;
  36025. }
  36026. }
  36027. /* Read the wal-index header. */
  36028. if( rc==SQLITE_OK ){
  36029. rc = walIndexReadHdr(pWal, &isChanged);
  36030. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  36031. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  36032. }
  36033. }
  36034. /* Copy data from the log to the database file. */
  36035. if( rc==SQLITE_OK ){
  36036. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  36037. rc = SQLITE_CORRUPT_BKPT;
  36038. }else{
  36039. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  36040. }
  36041. /* If no error occurred, set the output variables. */
  36042. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  36043. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  36044. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  36045. }
  36046. }
  36047. if( isChanged ){
  36048. /* If a new wal-index header was loaded before the checkpoint was
  36049. ** performed, then the pager-cache associated with pWal is now
  36050. ** out of date. So zero the cached wal-index header to ensure that
  36051. ** next time the pager opens a snapshot on this database it knows that
  36052. ** the cache needs to be reset.
  36053. */
  36054. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  36055. }
  36056. /* Release the locks. */
  36057. sqlite3WalEndWriteTransaction(pWal);
  36058. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  36059. pWal->ckptLock = 0;
  36060. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  36061. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  36062. }
  36063. /* Return the value to pass to a sqlite3_wal_hook callback, the
  36064. ** number of frames in the WAL at the point of the last commit since
  36065. ** sqlite3WalCallback() was called. If no commits have occurred since
  36066. ** the last call, then return 0.
  36067. */
  36068. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  36069. u32 ret = 0;
  36070. if( pWal ){
  36071. ret = pWal->iCallback;
  36072. pWal->iCallback = 0;
  36073. }
  36074. return (int)ret;
  36075. }
  36076. /*
  36077. ** This function is called to change the WAL subsystem into or out
  36078. ** of locking_mode=EXCLUSIVE.
  36079. **
  36080. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  36081. ** into locking_mode=NORMAL. This means that we must acquire a lock
  36082. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  36083. ** or if the acquisition of the lock fails, then return 0. If the
  36084. ** transition out of exclusive-mode is successful, return 1. This
  36085. ** operation must occur while the pager is still holding the exclusive
  36086. ** lock on the main database file.
  36087. **
  36088. ** If op is one, then change from locking_mode=NORMAL into
  36089. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  36090. ** be released. Return 1 if the transition is made and 0 if the
  36091. ** WAL is already in exclusive-locking mode - meaning that this
  36092. ** routine is a no-op. The pager must already hold the exclusive lock
  36093. ** on the main database file before invoking this operation.
  36094. **
  36095. ** If op is negative, then do a dry-run of the op==1 case but do
  36096. ** not actually change anything. The pager uses this to see if it
  36097. ** should acquire the database exclusive lock prior to invoking
  36098. ** the op==1 case.
  36099. */
  36100. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  36101. int rc;
  36102. assert( pWal->writeLock==0 );
  36103. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  36104. /* pWal->readLock is usually set, but might be -1 if there was a
  36105. ** prior error while attempting to acquire are read-lock. This cannot
  36106. ** happen if the connection is actually in exclusive mode (as no xShmLock
  36107. ** locks are taken in this case). Nor should the pager attempt to
  36108. ** upgrade to exclusive-mode following such an error.
  36109. */
  36110. assert( pWal->readLock>=0 || pWal->lockError );
  36111. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  36112. if( op==0 ){
  36113. if( pWal->exclusiveMode ){
  36114. pWal->exclusiveMode = 0;
  36115. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  36116. pWal->exclusiveMode = 1;
  36117. }
  36118. rc = pWal->exclusiveMode==0;
  36119. }else{
  36120. /* Already in locking_mode=NORMAL */
  36121. rc = 0;
  36122. }
  36123. }else if( op>0 ){
  36124. assert( pWal->exclusiveMode==0 );
  36125. assert( pWal->readLock>=0 );
  36126. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  36127. pWal->exclusiveMode = 1;
  36128. rc = 1;
  36129. }else{
  36130. rc = pWal->exclusiveMode==0;
  36131. }
  36132. return rc;
  36133. }
  36134. /*
  36135. ** Return true if the argument is non-NULL and the WAL module is using
  36136. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  36137. ** WAL module is using shared-memory, return false.
  36138. */
  36139. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  36140. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  36141. }
  36142. #ifdef SQLITE_ENABLE_ZIPVFS
  36143. /*
  36144. ** If the argument is not NULL, it points to a Wal object that holds a
  36145. ** read-lock. This function returns the database page-size if it is known,
  36146. ** or zero if it is not (or if pWal is NULL).
  36147. */
  36148. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  36149. assert( pWal==0 || pWal->readLock>=0 );
  36150. return (pWal ? pWal->szPage : 0);
  36151. }
  36152. #endif
  36153. #endif /* #ifndef SQLITE_OMIT_WAL */
  36154. /************** End of wal.c *************************************************/
  36155. /************** Begin file btmutex.c *****************************************/
  36156. /*
  36157. ** 2007 August 27
  36158. **
  36159. ** The author disclaims copyright to this source code. In place of
  36160. ** a legal notice, here is a blessing:
  36161. **
  36162. ** May you do good and not evil.
  36163. ** May you find forgiveness for yourself and forgive others.
  36164. ** May you share freely, never taking more than you give.
  36165. **
  36166. *************************************************************************
  36167. **
  36168. ** This file contains code used to implement mutexes on Btree objects.
  36169. ** This code really belongs in btree.c. But btree.c is getting too
  36170. ** big and we want to break it down some. This packaged seemed like
  36171. ** a good breakout.
  36172. */
  36173. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  36174. /************** Begin file btreeInt.h ****************************************/
  36175. /*
  36176. ** 2004 April 6
  36177. **
  36178. ** The author disclaims copyright to this source code. In place of
  36179. ** a legal notice, here is a blessing:
  36180. **
  36181. ** May you do good and not evil.
  36182. ** May you find forgiveness for yourself and forgive others.
  36183. ** May you share freely, never taking more than you give.
  36184. **
  36185. *************************************************************************
  36186. ** This file implements a external (disk-based) database using BTrees.
  36187. ** For a detailed discussion of BTrees, refer to
  36188. **
  36189. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  36190. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  36191. ** Publishing Company, Reading, Massachusetts.
  36192. **
  36193. ** The basic idea is that each page of the file contains N database
  36194. ** entries and N+1 pointers to subpages.
  36195. **
  36196. ** ----------------------------------------------------------------
  36197. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  36198. ** ----------------------------------------------------------------
  36199. **
  36200. ** All of the keys on the page that Ptr(0) points to have values less
  36201. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  36202. ** values greater than Key(0) and less than Key(1). All of the keys
  36203. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  36204. ** so forth.
  36205. **
  36206. ** Finding a particular key requires reading O(log(M)) pages from the
  36207. ** disk where M is the number of entries in the tree.
  36208. **
  36209. ** In this implementation, a single file can hold one or more separate
  36210. ** BTrees. Each BTree is identified by the index of its root page. The
  36211. ** key and data for any entry are combined to form the "payload". A
  36212. ** fixed amount of payload can be carried directly on the database
  36213. ** page. If the payload is larger than the preset amount then surplus
  36214. ** bytes are stored on overflow pages. The payload for an entry
  36215. ** and the preceding pointer are combined to form a "Cell". Each
  36216. ** page has a small header which contains the Ptr(N) pointer and other
  36217. ** information such as the size of key and data.
  36218. **
  36219. ** FORMAT DETAILS
  36220. **
  36221. ** The file is divided into pages. The first page is called page 1,
  36222. ** the second is page 2, and so forth. A page number of zero indicates
  36223. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  36224. ** Each page can be either a btree page, a freelist page, an overflow
  36225. ** page, or a pointer-map page.
  36226. **
  36227. ** The first page is always a btree page. The first 100 bytes of the first
  36228. ** page contain a special header (the "file header") that describes the file.
  36229. ** The format of the file header is as follows:
  36230. **
  36231. ** OFFSET SIZE DESCRIPTION
  36232. ** 0 16 Header string: "SQLite format 3\000"
  36233. ** 16 2 Page size in bytes. (1 means 65536)
  36234. ** 18 1 File format write version
  36235. ** 19 1 File format read version
  36236. ** 20 1 Bytes of unused space at the end of each page
  36237. ** 21 1 Max embedded payload fraction (must be 64)
  36238. ** 22 1 Min embedded payload fraction (must be 32)
  36239. ** 23 1 Min leaf payload fraction (must be 32)
  36240. ** 24 4 File change counter
  36241. ** 28 4 Reserved for future use
  36242. ** 32 4 First freelist page
  36243. ** 36 4 Number of freelist pages in the file
  36244. ** 40 60 15 4-byte meta values passed to higher layers
  36245. **
  36246. ** 40 4 Schema cookie
  36247. ** 44 4 File format of schema layer
  36248. ** 48 4 Size of page cache
  36249. ** 52 4 Largest root-page (auto/incr_vacuum)
  36250. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  36251. ** 60 4 User version
  36252. ** 64 4 Incremental vacuum mode
  36253. ** 68 4 Application-ID
  36254. ** 72 20 unused
  36255. ** 92 4 The version-valid-for number
  36256. ** 96 4 SQLITE_VERSION_NUMBER
  36257. **
  36258. ** All of the integer values are big-endian (most significant byte first).
  36259. **
  36260. ** The file change counter is incremented when the database is changed
  36261. ** This counter allows other processes to know when the file has changed
  36262. ** and thus when they need to flush their cache.
  36263. **
  36264. ** The max embedded payload fraction is the amount of the total usable
  36265. ** space in a page that can be consumed by a single cell for standard
  36266. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  36267. ** is to limit the maximum cell size so that at least 4 cells will fit
  36268. ** on one page. Thus the default max embedded payload fraction is 64.
  36269. **
  36270. ** If the payload for a cell is larger than the max payload, then extra
  36271. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  36272. ** as many bytes as possible are moved into the overflow pages without letting
  36273. ** the cell size drop below the min embedded payload fraction.
  36274. **
  36275. ** The min leaf payload fraction is like the min embedded payload fraction
  36276. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  36277. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  36278. ** not specified in the header.
  36279. **
  36280. ** Each btree pages is divided into three sections: The header, the
  36281. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  36282. ** file header that occurs before the page header.
  36283. **
  36284. ** |----------------|
  36285. ** | file header | 100 bytes. Page 1 only.
  36286. ** |----------------|
  36287. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  36288. ** |----------------|
  36289. ** | cell pointer | | 2 bytes per cell. Sorted order.
  36290. ** | array | | Grows downward
  36291. ** | | v
  36292. ** |----------------|
  36293. ** | unallocated |
  36294. ** | space |
  36295. ** |----------------| ^ Grows upwards
  36296. ** | cell content | | Arbitrary order interspersed with freeblocks.
  36297. ** | area | | and free space fragments.
  36298. ** |----------------|
  36299. **
  36300. ** The page headers looks like this:
  36301. **
  36302. ** OFFSET SIZE DESCRIPTION
  36303. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  36304. ** 1 2 byte offset to the first freeblock
  36305. ** 3 2 number of cells on this page
  36306. ** 5 2 first byte of the cell content area
  36307. ** 7 1 number of fragmented free bytes
  36308. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  36309. **
  36310. ** The flags define the format of this btree page. The leaf flag means that
  36311. ** this page has no children. The zerodata flag means that this page carries
  36312. ** only keys and no data. The intkey flag means that the key is a integer
  36313. ** which is stored in the key size entry of the cell header rather than in
  36314. ** the payload area.
  36315. **
  36316. ** The cell pointer array begins on the first byte after the page header.
  36317. ** The cell pointer array contains zero or more 2-byte numbers which are
  36318. ** offsets from the beginning of the page to the cell content in the cell
  36319. ** content area. The cell pointers occur in sorted order. The system strives
  36320. ** to keep free space after the last cell pointer so that new cells can
  36321. ** be easily added without having to defragment the page.
  36322. **
  36323. ** Cell content is stored at the very end of the page and grows toward the
  36324. ** beginning of the page.
  36325. **
  36326. ** Unused space within the cell content area is collected into a linked list of
  36327. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  36328. ** to the first freeblock is given in the header. Freeblocks occur in
  36329. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  36330. ** any group of 3 or fewer unused bytes in the cell content area cannot
  36331. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  36332. ** a fragment. The total number of bytes in all fragments is recorded.
  36333. ** in the page header at offset 7.
  36334. **
  36335. ** SIZE DESCRIPTION
  36336. ** 2 Byte offset of the next freeblock
  36337. ** 2 Bytes in this freeblock
  36338. **
  36339. ** Cells are of variable length. Cells are stored in the cell content area at
  36340. ** the end of the page. Pointers to the cells are in the cell pointer array
  36341. ** that immediately follows the page header. Cells is not necessarily
  36342. ** contiguous or in order, but cell pointers are contiguous and in order.
  36343. **
  36344. ** Cell content makes use of variable length integers. A variable
  36345. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  36346. ** byte are used. The integer consists of all bytes that have bit 8 set and
  36347. ** the first byte with bit 8 clear. The most significant byte of the integer
  36348. ** appears first. A variable-length integer may not be more than 9 bytes long.
  36349. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  36350. ** allows a 64-bit integer to be encoded in 9 bytes.
  36351. **
  36352. ** 0x00 becomes 0x00000000
  36353. ** 0x7f becomes 0x0000007f
  36354. ** 0x81 0x00 becomes 0x00000080
  36355. ** 0x82 0x00 becomes 0x00000100
  36356. ** 0x80 0x7f becomes 0x0000007f
  36357. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  36358. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  36359. **
  36360. ** Variable length integers are used for rowids and to hold the number of
  36361. ** bytes of key and data in a btree cell.
  36362. **
  36363. ** The content of a cell looks like this:
  36364. **
  36365. ** SIZE DESCRIPTION
  36366. ** 4 Page number of the left child. Omitted if leaf flag is set.
  36367. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  36368. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  36369. ** * Payload
  36370. ** 4 First page of the overflow chain. Omitted if no overflow
  36371. **
  36372. ** Overflow pages form a linked list. Each page except the last is completely
  36373. ** filled with data (pagesize - 4 bytes). The last page can have as little
  36374. ** as 1 byte of data.
  36375. **
  36376. ** SIZE DESCRIPTION
  36377. ** 4 Page number of next overflow page
  36378. ** * Data
  36379. **
  36380. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  36381. ** file header points to the first in a linked list of trunk page. Each trunk
  36382. ** page points to multiple leaf pages. The content of a leaf page is
  36383. ** unspecified. A trunk page looks like this:
  36384. **
  36385. ** SIZE DESCRIPTION
  36386. ** 4 Page number of next trunk page
  36387. ** 4 Number of leaf pointers on this page
  36388. ** * zero or more pages numbers of leaves
  36389. */
  36390. /* The following value is the maximum cell size assuming a maximum page
  36391. ** size give above.
  36392. */
  36393. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  36394. /* The maximum number of cells on a single page of the database. This
  36395. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  36396. ** plus 2 bytes for the index to the cell in the page header). Such
  36397. ** small cells will be rare, but they are possible.
  36398. */
  36399. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  36400. /* Forward declarations */
  36401. typedef struct MemPage MemPage;
  36402. typedef struct BtLock BtLock;
  36403. /*
  36404. ** This is a magic string that appears at the beginning of every
  36405. ** SQLite database in order to identify the file as a real database.
  36406. **
  36407. ** You can change this value at compile-time by specifying a
  36408. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  36409. ** header must be exactly 16 bytes including the zero-terminator so
  36410. ** the string itself should be 15 characters long. If you change
  36411. ** the header, then your custom library will not be able to read
  36412. ** databases generated by the standard tools and the standard tools
  36413. ** will not be able to read databases created by your custom library.
  36414. */
  36415. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  36416. # define SQLITE_FILE_HEADER "SQLite format 3"
  36417. #endif
  36418. /*
  36419. ** Page type flags. An ORed combination of these flags appear as the
  36420. ** first byte of on-disk image of every BTree page.
  36421. */
  36422. #define PTF_INTKEY 0x01
  36423. #define PTF_ZERODATA 0x02
  36424. #define PTF_LEAFDATA 0x04
  36425. #define PTF_LEAF 0x08
  36426. /*
  36427. ** As each page of the file is loaded into memory, an instance of the following
  36428. ** structure is appended and initialized to zero. This structure stores
  36429. ** information about the page that is decoded from the raw file page.
  36430. **
  36431. ** The pParent field points back to the parent page. This allows us to
  36432. ** walk up the BTree from any leaf to the root. Care must be taken to
  36433. ** unref() the parent page pointer when this page is no longer referenced.
  36434. ** The pageDestructor() routine handles that chore.
  36435. **
  36436. ** Access to all fields of this structure is controlled by the mutex
  36437. ** stored in MemPage.pBt->mutex.
  36438. */
  36439. struct MemPage {
  36440. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  36441. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  36442. u8 intKey; /* True if intkey flag is set */
  36443. u8 leaf; /* True if leaf flag is set */
  36444. u8 hasData; /* True if this page stores data */
  36445. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  36446. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  36447. u8 max1bytePayload; /* min(maxLocal,127) */
  36448. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  36449. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  36450. u16 cellOffset; /* Index in aData of first cell pointer */
  36451. u16 nFree; /* Number of free bytes on the page */
  36452. u16 nCell; /* Number of cells on this page, local and ovfl */
  36453. u16 maskPage; /* Mask for page offset */
  36454. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  36455. ** non-overflow cell */
  36456. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  36457. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  36458. u8 *aData; /* Pointer to disk image of the page data */
  36459. u8 *aDataEnd; /* One byte past the end of usable data */
  36460. u8 *aCellIdx; /* The cell index area */
  36461. DbPage *pDbPage; /* Pager page handle */
  36462. Pgno pgno; /* Page number for this page */
  36463. };
  36464. /*
  36465. ** The in-memory image of a disk page has the auxiliary information appended
  36466. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  36467. ** that extra information.
  36468. */
  36469. #define EXTRA_SIZE sizeof(MemPage)
  36470. /*
  36471. ** A linked list of the following structures is stored at BtShared.pLock.
  36472. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  36473. ** is opened on the table with root page BtShared.iTable. Locks are removed
  36474. ** from this list when a transaction is committed or rolled back, or when
  36475. ** a btree handle is closed.
  36476. */
  36477. struct BtLock {
  36478. Btree *pBtree; /* Btree handle holding this lock */
  36479. Pgno iTable; /* Root page of table */
  36480. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  36481. BtLock *pNext; /* Next in BtShared.pLock list */
  36482. };
  36483. /* Candidate values for BtLock.eLock */
  36484. #define READ_LOCK 1
  36485. #define WRITE_LOCK 2
  36486. /* A Btree handle
  36487. **
  36488. ** A database connection contains a pointer to an instance of
  36489. ** this object for every database file that it has open. This structure
  36490. ** is opaque to the database connection. The database connection cannot
  36491. ** see the internals of this structure and only deals with pointers to
  36492. ** this structure.
  36493. **
  36494. ** For some database files, the same underlying database cache might be
  36495. ** shared between multiple connections. In that case, each connection
  36496. ** has it own instance of this object. But each instance of this object
  36497. ** points to the same BtShared object. The database cache and the
  36498. ** schema associated with the database file are all contained within
  36499. ** the BtShared object.
  36500. **
  36501. ** All fields in this structure are accessed under sqlite3.mutex.
  36502. ** The pBt pointer itself may not be changed while there exists cursors
  36503. ** in the referenced BtShared that point back to this Btree since those
  36504. ** cursors have to go through this Btree to find their BtShared and
  36505. ** they often do so without holding sqlite3.mutex.
  36506. */
  36507. struct Btree {
  36508. sqlite3 *db; /* The database connection holding this btree */
  36509. BtShared *pBt; /* Sharable content of this btree */
  36510. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  36511. u8 sharable; /* True if we can share pBt with another db */
  36512. u8 locked; /* True if db currently has pBt locked */
  36513. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  36514. int nBackup; /* Number of backup operations reading this btree */
  36515. Btree *pNext; /* List of other sharable Btrees from the same db */
  36516. Btree *pPrev; /* Back pointer of the same list */
  36517. #ifndef SQLITE_OMIT_SHARED_CACHE
  36518. BtLock lock; /* Object used to lock page 1 */
  36519. #endif
  36520. };
  36521. /*
  36522. ** Btree.inTrans may take one of the following values.
  36523. **
  36524. ** If the shared-data extension is enabled, there may be multiple users
  36525. ** of the Btree structure. At most one of these may open a write transaction,
  36526. ** but any number may have active read transactions.
  36527. */
  36528. #define TRANS_NONE 0
  36529. #define TRANS_READ 1
  36530. #define TRANS_WRITE 2
  36531. /*
  36532. ** An instance of this object represents a single database file.
  36533. **
  36534. ** A single database file can be in use at the same time by two
  36535. ** or more database connections. When two or more connections are
  36536. ** sharing the same database file, each connection has it own
  36537. ** private Btree object for the file and each of those Btrees points
  36538. ** to this one BtShared object. BtShared.nRef is the number of
  36539. ** connections currently sharing this database file.
  36540. **
  36541. ** Fields in this structure are accessed under the BtShared.mutex
  36542. ** mutex, except for nRef and pNext which are accessed under the
  36543. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  36544. ** may not be modified once it is initially set as long as nRef>0.
  36545. ** The pSchema field may be set once under BtShared.mutex and
  36546. ** thereafter is unchanged as long as nRef>0.
  36547. **
  36548. ** isPending:
  36549. **
  36550. ** If a BtShared client fails to obtain a write-lock on a database
  36551. ** table (because there exists one or more read-locks on the table),
  36552. ** the shared-cache enters 'pending-lock' state and isPending is
  36553. ** set to true.
  36554. **
  36555. ** The shared-cache leaves the 'pending lock' state when either of
  36556. ** the following occur:
  36557. **
  36558. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  36559. ** 2) The number of locks held by other connections drops to zero.
  36560. **
  36561. ** while in the 'pending-lock' state, no connection may start a new
  36562. ** transaction.
  36563. **
  36564. ** This feature is included to help prevent writer-starvation.
  36565. */
  36566. struct BtShared {
  36567. Pager *pPager; /* The page cache */
  36568. sqlite3 *db; /* Database connection currently using this Btree */
  36569. BtCursor *pCursor; /* A list of all open cursors */
  36570. MemPage *pPage1; /* First page of the database */
  36571. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  36572. #ifndef SQLITE_OMIT_AUTOVACUUM
  36573. u8 autoVacuum; /* True if auto-vacuum is enabled */
  36574. u8 incrVacuum; /* True if incr-vacuum is enabled */
  36575. u8 bDoTruncate; /* True to truncate db on commit */
  36576. #endif
  36577. u8 inTransaction; /* Transaction state */
  36578. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  36579. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  36580. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  36581. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  36582. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  36583. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  36584. u32 pageSize; /* Total number of bytes on a page */
  36585. u32 usableSize; /* Number of usable bytes on each page */
  36586. int nTransaction; /* Number of open transactions (read + write) */
  36587. u32 nPage; /* Number of pages in the database */
  36588. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  36589. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  36590. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  36591. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  36592. #ifndef SQLITE_OMIT_SHARED_CACHE
  36593. int nRef; /* Number of references to this structure */
  36594. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  36595. BtLock *pLock; /* List of locks held on this shared-btree struct */
  36596. Btree *pWriter; /* Btree with currently open write transaction */
  36597. #endif
  36598. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  36599. };
  36600. /*
  36601. ** Allowed values for BtShared.btsFlags
  36602. */
  36603. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  36604. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  36605. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  36606. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  36607. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  36608. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  36609. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  36610. /*
  36611. ** An instance of the following structure is used to hold information
  36612. ** about a cell. The parseCellPtr() function fills in this structure
  36613. ** based on information extract from the raw disk page.
  36614. */
  36615. typedef struct CellInfo CellInfo;
  36616. struct CellInfo {
  36617. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  36618. u8 *pCell; /* Pointer to the start of cell content */
  36619. u32 nData; /* Number of bytes of data */
  36620. u32 nPayload; /* Total amount of payload */
  36621. u16 nHeader; /* Size of the cell content header in bytes */
  36622. u16 nLocal; /* Amount of payload held locally */
  36623. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  36624. u16 nSize; /* Size of the cell content on the main b-tree page */
  36625. };
  36626. /*
  36627. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  36628. ** this will be declared corrupt. This value is calculated based on a
  36629. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  36630. ** root-node and 3 for all other internal nodes.
  36631. **
  36632. ** If a tree that appears to be taller than this is encountered, it is
  36633. ** assumed that the database is corrupt.
  36634. */
  36635. #define BTCURSOR_MAX_DEPTH 20
  36636. /*
  36637. ** A cursor is a pointer to a particular entry within a particular
  36638. ** b-tree within a database file.
  36639. **
  36640. ** The entry is identified by its MemPage and the index in
  36641. ** MemPage.aCell[] of the entry.
  36642. **
  36643. ** A single database file can be shared by two more database connections,
  36644. ** but cursors cannot be shared. Each cursor is associated with a
  36645. ** particular database connection identified BtCursor.pBtree.db.
  36646. **
  36647. ** Fields in this structure are accessed under the BtShared.mutex
  36648. ** found at self->pBt->mutex.
  36649. */
  36650. struct BtCursor {
  36651. Btree *pBtree; /* The Btree to which this cursor belongs */
  36652. BtShared *pBt; /* The BtShared this cursor points to */
  36653. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  36654. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  36655. #ifndef SQLITE_OMIT_INCRBLOB
  36656. Pgno *aOverflow; /* Cache of overflow page locations */
  36657. #endif
  36658. Pgno pgnoRoot; /* The root page of this tree */
  36659. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  36660. CellInfo info; /* A parse of the cell we are pointing at */
  36661. i64 nKey; /* Size of pKey, or last integer key */
  36662. void *pKey; /* Saved key that was cursor's last known position */
  36663. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  36664. u8 wrFlag; /* True if writable */
  36665. u8 atLast; /* Cursor pointing to the last entry */
  36666. u8 validNKey; /* True if info.nKey is valid */
  36667. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  36668. #ifndef SQLITE_OMIT_INCRBLOB
  36669. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  36670. #endif
  36671. u8 hints; /* As configured by CursorSetHints() */
  36672. i16 iPage; /* Index of current page in apPage */
  36673. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  36674. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  36675. };
  36676. /*
  36677. ** Potential values for BtCursor.eState.
  36678. **
  36679. ** CURSOR_INVALID:
  36680. ** Cursor does not point to a valid entry. This can happen (for example)
  36681. ** because the table is empty or because BtreeCursorFirst() has not been
  36682. ** called.
  36683. **
  36684. ** CURSOR_VALID:
  36685. ** Cursor points to a valid entry. getPayload() etc. may be called.
  36686. **
  36687. ** CURSOR_SKIPNEXT:
  36688. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  36689. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  36690. ** operation should be a no-op.
  36691. **
  36692. ** CURSOR_REQUIRESEEK:
  36693. ** The table that this cursor was opened on still exists, but has been
  36694. ** modified since the cursor was last used. The cursor position is saved
  36695. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  36696. ** this state, restoreCursorPosition() can be called to attempt to
  36697. ** seek the cursor to the saved position.
  36698. **
  36699. ** CURSOR_FAULT:
  36700. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  36701. ** on a different connection that shares the BtShared cache with this
  36702. ** cursor. The error has left the cache in an inconsistent state.
  36703. ** Do nothing else with this cursor. Any attempt to use the cursor
  36704. ** should return the error code stored in BtCursor.skip
  36705. */
  36706. #define CURSOR_INVALID 0
  36707. #define CURSOR_VALID 1
  36708. #define CURSOR_SKIPNEXT 2
  36709. #define CURSOR_REQUIRESEEK 3
  36710. #define CURSOR_FAULT 4
  36711. /*
  36712. ** The database page the PENDING_BYTE occupies. This page is never used.
  36713. */
  36714. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  36715. /*
  36716. ** These macros define the location of the pointer-map entry for a
  36717. ** database page. The first argument to each is the number of usable
  36718. ** bytes on each page of the database (often 1024). The second is the
  36719. ** page number to look up in the pointer map.
  36720. **
  36721. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  36722. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  36723. ** the offset of the requested map entry.
  36724. **
  36725. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  36726. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  36727. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  36728. ** this test.
  36729. */
  36730. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  36731. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  36732. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  36733. /*
  36734. ** The pointer map is a lookup table that identifies the parent page for
  36735. ** each child page in the database file. The parent page is the page that
  36736. ** contains a pointer to the child. Every page in the database contains
  36737. ** 0 or 1 parent pages. (In this context 'database page' refers
  36738. ** to any page that is not part of the pointer map itself.) Each pointer map
  36739. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  36740. ** The PTRMAP_XXX identifiers below are the valid types.
  36741. **
  36742. ** The purpose of the pointer map is to facility moving pages from one
  36743. ** position in the file to another as part of autovacuum. When a page
  36744. ** is moved, the pointer in its parent must be updated to point to the
  36745. ** new location. The pointer map is used to locate the parent page quickly.
  36746. **
  36747. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  36748. ** used in this case.
  36749. **
  36750. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  36751. ** is not used in this case.
  36752. **
  36753. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  36754. ** overflow pages. The page number identifies the page that
  36755. ** contains the cell with a pointer to this overflow page.
  36756. **
  36757. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  36758. ** overflow pages. The page-number identifies the previous
  36759. ** page in the overflow page list.
  36760. **
  36761. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  36762. ** identifies the parent page in the btree.
  36763. */
  36764. #define PTRMAP_ROOTPAGE 1
  36765. #define PTRMAP_FREEPAGE 2
  36766. #define PTRMAP_OVERFLOW1 3
  36767. #define PTRMAP_OVERFLOW2 4
  36768. #define PTRMAP_BTREE 5
  36769. /* A bunch of assert() statements to check the transaction state variables
  36770. ** of handle p (type Btree*) are internally consistent.
  36771. */
  36772. #define btreeIntegrity(p) \
  36773. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  36774. assert( p->pBt->inTransaction>=p->inTrans );
  36775. /*
  36776. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  36777. ** if the database supports auto-vacuum or not. Because it is used
  36778. ** within an expression that is an argument to another macro
  36779. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  36780. ** So, this macro is defined instead.
  36781. */
  36782. #ifndef SQLITE_OMIT_AUTOVACUUM
  36783. #define ISAUTOVACUUM (pBt->autoVacuum)
  36784. #else
  36785. #define ISAUTOVACUUM 0
  36786. #endif
  36787. /*
  36788. ** This structure is passed around through all the sanity checking routines
  36789. ** in order to keep track of some global state information.
  36790. **
  36791. ** The aRef[] array is allocated so that there is 1 bit for each page in
  36792. ** the database. As the integrity-check proceeds, for each page used in
  36793. ** the database the corresponding bit is set. This allows integrity-check to
  36794. ** detect pages that are used twice and orphaned pages (both of which
  36795. ** indicate corruption).
  36796. */
  36797. typedef struct IntegrityCk IntegrityCk;
  36798. struct IntegrityCk {
  36799. BtShared *pBt; /* The tree being checked out */
  36800. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  36801. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  36802. Pgno nPage; /* Number of pages in the database */
  36803. int mxErr; /* Stop accumulating errors when this reaches zero */
  36804. int nErr; /* Number of messages written to zErrMsg so far */
  36805. int mallocFailed; /* A memory allocation error has occurred */
  36806. StrAccum errMsg; /* Accumulate the error message text here */
  36807. };
  36808. /*
  36809. ** Routines to read or write a two- and four-byte big-endian integer values.
  36810. */
  36811. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  36812. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  36813. #define get4byte sqlite3Get4byte
  36814. #define put4byte sqlite3Put4byte
  36815. /************** End of btreeInt.h ********************************************/
  36816. /************** Continuing where we left off in btmutex.c ********************/
  36817. #ifndef SQLITE_OMIT_SHARED_CACHE
  36818. #if SQLITE_THREADSAFE
  36819. /*
  36820. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  36821. ** set BtShared.db to the database handle associated with p and the
  36822. ** p->locked boolean to true.
  36823. */
  36824. static void lockBtreeMutex(Btree *p){
  36825. assert( p->locked==0 );
  36826. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  36827. assert( sqlite3_mutex_held(p->db->mutex) );
  36828. sqlite3_mutex_enter(p->pBt->mutex);
  36829. p->pBt->db = p->db;
  36830. p->locked = 1;
  36831. }
  36832. /*
  36833. ** Release the BtShared mutex associated with B-Tree handle p and
  36834. ** clear the p->locked boolean.
  36835. */
  36836. static void unlockBtreeMutex(Btree *p){
  36837. BtShared *pBt = p->pBt;
  36838. assert( p->locked==1 );
  36839. assert( sqlite3_mutex_held(pBt->mutex) );
  36840. assert( sqlite3_mutex_held(p->db->mutex) );
  36841. assert( p->db==pBt->db );
  36842. sqlite3_mutex_leave(pBt->mutex);
  36843. p->locked = 0;
  36844. }
  36845. /*
  36846. ** Enter a mutex on the given BTree object.
  36847. **
  36848. ** If the object is not sharable, then no mutex is ever required
  36849. ** and this routine is a no-op. The underlying mutex is non-recursive.
  36850. ** But we keep a reference count in Btree.wantToLock so the behavior
  36851. ** of this interface is recursive.
  36852. **
  36853. ** To avoid deadlocks, multiple Btrees are locked in the same order
  36854. ** by all database connections. The p->pNext is a list of other
  36855. ** Btrees belonging to the same database connection as the p Btree
  36856. ** which need to be locked after p. If we cannot get a lock on
  36857. ** p, then first unlock all of the others on p->pNext, then wait
  36858. ** for the lock to become available on p, then relock all of the
  36859. ** subsequent Btrees that desire a lock.
  36860. */
  36861. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  36862. Btree *pLater;
  36863. /* Some basic sanity checking on the Btree. The list of Btrees
  36864. ** connected by pNext and pPrev should be in sorted order by
  36865. ** Btree.pBt value. All elements of the list should belong to
  36866. ** the same connection. Only shared Btrees are on the list. */
  36867. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  36868. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  36869. assert( p->pNext==0 || p->pNext->db==p->db );
  36870. assert( p->pPrev==0 || p->pPrev->db==p->db );
  36871. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  36872. /* Check for locking consistency */
  36873. assert( !p->locked || p->wantToLock>0 );
  36874. assert( p->sharable || p->wantToLock==0 );
  36875. /* We should already hold a lock on the database connection */
  36876. assert( sqlite3_mutex_held(p->db->mutex) );
  36877. /* Unless the database is sharable and unlocked, then BtShared.db
  36878. ** should already be set correctly. */
  36879. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  36880. if( !p->sharable ) return;
  36881. p->wantToLock++;
  36882. if( p->locked ) return;
  36883. /* In most cases, we should be able to acquire the lock we
  36884. ** want without having to go throught the ascending lock
  36885. ** procedure that follows. Just be sure not to block.
  36886. */
  36887. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  36888. p->pBt->db = p->db;
  36889. p->locked = 1;
  36890. return;
  36891. }
  36892. /* To avoid deadlock, first release all locks with a larger
  36893. ** BtShared address. Then acquire our lock. Then reacquire
  36894. ** the other BtShared locks that we used to hold in ascending
  36895. ** order.
  36896. */
  36897. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  36898. assert( pLater->sharable );
  36899. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  36900. assert( !pLater->locked || pLater->wantToLock>0 );
  36901. if( pLater->locked ){
  36902. unlockBtreeMutex(pLater);
  36903. }
  36904. }
  36905. lockBtreeMutex(p);
  36906. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  36907. if( pLater->wantToLock ){
  36908. lockBtreeMutex(pLater);
  36909. }
  36910. }
  36911. }
  36912. /*
  36913. ** Exit the recursive mutex on a Btree.
  36914. */
  36915. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  36916. if( p->sharable ){
  36917. assert( p->wantToLock>0 );
  36918. p->wantToLock--;
  36919. if( p->wantToLock==0 ){
  36920. unlockBtreeMutex(p);
  36921. }
  36922. }
  36923. }
  36924. #ifndef NDEBUG
  36925. /*
  36926. ** Return true if the BtShared mutex is held on the btree, or if the
  36927. ** B-Tree is not marked as sharable.
  36928. **
  36929. ** This routine is used only from within assert() statements.
  36930. */
  36931. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  36932. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  36933. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  36934. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  36935. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  36936. return (p->sharable==0 || p->locked);
  36937. }
  36938. #endif
  36939. #ifndef SQLITE_OMIT_INCRBLOB
  36940. /*
  36941. ** Enter and leave a mutex on a Btree given a cursor owned by that
  36942. ** Btree. These entry points are used by incremental I/O and can be
  36943. ** omitted if that module is not used.
  36944. */
  36945. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  36946. sqlite3BtreeEnter(pCur->pBtree);
  36947. }
  36948. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  36949. sqlite3BtreeLeave(pCur->pBtree);
  36950. }
  36951. #endif /* SQLITE_OMIT_INCRBLOB */
  36952. /*
  36953. ** Enter the mutex on every Btree associated with a database
  36954. ** connection. This is needed (for example) prior to parsing
  36955. ** a statement since we will be comparing table and column names
  36956. ** against all schemas and we do not want those schemas being
  36957. ** reset out from under us.
  36958. **
  36959. ** There is a corresponding leave-all procedures.
  36960. **
  36961. ** Enter the mutexes in accending order by BtShared pointer address
  36962. ** to avoid the possibility of deadlock when two threads with
  36963. ** two or more btrees in common both try to lock all their btrees
  36964. ** at the same instant.
  36965. */
  36966. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  36967. int i;
  36968. Btree *p;
  36969. assert( sqlite3_mutex_held(db->mutex) );
  36970. for(i=0; i<db->nDb; i++){
  36971. p = db->aDb[i].pBt;
  36972. if( p ) sqlite3BtreeEnter(p);
  36973. }
  36974. }
  36975. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  36976. int i;
  36977. Btree *p;
  36978. assert( sqlite3_mutex_held(db->mutex) );
  36979. for(i=0; i<db->nDb; i++){
  36980. p = db->aDb[i].pBt;
  36981. if( p ) sqlite3BtreeLeave(p);
  36982. }
  36983. }
  36984. /*
  36985. ** Return true if a particular Btree requires a lock. Return FALSE if
  36986. ** no lock is ever required since it is not sharable.
  36987. */
  36988. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  36989. return p->sharable;
  36990. }
  36991. #ifndef NDEBUG
  36992. /*
  36993. ** Return true if the current thread holds the database connection
  36994. ** mutex and all required BtShared mutexes.
  36995. **
  36996. ** This routine is used inside assert() statements only.
  36997. */
  36998. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  36999. int i;
  37000. if( !sqlite3_mutex_held(db->mutex) ){
  37001. return 0;
  37002. }
  37003. for(i=0; i<db->nDb; i++){
  37004. Btree *p;
  37005. p = db->aDb[i].pBt;
  37006. if( p && p->sharable &&
  37007. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  37008. return 0;
  37009. }
  37010. }
  37011. return 1;
  37012. }
  37013. #endif /* NDEBUG */
  37014. #ifndef NDEBUG
  37015. /*
  37016. ** Return true if the correct mutexes are held for accessing the
  37017. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  37018. ** access are:
  37019. **
  37020. ** (1) The mutex on db
  37021. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  37022. **
  37023. ** If pSchema is not NULL, then iDb is computed from pSchema and
  37024. ** db using sqlite3SchemaToIndex().
  37025. */
  37026. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  37027. Btree *p;
  37028. assert( db!=0 );
  37029. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  37030. assert( iDb>=0 && iDb<db->nDb );
  37031. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  37032. if( iDb==1 ) return 1;
  37033. p = db->aDb[iDb].pBt;
  37034. assert( p!=0 );
  37035. return p->sharable==0 || p->locked==1;
  37036. }
  37037. #endif /* NDEBUG */
  37038. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  37039. /*
  37040. ** The following are special cases for mutex enter routines for use
  37041. ** in single threaded applications that use shared cache. Except for
  37042. ** these two routines, all mutex operations are no-ops in that case and
  37043. ** are null #defines in btree.h.
  37044. **
  37045. ** If shared cache is disabled, then all btree mutex routines, including
  37046. ** the ones below, are no-ops and are null #defines in btree.h.
  37047. */
  37048. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  37049. p->pBt->db = p->db;
  37050. }
  37051. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  37052. int i;
  37053. for(i=0; i<db->nDb; i++){
  37054. Btree *p = db->aDb[i].pBt;
  37055. if( p ){
  37056. p->pBt->db = p->db;
  37057. }
  37058. }
  37059. }
  37060. #endif /* if SQLITE_THREADSAFE */
  37061. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  37062. /************** End of btmutex.c *********************************************/
  37063. /************** Begin file btree.c *******************************************/
  37064. /*
  37065. ** 2004 April 6
  37066. **
  37067. ** The author disclaims copyright to this source code. In place of
  37068. ** a legal notice, here is a blessing:
  37069. **
  37070. ** May you do good and not evil.
  37071. ** May you find forgiveness for yourself and forgive others.
  37072. ** May you share freely, never taking more than you give.
  37073. **
  37074. *************************************************************************
  37075. ** This file implements a external (disk-based) database using BTrees.
  37076. ** See the header comment on "btreeInt.h" for additional information.
  37077. ** Including a description of file format and an overview of operation.
  37078. */
  37079. /*
  37080. ** The header string that appears at the beginning of every
  37081. ** SQLite database.
  37082. */
  37083. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  37084. /*
  37085. ** Set this global variable to 1 to enable tracing using the TRACE
  37086. ** macro.
  37087. */
  37088. #if 0
  37089. int sqlite3BtreeTrace=1; /* True to enable tracing */
  37090. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  37091. #else
  37092. # define TRACE(X)
  37093. #endif
  37094. /*
  37095. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  37096. ** But if the value is zero, make it 65536.
  37097. **
  37098. ** This routine is used to extract the "offset to cell content area" value
  37099. ** from the header of a btree page. If the page size is 65536 and the page
  37100. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  37101. ** This routine makes the necessary adjustment to 65536.
  37102. */
  37103. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  37104. /*
  37105. ** Values passed as the 5th argument to allocateBtreePage()
  37106. */
  37107. #define BTALLOC_ANY 0 /* Allocate any page */
  37108. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  37109. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  37110. /*
  37111. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  37112. ** defined, or 0 if it is. For example:
  37113. **
  37114. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  37115. */
  37116. #ifndef SQLITE_OMIT_AUTOVACUUM
  37117. #define IfNotOmitAV(expr) (expr)
  37118. #else
  37119. #define IfNotOmitAV(expr) 0
  37120. #endif
  37121. #ifndef SQLITE_OMIT_SHARED_CACHE
  37122. /*
  37123. ** A list of BtShared objects that are eligible for participation
  37124. ** in shared cache. This variable has file scope during normal builds,
  37125. ** but the test harness needs to access it so we make it global for
  37126. ** test builds.
  37127. **
  37128. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  37129. */
  37130. #ifdef SQLITE_TEST
  37131. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  37132. #else
  37133. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  37134. #endif
  37135. #endif /* SQLITE_OMIT_SHARED_CACHE */
  37136. #ifndef SQLITE_OMIT_SHARED_CACHE
  37137. /*
  37138. ** Enable or disable the shared pager and schema features.
  37139. **
  37140. ** This routine has no effect on existing database connections.
  37141. ** The shared cache setting effects only future calls to
  37142. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  37143. */
  37144. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  37145. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  37146. return SQLITE_OK;
  37147. }
  37148. #endif
  37149. #ifdef SQLITE_OMIT_SHARED_CACHE
  37150. /*
  37151. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  37152. ** and clearAllSharedCacheTableLocks()
  37153. ** manipulate entries in the BtShared.pLock linked list used to store
  37154. ** shared-cache table level locks. If the library is compiled with the
  37155. ** shared-cache feature disabled, then there is only ever one user
  37156. ** of each BtShared structure and so this locking is not necessary.
  37157. ** So define the lock related functions as no-ops.
  37158. */
  37159. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  37160. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  37161. #define clearAllSharedCacheTableLocks(a)
  37162. #define downgradeAllSharedCacheTableLocks(a)
  37163. #define hasSharedCacheTableLock(a,b,c,d) 1
  37164. #define hasReadConflicts(a, b) 0
  37165. #endif
  37166. #ifndef SQLITE_OMIT_SHARED_CACHE
  37167. #ifdef SQLITE_DEBUG
  37168. /*
  37169. **** This function is only used as part of an assert() statement. ***
  37170. **
  37171. ** Check to see if pBtree holds the required locks to read or write to the
  37172. ** table with root page iRoot. Return 1 if it does and 0 if not.
  37173. **
  37174. ** For example, when writing to a table with root-page iRoot via
  37175. ** Btree connection pBtree:
  37176. **
  37177. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  37178. **
  37179. ** When writing to an index that resides in a sharable database, the
  37180. ** caller should have first obtained a lock specifying the root page of
  37181. ** the corresponding table. This makes things a bit more complicated,
  37182. ** as this module treats each table as a separate structure. To determine
  37183. ** the table corresponding to the index being written, this
  37184. ** function has to search through the database schema.
  37185. **
  37186. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  37187. ** hold a write-lock on the schema table (root page 1). This is also
  37188. ** acceptable.
  37189. */
  37190. static int hasSharedCacheTableLock(
  37191. Btree *pBtree, /* Handle that must hold lock */
  37192. Pgno iRoot, /* Root page of b-tree */
  37193. int isIndex, /* True if iRoot is the root of an index b-tree */
  37194. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  37195. ){
  37196. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  37197. Pgno iTab = 0;
  37198. BtLock *pLock;
  37199. /* If this database is not shareable, or if the client is reading
  37200. ** and has the read-uncommitted flag set, then no lock is required.
  37201. ** Return true immediately.
  37202. */
  37203. if( (pBtree->sharable==0)
  37204. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  37205. ){
  37206. return 1;
  37207. }
  37208. /* If the client is reading or writing an index and the schema is
  37209. ** not loaded, then it is too difficult to actually check to see if
  37210. ** the correct locks are held. So do not bother - just return true.
  37211. ** This case does not come up very often anyhow.
  37212. */
  37213. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  37214. return 1;
  37215. }
  37216. /* Figure out the root-page that the lock should be held on. For table
  37217. ** b-trees, this is just the root page of the b-tree being read or
  37218. ** written. For index b-trees, it is the root page of the associated
  37219. ** table. */
  37220. if( isIndex ){
  37221. HashElem *p;
  37222. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  37223. Index *pIdx = (Index *)sqliteHashData(p);
  37224. if( pIdx->tnum==(int)iRoot ){
  37225. iTab = pIdx->pTable->tnum;
  37226. }
  37227. }
  37228. }else{
  37229. iTab = iRoot;
  37230. }
  37231. /* Search for the required lock. Either a write-lock on root-page iTab, a
  37232. ** write-lock on the schema table, or (if the client is reading) a
  37233. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  37234. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  37235. if( pLock->pBtree==pBtree
  37236. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  37237. && pLock->eLock>=eLockType
  37238. ){
  37239. return 1;
  37240. }
  37241. }
  37242. /* Failed to find the required lock. */
  37243. return 0;
  37244. }
  37245. #endif /* SQLITE_DEBUG */
  37246. #ifdef SQLITE_DEBUG
  37247. /*
  37248. **** This function may be used as part of assert() statements only. ****
  37249. **
  37250. ** Return true if it would be illegal for pBtree to write into the
  37251. ** table or index rooted at iRoot because other shared connections are
  37252. ** simultaneously reading that same table or index.
  37253. **
  37254. ** It is illegal for pBtree to write if some other Btree object that
  37255. ** shares the same BtShared object is currently reading or writing
  37256. ** the iRoot table. Except, if the other Btree object has the
  37257. ** read-uncommitted flag set, then it is OK for the other object to
  37258. ** have a read cursor.
  37259. **
  37260. ** For example, before writing to any part of the table or index
  37261. ** rooted at page iRoot, one should call:
  37262. **
  37263. ** assert( !hasReadConflicts(pBtree, iRoot) );
  37264. */
  37265. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  37266. BtCursor *p;
  37267. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  37268. if( p->pgnoRoot==iRoot
  37269. && p->pBtree!=pBtree
  37270. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  37271. ){
  37272. return 1;
  37273. }
  37274. }
  37275. return 0;
  37276. }
  37277. #endif /* #ifdef SQLITE_DEBUG */
  37278. /*
  37279. ** Query to see if Btree handle p may obtain a lock of type eLock
  37280. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  37281. ** SQLITE_OK if the lock may be obtained (by calling
  37282. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  37283. */
  37284. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  37285. BtShared *pBt = p->pBt;
  37286. BtLock *pIter;
  37287. assert( sqlite3BtreeHoldsMutex(p) );
  37288. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  37289. assert( p->db!=0 );
  37290. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  37291. /* If requesting a write-lock, then the Btree must have an open write
  37292. ** transaction on this file. And, obviously, for this to be so there
  37293. ** must be an open write transaction on the file itself.
  37294. */
  37295. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  37296. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  37297. /* This routine is a no-op if the shared-cache is not enabled */
  37298. if( !p->sharable ){
  37299. return SQLITE_OK;
  37300. }
  37301. /* If some other connection is holding an exclusive lock, the
  37302. ** requested lock may not be obtained.
  37303. */
  37304. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  37305. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  37306. return SQLITE_LOCKED_SHAREDCACHE;
  37307. }
  37308. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  37309. /* The condition (pIter->eLock!=eLock) in the following if(...)
  37310. ** statement is a simplification of:
  37311. **
  37312. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  37313. **
  37314. ** since we know that if eLock==WRITE_LOCK, then no other connection
  37315. ** may hold a WRITE_LOCK on any table in this file (since there can
  37316. ** only be a single writer).
  37317. */
  37318. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  37319. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  37320. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  37321. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  37322. if( eLock==WRITE_LOCK ){
  37323. assert( p==pBt->pWriter );
  37324. pBt->btsFlags |= BTS_PENDING;
  37325. }
  37326. return SQLITE_LOCKED_SHAREDCACHE;
  37327. }
  37328. }
  37329. return SQLITE_OK;
  37330. }
  37331. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  37332. #ifndef SQLITE_OMIT_SHARED_CACHE
  37333. /*
  37334. ** Add a lock on the table with root-page iTable to the shared-btree used
  37335. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  37336. ** WRITE_LOCK.
  37337. **
  37338. ** This function assumes the following:
  37339. **
  37340. ** (a) The specified Btree object p is connected to a sharable
  37341. ** database (one with the BtShared.sharable flag set), and
  37342. **
  37343. ** (b) No other Btree objects hold a lock that conflicts
  37344. ** with the requested lock (i.e. querySharedCacheTableLock() has
  37345. ** already been called and returned SQLITE_OK).
  37346. **
  37347. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  37348. ** is returned if a malloc attempt fails.
  37349. */
  37350. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  37351. BtShared *pBt = p->pBt;
  37352. BtLock *pLock = 0;
  37353. BtLock *pIter;
  37354. assert( sqlite3BtreeHoldsMutex(p) );
  37355. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  37356. assert( p->db!=0 );
  37357. /* A connection with the read-uncommitted flag set will never try to
  37358. ** obtain a read-lock using this function. The only read-lock obtained
  37359. ** by a connection in read-uncommitted mode is on the sqlite_master
  37360. ** table, and that lock is obtained in BtreeBeginTrans(). */
  37361. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  37362. /* This function should only be called on a sharable b-tree after it
  37363. ** has been determined that no other b-tree holds a conflicting lock. */
  37364. assert( p->sharable );
  37365. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  37366. /* First search the list for an existing lock on this table. */
  37367. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  37368. if( pIter->iTable==iTable && pIter->pBtree==p ){
  37369. pLock = pIter;
  37370. break;
  37371. }
  37372. }
  37373. /* If the above search did not find a BtLock struct associating Btree p
  37374. ** with table iTable, allocate one and link it into the list.
  37375. */
  37376. if( !pLock ){
  37377. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  37378. if( !pLock ){
  37379. return SQLITE_NOMEM;
  37380. }
  37381. pLock->iTable = iTable;
  37382. pLock->pBtree = p;
  37383. pLock->pNext = pBt->pLock;
  37384. pBt->pLock = pLock;
  37385. }
  37386. /* Set the BtLock.eLock variable to the maximum of the current lock
  37387. ** and the requested lock. This means if a write-lock was already held
  37388. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  37389. */
  37390. assert( WRITE_LOCK>READ_LOCK );
  37391. if( eLock>pLock->eLock ){
  37392. pLock->eLock = eLock;
  37393. }
  37394. return SQLITE_OK;
  37395. }
  37396. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  37397. #ifndef SQLITE_OMIT_SHARED_CACHE
  37398. /*
  37399. ** Release all the table locks (locks obtained via calls to
  37400. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  37401. **
  37402. ** This function assumes that Btree p has an open read or write
  37403. ** transaction. If it does not, then the BTS_PENDING flag
  37404. ** may be incorrectly cleared.
  37405. */
  37406. static void clearAllSharedCacheTableLocks(Btree *p){
  37407. BtShared *pBt = p->pBt;
  37408. BtLock **ppIter = &pBt->pLock;
  37409. assert( sqlite3BtreeHoldsMutex(p) );
  37410. assert( p->sharable || 0==*ppIter );
  37411. assert( p->inTrans>0 );
  37412. while( *ppIter ){
  37413. BtLock *pLock = *ppIter;
  37414. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  37415. assert( pLock->pBtree->inTrans>=pLock->eLock );
  37416. if( pLock->pBtree==p ){
  37417. *ppIter = pLock->pNext;
  37418. assert( pLock->iTable!=1 || pLock==&p->lock );
  37419. if( pLock->iTable!=1 ){
  37420. sqlite3_free(pLock);
  37421. }
  37422. }else{
  37423. ppIter = &pLock->pNext;
  37424. }
  37425. }
  37426. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  37427. if( pBt->pWriter==p ){
  37428. pBt->pWriter = 0;
  37429. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  37430. }else if( pBt->nTransaction==2 ){
  37431. /* This function is called when Btree p is concluding its
  37432. ** transaction. If there currently exists a writer, and p is not
  37433. ** that writer, then the number of locks held by connections other
  37434. ** than the writer must be about to drop to zero. In this case
  37435. ** set the BTS_PENDING flag to 0.
  37436. **
  37437. ** If there is not currently a writer, then BTS_PENDING must
  37438. ** be zero already. So this next line is harmless in that case.
  37439. */
  37440. pBt->btsFlags &= ~BTS_PENDING;
  37441. }
  37442. }
  37443. /*
  37444. ** This function changes all write-locks held by Btree p into read-locks.
  37445. */
  37446. static void downgradeAllSharedCacheTableLocks(Btree *p){
  37447. BtShared *pBt = p->pBt;
  37448. if( pBt->pWriter==p ){
  37449. BtLock *pLock;
  37450. pBt->pWriter = 0;
  37451. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  37452. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  37453. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  37454. pLock->eLock = READ_LOCK;
  37455. }
  37456. }
  37457. }
  37458. #endif /* SQLITE_OMIT_SHARED_CACHE */
  37459. static void releasePage(MemPage *pPage); /* Forward reference */
  37460. /*
  37461. ***** This routine is used inside of assert() only ****
  37462. **
  37463. ** Verify that the cursor holds the mutex on its BtShared
  37464. */
  37465. #ifdef SQLITE_DEBUG
  37466. static int cursorHoldsMutex(BtCursor *p){
  37467. return sqlite3_mutex_held(p->pBt->mutex);
  37468. }
  37469. #endif
  37470. #ifndef SQLITE_OMIT_INCRBLOB
  37471. /*
  37472. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  37473. */
  37474. static void invalidateOverflowCache(BtCursor *pCur){
  37475. assert( cursorHoldsMutex(pCur) );
  37476. sqlite3_free(pCur->aOverflow);
  37477. pCur->aOverflow = 0;
  37478. }
  37479. /*
  37480. ** Invalidate the overflow page-list cache for all cursors opened
  37481. ** on the shared btree structure pBt.
  37482. */
  37483. static void invalidateAllOverflowCache(BtShared *pBt){
  37484. BtCursor *p;
  37485. assert( sqlite3_mutex_held(pBt->mutex) );
  37486. for(p=pBt->pCursor; p; p=p->pNext){
  37487. invalidateOverflowCache(p);
  37488. }
  37489. }
  37490. /*
  37491. ** This function is called before modifying the contents of a table
  37492. ** to invalidate any incrblob cursors that are open on the
  37493. ** row or one of the rows being modified.
  37494. **
  37495. ** If argument isClearTable is true, then the entire contents of the
  37496. ** table is about to be deleted. In this case invalidate all incrblob
  37497. ** cursors open on any row within the table with root-page pgnoRoot.
  37498. **
  37499. ** Otherwise, if argument isClearTable is false, then the row with
  37500. ** rowid iRow is being replaced or deleted. In this case invalidate
  37501. ** only those incrblob cursors open on that specific row.
  37502. */
  37503. static void invalidateIncrblobCursors(
  37504. Btree *pBtree, /* The database file to check */
  37505. i64 iRow, /* The rowid that might be changing */
  37506. int isClearTable /* True if all rows are being deleted */
  37507. ){
  37508. BtCursor *p;
  37509. BtShared *pBt = pBtree->pBt;
  37510. assert( sqlite3BtreeHoldsMutex(pBtree) );
  37511. for(p=pBt->pCursor; p; p=p->pNext){
  37512. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  37513. p->eState = CURSOR_INVALID;
  37514. }
  37515. }
  37516. }
  37517. #else
  37518. /* Stub functions when INCRBLOB is omitted */
  37519. #define invalidateOverflowCache(x)
  37520. #define invalidateAllOverflowCache(x)
  37521. #define invalidateIncrblobCursors(x,y,z)
  37522. #endif /* SQLITE_OMIT_INCRBLOB */
  37523. /*
  37524. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  37525. ** when a page that previously contained data becomes a free-list leaf
  37526. ** page.
  37527. **
  37528. ** The BtShared.pHasContent bitvec exists to work around an obscure
  37529. ** bug caused by the interaction of two useful IO optimizations surrounding
  37530. ** free-list leaf pages:
  37531. **
  37532. ** 1) When all data is deleted from a page and the page becomes
  37533. ** a free-list leaf page, the page is not written to the database
  37534. ** (as free-list leaf pages contain no meaningful data). Sometimes
  37535. ** such a page is not even journalled (as it will not be modified,
  37536. ** why bother journalling it?).
  37537. **
  37538. ** 2) When a free-list leaf page is reused, its content is not read
  37539. ** from the database or written to the journal file (why should it
  37540. ** be, if it is not at all meaningful?).
  37541. **
  37542. ** By themselves, these optimizations work fine and provide a handy
  37543. ** performance boost to bulk delete or insert operations. However, if
  37544. ** a page is moved to the free-list and then reused within the same
  37545. ** transaction, a problem comes up. If the page is not journalled when
  37546. ** it is moved to the free-list and it is also not journalled when it
  37547. ** is extracted from the free-list and reused, then the original data
  37548. ** may be lost. In the event of a rollback, it may not be possible
  37549. ** to restore the database to its original configuration.
  37550. **
  37551. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  37552. ** moved to become a free-list leaf page, the corresponding bit is
  37553. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  37554. ** optimization 2 above is omitted if the corresponding bit is already
  37555. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  37556. ** at the end of every transaction.
  37557. */
  37558. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  37559. int rc = SQLITE_OK;
  37560. if( !pBt->pHasContent ){
  37561. assert( pgno<=pBt->nPage );
  37562. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  37563. if( !pBt->pHasContent ){
  37564. rc = SQLITE_NOMEM;
  37565. }
  37566. }
  37567. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  37568. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  37569. }
  37570. return rc;
  37571. }
  37572. /*
  37573. ** Query the BtShared.pHasContent vector.
  37574. **
  37575. ** This function is called when a free-list leaf page is removed from the
  37576. ** free-list for reuse. It returns false if it is safe to retrieve the
  37577. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  37578. */
  37579. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  37580. Bitvec *p = pBt->pHasContent;
  37581. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  37582. }
  37583. /*
  37584. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  37585. ** invoked at the conclusion of each write-transaction.
  37586. */
  37587. static void btreeClearHasContent(BtShared *pBt){
  37588. sqlite3BitvecDestroy(pBt->pHasContent);
  37589. pBt->pHasContent = 0;
  37590. }
  37591. /*
  37592. ** Release all of the apPage[] pages for a cursor.
  37593. */
  37594. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  37595. int i;
  37596. for(i=0; i<=pCur->iPage; i++){
  37597. releasePage(pCur->apPage[i]);
  37598. pCur->apPage[i] = 0;
  37599. }
  37600. pCur->iPage = -1;
  37601. }
  37602. /*
  37603. ** Save the current cursor position in the variables BtCursor.nKey
  37604. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  37605. **
  37606. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  37607. ** prior to calling this routine.
  37608. */
  37609. static int saveCursorPosition(BtCursor *pCur){
  37610. int rc;
  37611. assert( CURSOR_VALID==pCur->eState );
  37612. assert( 0==pCur->pKey );
  37613. assert( cursorHoldsMutex(pCur) );
  37614. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  37615. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  37616. /* If this is an intKey table, then the above call to BtreeKeySize()
  37617. ** stores the integer key in pCur->nKey. In this case this value is
  37618. ** all that is required. Otherwise, if pCur is not open on an intKey
  37619. ** table, then malloc space for and store the pCur->nKey bytes of key
  37620. ** data.
  37621. */
  37622. if( 0==pCur->apPage[0]->intKey ){
  37623. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  37624. if( pKey ){
  37625. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  37626. if( rc==SQLITE_OK ){
  37627. pCur->pKey = pKey;
  37628. }else{
  37629. sqlite3_free(pKey);
  37630. }
  37631. }else{
  37632. rc = SQLITE_NOMEM;
  37633. }
  37634. }
  37635. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  37636. if( rc==SQLITE_OK ){
  37637. btreeReleaseAllCursorPages(pCur);
  37638. pCur->eState = CURSOR_REQUIRESEEK;
  37639. }
  37640. invalidateOverflowCache(pCur);
  37641. return rc;
  37642. }
  37643. /*
  37644. ** Save the positions of all cursors (except pExcept) that are open on
  37645. ** the table with root-page iRoot. Usually, this is called just before cursor
  37646. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  37647. */
  37648. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  37649. BtCursor *p;
  37650. assert( sqlite3_mutex_held(pBt->mutex) );
  37651. assert( pExcept==0 || pExcept->pBt==pBt );
  37652. for(p=pBt->pCursor; p; p=p->pNext){
  37653. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  37654. if( p->eState==CURSOR_VALID ){
  37655. int rc = saveCursorPosition(p);
  37656. if( SQLITE_OK!=rc ){
  37657. return rc;
  37658. }
  37659. }else{
  37660. testcase( p->iPage>0 );
  37661. btreeReleaseAllCursorPages(p);
  37662. }
  37663. }
  37664. }
  37665. return SQLITE_OK;
  37666. }
  37667. /*
  37668. ** Clear the current cursor position.
  37669. */
  37670. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  37671. assert( cursorHoldsMutex(pCur) );
  37672. sqlite3_free(pCur->pKey);
  37673. pCur->pKey = 0;
  37674. pCur->eState = CURSOR_INVALID;
  37675. }
  37676. /*
  37677. ** In this version of BtreeMoveto, pKey is a packed index record
  37678. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  37679. ** record and then call BtreeMovetoUnpacked() to do the work.
  37680. */
  37681. static int btreeMoveto(
  37682. BtCursor *pCur, /* Cursor open on the btree to be searched */
  37683. const void *pKey, /* Packed key if the btree is an index */
  37684. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  37685. int bias, /* Bias search to the high end */
  37686. int *pRes /* Write search results here */
  37687. ){
  37688. int rc; /* Status code */
  37689. UnpackedRecord *pIdxKey; /* Unpacked index key */
  37690. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  37691. char *pFree = 0;
  37692. if( pKey ){
  37693. assert( nKey==(i64)(int)nKey );
  37694. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  37695. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  37696. );
  37697. if( pIdxKey==0 ) return SQLITE_NOMEM;
  37698. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  37699. }else{
  37700. pIdxKey = 0;
  37701. }
  37702. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  37703. if( pFree ){
  37704. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  37705. }
  37706. return rc;
  37707. }
  37708. /*
  37709. ** Restore the cursor to the position it was in (or as close to as possible)
  37710. ** when saveCursorPosition() was called. Note that this call deletes the
  37711. ** saved position info stored by saveCursorPosition(), so there can be
  37712. ** at most one effective restoreCursorPosition() call after each
  37713. ** saveCursorPosition().
  37714. */
  37715. static int btreeRestoreCursorPosition(BtCursor *pCur){
  37716. int rc;
  37717. assert( cursorHoldsMutex(pCur) );
  37718. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  37719. if( pCur->eState==CURSOR_FAULT ){
  37720. return pCur->skipNext;
  37721. }
  37722. pCur->eState = CURSOR_INVALID;
  37723. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  37724. if( rc==SQLITE_OK ){
  37725. sqlite3_free(pCur->pKey);
  37726. pCur->pKey = 0;
  37727. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  37728. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  37729. pCur->eState = CURSOR_SKIPNEXT;
  37730. }
  37731. }
  37732. return rc;
  37733. }
  37734. #define restoreCursorPosition(p) \
  37735. (p->eState>=CURSOR_REQUIRESEEK ? \
  37736. btreeRestoreCursorPosition(p) : \
  37737. SQLITE_OK)
  37738. /*
  37739. ** Determine whether or not a cursor has moved from the position it
  37740. ** was last placed at. Cursors can move when the row they are pointing
  37741. ** at is deleted out from under them.
  37742. **
  37743. ** This routine returns an error code if something goes wrong. The
  37744. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  37745. */
  37746. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  37747. int rc;
  37748. rc = restoreCursorPosition(pCur);
  37749. if( rc ){
  37750. *pHasMoved = 1;
  37751. return rc;
  37752. }
  37753. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  37754. *pHasMoved = 1;
  37755. }else{
  37756. *pHasMoved = 0;
  37757. }
  37758. return SQLITE_OK;
  37759. }
  37760. #ifndef SQLITE_OMIT_AUTOVACUUM
  37761. /*
  37762. ** Given a page number of a regular database page, return the page
  37763. ** number for the pointer-map page that contains the entry for the
  37764. ** input page number.
  37765. **
  37766. ** Return 0 (not a valid page) for pgno==1 since there is
  37767. ** no pointer map associated with page 1. The integrity_check logic
  37768. ** requires that ptrmapPageno(*,1)!=1.
  37769. */
  37770. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  37771. int nPagesPerMapPage;
  37772. Pgno iPtrMap, ret;
  37773. assert( sqlite3_mutex_held(pBt->mutex) );
  37774. if( pgno<2 ) return 0;
  37775. nPagesPerMapPage = (pBt->usableSize/5)+1;
  37776. iPtrMap = (pgno-2)/nPagesPerMapPage;
  37777. ret = (iPtrMap*nPagesPerMapPage) + 2;
  37778. if( ret==PENDING_BYTE_PAGE(pBt) ){
  37779. ret++;
  37780. }
  37781. return ret;
  37782. }
  37783. /*
  37784. ** Write an entry into the pointer map.
  37785. **
  37786. ** This routine updates the pointer map entry for page number 'key'
  37787. ** so that it maps to type 'eType' and parent page number 'pgno'.
  37788. **
  37789. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  37790. ** a no-op. If an error occurs, the appropriate error code is written
  37791. ** into *pRC.
  37792. */
  37793. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  37794. DbPage *pDbPage; /* The pointer map page */
  37795. u8 *pPtrmap; /* The pointer map data */
  37796. Pgno iPtrmap; /* The pointer map page number */
  37797. int offset; /* Offset in pointer map page */
  37798. int rc; /* Return code from subfunctions */
  37799. if( *pRC ) return;
  37800. assert( sqlite3_mutex_held(pBt->mutex) );
  37801. /* The master-journal page number must never be used as a pointer map page */
  37802. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  37803. assert( pBt->autoVacuum );
  37804. if( key==0 ){
  37805. *pRC = SQLITE_CORRUPT_BKPT;
  37806. return;
  37807. }
  37808. iPtrmap = PTRMAP_PAGENO(pBt, key);
  37809. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  37810. if( rc!=SQLITE_OK ){
  37811. *pRC = rc;
  37812. return;
  37813. }
  37814. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  37815. if( offset<0 ){
  37816. *pRC = SQLITE_CORRUPT_BKPT;
  37817. goto ptrmap_exit;
  37818. }
  37819. assert( offset <= (int)pBt->usableSize-5 );
  37820. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  37821. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  37822. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  37823. *pRC= rc = sqlite3PagerWrite(pDbPage);
  37824. if( rc==SQLITE_OK ){
  37825. pPtrmap[offset] = eType;
  37826. put4byte(&pPtrmap[offset+1], parent);
  37827. }
  37828. }
  37829. ptrmap_exit:
  37830. sqlite3PagerUnref(pDbPage);
  37831. }
  37832. /*
  37833. ** Read an entry from the pointer map.
  37834. **
  37835. ** This routine retrieves the pointer map entry for page 'key', writing
  37836. ** the type and parent page number to *pEType and *pPgno respectively.
  37837. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  37838. */
  37839. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  37840. DbPage *pDbPage; /* The pointer map page */
  37841. int iPtrmap; /* Pointer map page index */
  37842. u8 *pPtrmap; /* Pointer map page data */
  37843. int offset; /* Offset of entry in pointer map */
  37844. int rc;
  37845. assert( sqlite3_mutex_held(pBt->mutex) );
  37846. iPtrmap = PTRMAP_PAGENO(pBt, key);
  37847. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  37848. if( rc!=0 ){
  37849. return rc;
  37850. }
  37851. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  37852. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  37853. if( offset<0 ){
  37854. sqlite3PagerUnref(pDbPage);
  37855. return SQLITE_CORRUPT_BKPT;
  37856. }
  37857. assert( offset <= (int)pBt->usableSize-5 );
  37858. assert( pEType!=0 );
  37859. *pEType = pPtrmap[offset];
  37860. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  37861. sqlite3PagerUnref(pDbPage);
  37862. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  37863. return SQLITE_OK;
  37864. }
  37865. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  37866. #define ptrmapPut(w,x,y,z,rc)
  37867. #define ptrmapGet(w,x,y,z) SQLITE_OK
  37868. #define ptrmapPutOvflPtr(x, y, rc)
  37869. #endif
  37870. /*
  37871. ** Given a btree page and a cell index (0 means the first cell on
  37872. ** the page, 1 means the second cell, and so forth) return a pointer
  37873. ** to the cell content.
  37874. **
  37875. ** This routine works only for pages that do not contain overflow cells.
  37876. */
  37877. #define findCell(P,I) \
  37878. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  37879. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  37880. /*
  37881. ** This a more complex version of findCell() that works for
  37882. ** pages that do contain overflow cells.
  37883. */
  37884. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  37885. int i;
  37886. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  37887. for(i=pPage->nOverflow-1; i>=0; i--){
  37888. int k;
  37889. k = pPage->aiOvfl[i];
  37890. if( k<=iCell ){
  37891. if( k==iCell ){
  37892. return pPage->apOvfl[i];
  37893. }
  37894. iCell--;
  37895. }
  37896. }
  37897. return findCell(pPage, iCell);
  37898. }
  37899. /*
  37900. ** Parse a cell content block and fill in the CellInfo structure. There
  37901. ** are two versions of this function. btreeParseCell() takes a
  37902. ** cell index as the second argument and btreeParseCellPtr()
  37903. ** takes a pointer to the body of the cell as its second argument.
  37904. **
  37905. ** Within this file, the parseCell() macro can be called instead of
  37906. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  37907. */
  37908. static void btreeParseCellPtr(
  37909. MemPage *pPage, /* Page containing the cell */
  37910. u8 *pCell, /* Pointer to the cell text. */
  37911. CellInfo *pInfo /* Fill in this structure */
  37912. ){
  37913. u16 n; /* Number bytes in cell content header */
  37914. u32 nPayload; /* Number of bytes of cell payload */
  37915. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  37916. pInfo->pCell = pCell;
  37917. assert( pPage->leaf==0 || pPage->leaf==1 );
  37918. n = pPage->childPtrSize;
  37919. assert( n==4-4*pPage->leaf );
  37920. if( pPage->intKey ){
  37921. if( pPage->hasData ){
  37922. assert( n==0 );
  37923. n = getVarint32(pCell, nPayload);
  37924. }else{
  37925. nPayload = 0;
  37926. }
  37927. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  37928. pInfo->nData = nPayload;
  37929. }else{
  37930. pInfo->nData = 0;
  37931. n += getVarint32(&pCell[n], nPayload);
  37932. pInfo->nKey = nPayload;
  37933. }
  37934. pInfo->nPayload = nPayload;
  37935. pInfo->nHeader = n;
  37936. testcase( nPayload==pPage->maxLocal );
  37937. testcase( nPayload==pPage->maxLocal+1 );
  37938. if( likely(nPayload<=pPage->maxLocal) ){
  37939. /* This is the (easy) common case where the entire payload fits
  37940. ** on the local page. No overflow is required.
  37941. */
  37942. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  37943. pInfo->nLocal = (u16)nPayload;
  37944. pInfo->iOverflow = 0;
  37945. }else{
  37946. /* If the payload will not fit completely on the local page, we have
  37947. ** to decide how much to store locally and how much to spill onto
  37948. ** overflow pages. The strategy is to minimize the amount of unused
  37949. ** space on overflow pages while keeping the amount of local storage
  37950. ** in between minLocal and maxLocal.
  37951. **
  37952. ** Warning: changing the way overflow payload is distributed in any
  37953. ** way will result in an incompatible file format.
  37954. */
  37955. int minLocal; /* Minimum amount of payload held locally */
  37956. int maxLocal; /* Maximum amount of payload held locally */
  37957. int surplus; /* Overflow payload available for local storage */
  37958. minLocal = pPage->minLocal;
  37959. maxLocal = pPage->maxLocal;
  37960. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  37961. testcase( surplus==maxLocal );
  37962. testcase( surplus==maxLocal+1 );
  37963. if( surplus <= maxLocal ){
  37964. pInfo->nLocal = (u16)surplus;
  37965. }else{
  37966. pInfo->nLocal = (u16)minLocal;
  37967. }
  37968. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  37969. pInfo->nSize = pInfo->iOverflow + 4;
  37970. }
  37971. }
  37972. #define parseCell(pPage, iCell, pInfo) \
  37973. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  37974. static void btreeParseCell(
  37975. MemPage *pPage, /* Page containing the cell */
  37976. int iCell, /* The cell index. First cell is 0 */
  37977. CellInfo *pInfo /* Fill in this structure */
  37978. ){
  37979. parseCell(pPage, iCell, pInfo);
  37980. }
  37981. /*
  37982. ** Compute the total number of bytes that a Cell needs in the cell
  37983. ** data area of the btree-page. The return number includes the cell
  37984. ** data header and the local payload, but not any overflow page or
  37985. ** the space used by the cell pointer.
  37986. */
  37987. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  37988. u8 *pIter = &pCell[pPage->childPtrSize];
  37989. u32 nSize;
  37990. #ifdef SQLITE_DEBUG
  37991. /* The value returned by this function should always be the same as
  37992. ** the (CellInfo.nSize) value found by doing a full parse of the
  37993. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  37994. ** this function verifies that this invariant is not violated. */
  37995. CellInfo debuginfo;
  37996. btreeParseCellPtr(pPage, pCell, &debuginfo);
  37997. #endif
  37998. if( pPage->intKey ){
  37999. u8 *pEnd;
  38000. if( pPage->hasData ){
  38001. pIter += getVarint32(pIter, nSize);
  38002. }else{
  38003. nSize = 0;
  38004. }
  38005. /* pIter now points at the 64-bit integer key value, a variable length
  38006. ** integer. The following block moves pIter to point at the first byte
  38007. ** past the end of the key value. */
  38008. pEnd = &pIter[9];
  38009. while( (*pIter++)&0x80 && pIter<pEnd );
  38010. }else{
  38011. pIter += getVarint32(pIter, nSize);
  38012. }
  38013. testcase( nSize==pPage->maxLocal );
  38014. testcase( nSize==pPage->maxLocal+1 );
  38015. if( nSize>pPage->maxLocal ){
  38016. int minLocal = pPage->minLocal;
  38017. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  38018. testcase( nSize==pPage->maxLocal );
  38019. testcase( nSize==pPage->maxLocal+1 );
  38020. if( nSize>pPage->maxLocal ){
  38021. nSize = minLocal;
  38022. }
  38023. nSize += 4;
  38024. }
  38025. nSize += (u32)(pIter - pCell);
  38026. /* The minimum size of any cell is 4 bytes. */
  38027. if( nSize<4 ){
  38028. nSize = 4;
  38029. }
  38030. assert( nSize==debuginfo.nSize );
  38031. return (u16)nSize;
  38032. }
  38033. #ifdef SQLITE_DEBUG
  38034. /* This variation on cellSizePtr() is used inside of assert() statements
  38035. ** only. */
  38036. static u16 cellSize(MemPage *pPage, int iCell){
  38037. return cellSizePtr(pPage, findCell(pPage, iCell));
  38038. }
  38039. #endif
  38040. #ifndef SQLITE_OMIT_AUTOVACUUM
  38041. /*
  38042. ** If the cell pCell, part of page pPage contains a pointer
  38043. ** to an overflow page, insert an entry into the pointer-map
  38044. ** for the overflow page.
  38045. */
  38046. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  38047. CellInfo info;
  38048. if( *pRC ) return;
  38049. assert( pCell!=0 );
  38050. btreeParseCellPtr(pPage, pCell, &info);
  38051. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  38052. if( info.iOverflow ){
  38053. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  38054. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  38055. }
  38056. }
  38057. #endif
  38058. /*
  38059. ** Defragment the page given. All Cells are moved to the
  38060. ** end of the page and all free space is collected into one
  38061. ** big FreeBlk that occurs in between the header and cell
  38062. ** pointer array and the cell content area.
  38063. */
  38064. static int defragmentPage(MemPage *pPage){
  38065. int i; /* Loop counter */
  38066. int pc; /* Address of a i-th cell */
  38067. int hdr; /* Offset to the page header */
  38068. int size; /* Size of a cell */
  38069. int usableSize; /* Number of usable bytes on a page */
  38070. int cellOffset; /* Offset to the cell pointer array */
  38071. int cbrk; /* Offset to the cell content area */
  38072. int nCell; /* Number of cells on the page */
  38073. unsigned char *data; /* The page data */
  38074. unsigned char *temp; /* Temp area for cell content */
  38075. int iCellFirst; /* First allowable cell index */
  38076. int iCellLast; /* Last possible cell index */
  38077. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38078. assert( pPage->pBt!=0 );
  38079. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  38080. assert( pPage->nOverflow==0 );
  38081. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38082. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  38083. data = pPage->aData;
  38084. hdr = pPage->hdrOffset;
  38085. cellOffset = pPage->cellOffset;
  38086. nCell = pPage->nCell;
  38087. assert( nCell==get2byte(&data[hdr+3]) );
  38088. usableSize = pPage->pBt->usableSize;
  38089. cbrk = get2byte(&data[hdr+5]);
  38090. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  38091. cbrk = usableSize;
  38092. iCellFirst = cellOffset + 2*nCell;
  38093. iCellLast = usableSize - 4;
  38094. for(i=0; i<nCell; i++){
  38095. u8 *pAddr; /* The i-th cell pointer */
  38096. pAddr = &data[cellOffset + i*2];
  38097. pc = get2byte(pAddr);
  38098. testcase( pc==iCellFirst );
  38099. testcase( pc==iCellLast );
  38100. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38101. /* These conditions have already been verified in btreeInitPage()
  38102. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  38103. */
  38104. if( pc<iCellFirst || pc>iCellLast ){
  38105. return SQLITE_CORRUPT_BKPT;
  38106. }
  38107. #endif
  38108. assert( pc>=iCellFirst && pc<=iCellLast );
  38109. size = cellSizePtr(pPage, &temp[pc]);
  38110. cbrk -= size;
  38111. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38112. if( cbrk<iCellFirst ){
  38113. return SQLITE_CORRUPT_BKPT;
  38114. }
  38115. #else
  38116. if( cbrk<iCellFirst || pc+size>usableSize ){
  38117. return SQLITE_CORRUPT_BKPT;
  38118. }
  38119. #endif
  38120. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  38121. testcase( cbrk+size==usableSize );
  38122. testcase( pc+size==usableSize );
  38123. memcpy(&data[cbrk], &temp[pc], size);
  38124. put2byte(pAddr, cbrk);
  38125. }
  38126. assert( cbrk>=iCellFirst );
  38127. put2byte(&data[hdr+5], cbrk);
  38128. data[hdr+1] = 0;
  38129. data[hdr+2] = 0;
  38130. data[hdr+7] = 0;
  38131. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  38132. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38133. if( cbrk-iCellFirst!=pPage->nFree ){
  38134. return SQLITE_CORRUPT_BKPT;
  38135. }
  38136. return SQLITE_OK;
  38137. }
  38138. /*
  38139. ** Allocate nByte bytes of space from within the B-Tree page passed
  38140. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  38141. ** of the first byte of allocated space. Return either SQLITE_OK or
  38142. ** an error code (usually SQLITE_CORRUPT).
  38143. **
  38144. ** The caller guarantees that there is sufficient space to make the
  38145. ** allocation. This routine might need to defragment in order to bring
  38146. ** all the space together, however. This routine will avoid using
  38147. ** the first two bytes past the cell pointer area since presumably this
  38148. ** allocation is being made in order to insert a new cell, so we will
  38149. ** also end up needing a new cell pointer.
  38150. */
  38151. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  38152. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  38153. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  38154. int nFrag; /* Number of fragmented bytes on pPage */
  38155. int top; /* First byte of cell content area */
  38156. int gap; /* First byte of gap between cell pointers and cell content */
  38157. int rc; /* Integer return code */
  38158. int usableSize; /* Usable size of the page */
  38159. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38160. assert( pPage->pBt );
  38161. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38162. assert( nByte>=0 ); /* Minimum cell size is 4 */
  38163. assert( pPage->nFree>=nByte );
  38164. assert( pPage->nOverflow==0 );
  38165. usableSize = pPage->pBt->usableSize;
  38166. assert( nByte < usableSize-8 );
  38167. nFrag = data[hdr+7];
  38168. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  38169. gap = pPage->cellOffset + 2*pPage->nCell;
  38170. top = get2byteNotZero(&data[hdr+5]);
  38171. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  38172. testcase( gap+2==top );
  38173. testcase( gap+1==top );
  38174. testcase( gap==top );
  38175. if( nFrag>=60 ){
  38176. /* Always defragment highly fragmented pages */
  38177. rc = defragmentPage(pPage);
  38178. if( rc ) return rc;
  38179. top = get2byteNotZero(&data[hdr+5]);
  38180. }else if( gap+2<=top ){
  38181. /* Search the freelist looking for a free slot big enough to satisfy
  38182. ** the request. The allocation is made from the first free slot in
  38183. ** the list that is large enough to accommodate it.
  38184. */
  38185. int pc, addr;
  38186. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  38187. int size; /* Size of the free slot */
  38188. if( pc>usableSize-4 || pc<addr+4 ){
  38189. return SQLITE_CORRUPT_BKPT;
  38190. }
  38191. size = get2byte(&data[pc+2]);
  38192. if( size>=nByte ){
  38193. int x = size - nByte;
  38194. testcase( x==4 );
  38195. testcase( x==3 );
  38196. if( x<4 ){
  38197. /* Remove the slot from the free-list. Update the number of
  38198. ** fragmented bytes within the page. */
  38199. memcpy(&data[addr], &data[pc], 2);
  38200. data[hdr+7] = (u8)(nFrag + x);
  38201. }else if( size+pc > usableSize ){
  38202. return SQLITE_CORRUPT_BKPT;
  38203. }else{
  38204. /* The slot remains on the free-list. Reduce its size to account
  38205. ** for the portion used by the new allocation. */
  38206. put2byte(&data[pc+2], x);
  38207. }
  38208. *pIdx = pc + x;
  38209. return SQLITE_OK;
  38210. }
  38211. }
  38212. }
  38213. /* Check to make sure there is enough space in the gap to satisfy
  38214. ** the allocation. If not, defragment.
  38215. */
  38216. testcase( gap+2+nByte==top );
  38217. if( gap+2+nByte>top ){
  38218. rc = defragmentPage(pPage);
  38219. if( rc ) return rc;
  38220. top = get2byteNotZero(&data[hdr+5]);
  38221. assert( gap+nByte<=top );
  38222. }
  38223. /* Allocate memory from the gap in between the cell pointer array
  38224. ** and the cell content area. The btreeInitPage() call has already
  38225. ** validated the freelist. Given that the freelist is valid, there
  38226. ** is no way that the allocation can extend off the end of the page.
  38227. ** The assert() below verifies the previous sentence.
  38228. */
  38229. top -= nByte;
  38230. put2byte(&data[hdr+5], top);
  38231. assert( top+nByte <= (int)pPage->pBt->usableSize );
  38232. *pIdx = top;
  38233. return SQLITE_OK;
  38234. }
  38235. /*
  38236. ** Return a section of the pPage->aData to the freelist.
  38237. ** The first byte of the new free block is pPage->aDisk[start]
  38238. ** and the size of the block is "size" bytes.
  38239. **
  38240. ** Most of the effort here is involved in coalesing adjacent
  38241. ** free blocks into a single big free block.
  38242. */
  38243. static int freeSpace(MemPage *pPage, int start, int size){
  38244. int addr, pbegin, hdr;
  38245. int iLast; /* Largest possible freeblock offset */
  38246. unsigned char *data = pPage->aData;
  38247. assert( pPage->pBt!=0 );
  38248. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38249. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  38250. assert( (start + size) <= (int)pPage->pBt->usableSize );
  38251. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38252. assert( size>=0 ); /* Minimum cell size is 4 */
  38253. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  38254. /* Overwrite deleted information with zeros when the secure_delete
  38255. ** option is enabled */
  38256. memset(&data[start], 0, size);
  38257. }
  38258. /* Add the space back into the linked list of freeblocks. Note that
  38259. ** even though the freeblock list was checked by btreeInitPage(),
  38260. ** btreeInitPage() did not detect overlapping cells or
  38261. ** freeblocks that overlapped cells. Nor does it detect when the
  38262. ** cell content area exceeds the value in the page header. If these
  38263. ** situations arise, then subsequent insert operations might corrupt
  38264. ** the freelist. So we do need to check for corruption while scanning
  38265. ** the freelist.
  38266. */
  38267. hdr = pPage->hdrOffset;
  38268. addr = hdr + 1;
  38269. iLast = pPage->pBt->usableSize - 4;
  38270. assert( start<=iLast );
  38271. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  38272. if( pbegin<addr+4 ){
  38273. return SQLITE_CORRUPT_BKPT;
  38274. }
  38275. addr = pbegin;
  38276. }
  38277. if( pbegin>iLast ){
  38278. return SQLITE_CORRUPT_BKPT;
  38279. }
  38280. assert( pbegin>addr || pbegin==0 );
  38281. put2byte(&data[addr], start);
  38282. put2byte(&data[start], pbegin);
  38283. put2byte(&data[start+2], size);
  38284. pPage->nFree = pPage->nFree + (u16)size;
  38285. /* Coalesce adjacent free blocks */
  38286. addr = hdr + 1;
  38287. while( (pbegin = get2byte(&data[addr]))>0 ){
  38288. int pnext, psize, x;
  38289. assert( pbegin>addr );
  38290. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  38291. pnext = get2byte(&data[pbegin]);
  38292. psize = get2byte(&data[pbegin+2]);
  38293. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  38294. int frag = pnext - (pbegin+psize);
  38295. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  38296. return SQLITE_CORRUPT_BKPT;
  38297. }
  38298. data[hdr+7] -= (u8)frag;
  38299. x = get2byte(&data[pnext]);
  38300. put2byte(&data[pbegin], x);
  38301. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  38302. put2byte(&data[pbegin+2], x);
  38303. }else{
  38304. addr = pbegin;
  38305. }
  38306. }
  38307. /* If the cell content area begins with a freeblock, remove it. */
  38308. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  38309. int top;
  38310. pbegin = get2byte(&data[hdr+1]);
  38311. memcpy(&data[hdr+1], &data[pbegin], 2);
  38312. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  38313. put2byte(&data[hdr+5], top);
  38314. }
  38315. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38316. return SQLITE_OK;
  38317. }
  38318. /*
  38319. ** Decode the flags byte (the first byte of the header) for a page
  38320. ** and initialize fields of the MemPage structure accordingly.
  38321. **
  38322. ** Only the following combinations are supported. Anything different
  38323. ** indicates a corrupt database files:
  38324. **
  38325. ** PTF_ZERODATA
  38326. ** PTF_ZERODATA | PTF_LEAF
  38327. ** PTF_LEAFDATA | PTF_INTKEY
  38328. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  38329. */
  38330. static int decodeFlags(MemPage *pPage, int flagByte){
  38331. BtShared *pBt; /* A copy of pPage->pBt */
  38332. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  38333. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38334. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  38335. flagByte &= ~PTF_LEAF;
  38336. pPage->childPtrSize = 4-4*pPage->leaf;
  38337. pBt = pPage->pBt;
  38338. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  38339. pPage->intKey = 1;
  38340. pPage->hasData = pPage->leaf;
  38341. pPage->maxLocal = pBt->maxLeaf;
  38342. pPage->minLocal = pBt->minLeaf;
  38343. }else if( flagByte==PTF_ZERODATA ){
  38344. pPage->intKey = 0;
  38345. pPage->hasData = 0;
  38346. pPage->maxLocal = pBt->maxLocal;
  38347. pPage->minLocal = pBt->minLocal;
  38348. }else{
  38349. return SQLITE_CORRUPT_BKPT;
  38350. }
  38351. pPage->max1bytePayload = pBt->max1bytePayload;
  38352. return SQLITE_OK;
  38353. }
  38354. /*
  38355. ** Initialize the auxiliary information for a disk block.
  38356. **
  38357. ** Return SQLITE_OK on success. If we see that the page does
  38358. ** not contain a well-formed database page, then return
  38359. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  38360. ** guarantee that the page is well-formed. It only shows that
  38361. ** we failed to detect any corruption.
  38362. */
  38363. static int btreeInitPage(MemPage *pPage){
  38364. assert( pPage->pBt!=0 );
  38365. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38366. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  38367. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  38368. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  38369. if( !pPage->isInit ){
  38370. u16 pc; /* Address of a freeblock within pPage->aData[] */
  38371. u8 hdr; /* Offset to beginning of page header */
  38372. u8 *data; /* Equal to pPage->aData */
  38373. BtShared *pBt; /* The main btree structure */
  38374. int usableSize; /* Amount of usable space on each page */
  38375. u16 cellOffset; /* Offset from start of page to first cell pointer */
  38376. int nFree; /* Number of unused bytes on the page */
  38377. int top; /* First byte of the cell content area */
  38378. int iCellFirst; /* First allowable cell or freeblock offset */
  38379. int iCellLast; /* Last possible cell or freeblock offset */
  38380. pBt = pPage->pBt;
  38381. hdr = pPage->hdrOffset;
  38382. data = pPage->aData;
  38383. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  38384. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  38385. pPage->maskPage = (u16)(pBt->pageSize - 1);
  38386. pPage->nOverflow = 0;
  38387. usableSize = pBt->usableSize;
  38388. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  38389. pPage->aDataEnd = &data[usableSize];
  38390. pPage->aCellIdx = &data[cellOffset];
  38391. top = get2byteNotZero(&data[hdr+5]);
  38392. pPage->nCell = get2byte(&data[hdr+3]);
  38393. if( pPage->nCell>MX_CELL(pBt) ){
  38394. /* To many cells for a single page. The page must be corrupt */
  38395. return SQLITE_CORRUPT_BKPT;
  38396. }
  38397. testcase( pPage->nCell==MX_CELL(pBt) );
  38398. /* A malformed database page might cause us to read past the end
  38399. ** of page when parsing a cell.
  38400. **
  38401. ** The following block of code checks early to see if a cell extends
  38402. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  38403. ** returned if it does.
  38404. */
  38405. iCellFirst = cellOffset + 2*pPage->nCell;
  38406. iCellLast = usableSize - 4;
  38407. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38408. {
  38409. int i; /* Index into the cell pointer array */
  38410. int sz; /* Size of a cell */
  38411. if( !pPage->leaf ) iCellLast--;
  38412. for(i=0; i<pPage->nCell; i++){
  38413. pc = get2byte(&data[cellOffset+i*2]);
  38414. testcase( pc==iCellFirst );
  38415. testcase( pc==iCellLast );
  38416. if( pc<iCellFirst || pc>iCellLast ){
  38417. return SQLITE_CORRUPT_BKPT;
  38418. }
  38419. sz = cellSizePtr(pPage, &data[pc]);
  38420. testcase( pc+sz==usableSize );
  38421. if( pc+sz>usableSize ){
  38422. return SQLITE_CORRUPT_BKPT;
  38423. }
  38424. }
  38425. if( !pPage->leaf ) iCellLast++;
  38426. }
  38427. #endif
  38428. /* Compute the total free space on the page */
  38429. pc = get2byte(&data[hdr+1]);
  38430. nFree = data[hdr+7] + top;
  38431. while( pc>0 ){
  38432. u16 next, size;
  38433. if( pc<iCellFirst || pc>iCellLast ){
  38434. /* Start of free block is off the page */
  38435. return SQLITE_CORRUPT_BKPT;
  38436. }
  38437. next = get2byte(&data[pc]);
  38438. size = get2byte(&data[pc+2]);
  38439. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  38440. /* Free blocks must be in ascending order. And the last byte of
  38441. ** the free-block must lie on the database page. */
  38442. return SQLITE_CORRUPT_BKPT;
  38443. }
  38444. nFree = nFree + size;
  38445. pc = next;
  38446. }
  38447. /* At this point, nFree contains the sum of the offset to the start
  38448. ** of the cell-content area plus the number of free bytes within
  38449. ** the cell-content area. If this is greater than the usable-size
  38450. ** of the page, then the page must be corrupted. This check also
  38451. ** serves to verify that the offset to the start of the cell-content
  38452. ** area, according to the page header, lies within the page.
  38453. */
  38454. if( nFree>usableSize ){
  38455. return SQLITE_CORRUPT_BKPT;
  38456. }
  38457. pPage->nFree = (u16)(nFree - iCellFirst);
  38458. pPage->isInit = 1;
  38459. }
  38460. return SQLITE_OK;
  38461. }
  38462. /*
  38463. ** Set up a raw page so that it looks like a database page holding
  38464. ** no entries.
  38465. */
  38466. static void zeroPage(MemPage *pPage, int flags){
  38467. unsigned char *data = pPage->aData;
  38468. BtShared *pBt = pPage->pBt;
  38469. u8 hdr = pPage->hdrOffset;
  38470. u16 first;
  38471. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  38472. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  38473. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  38474. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38475. assert( sqlite3_mutex_held(pBt->mutex) );
  38476. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  38477. memset(&data[hdr], 0, pBt->usableSize - hdr);
  38478. }
  38479. data[hdr] = (char)flags;
  38480. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  38481. memset(&data[hdr+1], 0, 4);
  38482. data[hdr+7] = 0;
  38483. put2byte(&data[hdr+5], pBt->usableSize);
  38484. pPage->nFree = (u16)(pBt->usableSize - first);
  38485. decodeFlags(pPage, flags);
  38486. pPage->hdrOffset = hdr;
  38487. pPage->cellOffset = first;
  38488. pPage->aDataEnd = &data[pBt->usableSize];
  38489. pPage->aCellIdx = &data[first];
  38490. pPage->nOverflow = 0;
  38491. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  38492. pPage->maskPage = (u16)(pBt->pageSize - 1);
  38493. pPage->nCell = 0;
  38494. pPage->isInit = 1;
  38495. }
  38496. /*
  38497. ** Convert a DbPage obtained from the pager into a MemPage used by
  38498. ** the btree layer.
  38499. */
  38500. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  38501. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  38502. pPage->aData = sqlite3PagerGetData(pDbPage);
  38503. pPage->pDbPage = pDbPage;
  38504. pPage->pBt = pBt;
  38505. pPage->pgno = pgno;
  38506. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  38507. return pPage;
  38508. }
  38509. /*
  38510. ** Get a page from the pager. Initialize the MemPage.pBt and
  38511. ** MemPage.aData elements if needed.
  38512. **
  38513. ** If the noContent flag is set, it means that we do not care about
  38514. ** the content of the page at this time. So do not go to the disk
  38515. ** to fetch the content. Just fill in the content with zeros for now.
  38516. ** If in the future we call sqlite3PagerWrite() on this page, that
  38517. ** means we have started to be concerned about content and the disk
  38518. ** read should occur at that point.
  38519. */
  38520. static int btreeGetPage(
  38521. BtShared *pBt, /* The btree */
  38522. Pgno pgno, /* Number of the page to fetch */
  38523. MemPage **ppPage, /* Return the page in this parameter */
  38524. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  38525. ){
  38526. int rc;
  38527. DbPage *pDbPage;
  38528. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  38529. assert( sqlite3_mutex_held(pBt->mutex) );
  38530. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  38531. if( rc ) return rc;
  38532. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  38533. return SQLITE_OK;
  38534. }
  38535. /*
  38536. ** Retrieve a page from the pager cache. If the requested page is not
  38537. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  38538. ** MemPage.aData elements if needed.
  38539. */
  38540. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  38541. DbPage *pDbPage;
  38542. assert( sqlite3_mutex_held(pBt->mutex) );
  38543. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  38544. if( pDbPage ){
  38545. return btreePageFromDbPage(pDbPage, pgno, pBt);
  38546. }
  38547. return 0;
  38548. }
  38549. /*
  38550. ** Return the size of the database file in pages. If there is any kind of
  38551. ** error, return ((unsigned int)-1).
  38552. */
  38553. static Pgno btreePagecount(BtShared *pBt){
  38554. return pBt->nPage;
  38555. }
  38556. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  38557. assert( sqlite3BtreeHoldsMutex(p) );
  38558. assert( ((p->pBt->nPage)&0x8000000)==0 );
  38559. return (int)btreePagecount(p->pBt);
  38560. }
  38561. /*
  38562. ** Get a page from the pager and initialize it. This routine is just a
  38563. ** convenience wrapper around separate calls to btreeGetPage() and
  38564. ** btreeInitPage().
  38565. **
  38566. ** If an error occurs, then the value *ppPage is set to is undefined. It
  38567. ** may remain unchanged, or it may be set to an invalid value.
  38568. */
  38569. static int getAndInitPage(
  38570. BtShared *pBt, /* The database file */
  38571. Pgno pgno, /* Number of the page to get */
  38572. MemPage **ppPage, /* Write the page pointer here */
  38573. int bReadonly /* PAGER_GET_READONLY or 0 */
  38574. ){
  38575. int rc;
  38576. assert( sqlite3_mutex_held(pBt->mutex) );
  38577. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  38578. if( pgno>btreePagecount(pBt) ){
  38579. rc = SQLITE_CORRUPT_BKPT;
  38580. }else{
  38581. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  38582. if( rc==SQLITE_OK ){
  38583. rc = btreeInitPage(*ppPage);
  38584. if( rc!=SQLITE_OK ){
  38585. releasePage(*ppPage);
  38586. }
  38587. }
  38588. }
  38589. testcase( pgno==0 );
  38590. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  38591. return rc;
  38592. }
  38593. /*
  38594. ** Release a MemPage. This should be called once for each prior
  38595. ** call to btreeGetPage.
  38596. */
  38597. static void releasePage(MemPage *pPage){
  38598. if( pPage ){
  38599. assert( pPage->aData );
  38600. assert( pPage->pBt );
  38601. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  38602. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  38603. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38604. sqlite3PagerUnref(pPage->pDbPage);
  38605. }
  38606. }
  38607. /*
  38608. ** During a rollback, when the pager reloads information into the cache
  38609. ** so that the cache is restored to its original state at the start of
  38610. ** the transaction, for each page restored this routine is called.
  38611. **
  38612. ** This routine needs to reset the extra data section at the end of the
  38613. ** page to agree with the restored data.
  38614. */
  38615. static void pageReinit(DbPage *pData){
  38616. MemPage *pPage;
  38617. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  38618. assert( sqlite3PagerPageRefcount(pData)>0 );
  38619. if( pPage->isInit ){
  38620. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38621. pPage->isInit = 0;
  38622. if( sqlite3PagerPageRefcount(pData)>1 ){
  38623. /* pPage might not be a btree page; it might be an overflow page
  38624. ** or ptrmap page or a free page. In those cases, the following
  38625. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  38626. ** But no harm is done by this. And it is very important that
  38627. ** btreeInitPage() be called on every btree page so we make
  38628. ** the call for every page that comes in for re-initing. */
  38629. btreeInitPage(pPage);
  38630. }
  38631. }
  38632. }
  38633. /*
  38634. ** Invoke the busy handler for a btree.
  38635. */
  38636. static int btreeInvokeBusyHandler(void *pArg){
  38637. BtShared *pBt = (BtShared*)pArg;
  38638. assert( pBt->db );
  38639. assert( sqlite3_mutex_held(pBt->db->mutex) );
  38640. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  38641. }
  38642. /*
  38643. ** Open a database file.
  38644. **
  38645. ** zFilename is the name of the database file. If zFilename is NULL
  38646. ** then an ephemeral database is created. The ephemeral database might
  38647. ** be exclusively in memory, or it might use a disk-based memory cache.
  38648. ** Either way, the ephemeral database will be automatically deleted
  38649. ** when sqlite3BtreeClose() is called.
  38650. **
  38651. ** If zFilename is ":memory:" then an in-memory database is created
  38652. ** that is automatically destroyed when it is closed.
  38653. **
  38654. ** The "flags" parameter is a bitmask that might contain bits like
  38655. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  38656. **
  38657. ** If the database is already opened in the same database connection
  38658. ** and we are in shared cache mode, then the open will fail with an
  38659. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  38660. ** objects in the same database connection since doing so will lead
  38661. ** to problems with locking.
  38662. */
  38663. SQLITE_PRIVATE int sqlite3BtreeOpen(
  38664. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  38665. const char *zFilename, /* Name of the file containing the BTree database */
  38666. sqlite3 *db, /* Associated database handle */
  38667. Btree **ppBtree, /* Pointer to new Btree object written here */
  38668. int flags, /* Options */
  38669. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  38670. ){
  38671. BtShared *pBt = 0; /* Shared part of btree structure */
  38672. Btree *p; /* Handle to return */
  38673. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  38674. int rc = SQLITE_OK; /* Result code from this function */
  38675. u8 nReserve; /* Byte of unused space on each page */
  38676. unsigned char zDbHeader[100]; /* Database header content */
  38677. /* True if opening an ephemeral, temporary database */
  38678. const int isTempDb = zFilename==0 || zFilename[0]==0;
  38679. /* Set the variable isMemdb to true for an in-memory database, or
  38680. ** false for a file-based database.
  38681. */
  38682. #ifdef SQLITE_OMIT_MEMORYDB
  38683. const int isMemdb = 0;
  38684. #else
  38685. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  38686. || (isTempDb && sqlite3TempInMemory(db))
  38687. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  38688. #endif
  38689. assert( db!=0 );
  38690. assert( pVfs!=0 );
  38691. assert( sqlite3_mutex_held(db->mutex) );
  38692. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  38693. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  38694. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  38695. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  38696. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  38697. if( isMemdb ){
  38698. flags |= BTREE_MEMORY;
  38699. }
  38700. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  38701. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  38702. }
  38703. p = sqlite3MallocZero(sizeof(Btree));
  38704. if( !p ){
  38705. return SQLITE_NOMEM;
  38706. }
  38707. p->inTrans = TRANS_NONE;
  38708. p->db = db;
  38709. #ifndef SQLITE_OMIT_SHARED_CACHE
  38710. p->lock.pBtree = p;
  38711. p->lock.iTable = 1;
  38712. #endif
  38713. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38714. /*
  38715. ** If this Btree is a candidate for shared cache, try to find an
  38716. ** existing BtShared object that we can share with
  38717. */
  38718. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  38719. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  38720. int nFullPathname = pVfs->mxPathname+1;
  38721. char *zFullPathname = sqlite3Malloc(nFullPathname);
  38722. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  38723. p->sharable = 1;
  38724. if( !zFullPathname ){
  38725. sqlite3_free(p);
  38726. return SQLITE_NOMEM;
  38727. }
  38728. if( isMemdb ){
  38729. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  38730. }else{
  38731. rc = sqlite3OsFullPathname(pVfs, zFilename,
  38732. nFullPathname, zFullPathname);
  38733. if( rc ){
  38734. sqlite3_free(zFullPathname);
  38735. sqlite3_free(p);
  38736. return rc;
  38737. }
  38738. }
  38739. #if SQLITE_THREADSAFE
  38740. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  38741. sqlite3_mutex_enter(mutexOpen);
  38742. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  38743. sqlite3_mutex_enter(mutexShared);
  38744. #endif
  38745. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  38746. assert( pBt->nRef>0 );
  38747. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  38748. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  38749. int iDb;
  38750. for(iDb=db->nDb-1; iDb>=0; iDb--){
  38751. Btree *pExisting = db->aDb[iDb].pBt;
  38752. if( pExisting && pExisting->pBt==pBt ){
  38753. sqlite3_mutex_leave(mutexShared);
  38754. sqlite3_mutex_leave(mutexOpen);
  38755. sqlite3_free(zFullPathname);
  38756. sqlite3_free(p);
  38757. return SQLITE_CONSTRAINT;
  38758. }
  38759. }
  38760. p->pBt = pBt;
  38761. pBt->nRef++;
  38762. break;
  38763. }
  38764. }
  38765. sqlite3_mutex_leave(mutexShared);
  38766. sqlite3_free(zFullPathname);
  38767. }
  38768. #ifdef SQLITE_DEBUG
  38769. else{
  38770. /* In debug mode, we mark all persistent databases as sharable
  38771. ** even when they are not. This exercises the locking code and
  38772. ** gives more opportunity for asserts(sqlite3_mutex_held())
  38773. ** statements to find locking problems.
  38774. */
  38775. p->sharable = 1;
  38776. }
  38777. #endif
  38778. }
  38779. #endif
  38780. if( pBt==0 ){
  38781. /*
  38782. ** The following asserts make sure that structures used by the btree are
  38783. ** the right size. This is to guard against size changes that result
  38784. ** when compiling on a different architecture.
  38785. */
  38786. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  38787. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  38788. assert( sizeof(u32)==4 );
  38789. assert( sizeof(u16)==2 );
  38790. assert( sizeof(Pgno)==4 );
  38791. pBt = sqlite3MallocZero( sizeof(*pBt) );
  38792. if( pBt==0 ){
  38793. rc = SQLITE_NOMEM;
  38794. goto btree_open_out;
  38795. }
  38796. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  38797. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  38798. if( rc==SQLITE_OK ){
  38799. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  38800. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  38801. }
  38802. if( rc!=SQLITE_OK ){
  38803. goto btree_open_out;
  38804. }
  38805. pBt->openFlags = (u8)flags;
  38806. pBt->db = db;
  38807. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  38808. p->pBt = pBt;
  38809. pBt->pCursor = 0;
  38810. pBt->pPage1 = 0;
  38811. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  38812. #ifdef SQLITE_SECURE_DELETE
  38813. pBt->btsFlags |= BTS_SECURE_DELETE;
  38814. #endif
  38815. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  38816. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  38817. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  38818. pBt->pageSize = 0;
  38819. #ifndef SQLITE_OMIT_AUTOVACUUM
  38820. /* If the magic name ":memory:" will create an in-memory database, then
  38821. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  38822. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  38823. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  38824. ** regular file-name. In this case the auto-vacuum applies as per normal.
  38825. */
  38826. if( zFilename && !isMemdb ){
  38827. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  38828. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  38829. }
  38830. #endif
  38831. nReserve = 0;
  38832. }else{
  38833. nReserve = zDbHeader[20];
  38834. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  38835. #ifndef SQLITE_OMIT_AUTOVACUUM
  38836. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  38837. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  38838. #endif
  38839. }
  38840. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  38841. if( rc ) goto btree_open_out;
  38842. pBt->usableSize = pBt->pageSize - nReserve;
  38843. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  38844. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38845. /* Add the new BtShared object to the linked list sharable BtShareds.
  38846. */
  38847. if( p->sharable ){
  38848. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  38849. pBt->nRef = 1;
  38850. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  38851. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  38852. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  38853. if( pBt->mutex==0 ){
  38854. rc = SQLITE_NOMEM;
  38855. db->mallocFailed = 0;
  38856. goto btree_open_out;
  38857. }
  38858. }
  38859. sqlite3_mutex_enter(mutexShared);
  38860. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  38861. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  38862. sqlite3_mutex_leave(mutexShared);
  38863. }
  38864. #endif
  38865. }
  38866. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38867. /* If the new Btree uses a sharable pBtShared, then link the new
  38868. ** Btree into the list of all sharable Btrees for the same connection.
  38869. ** The list is kept in ascending order by pBt address.
  38870. */
  38871. if( p->sharable ){
  38872. int i;
  38873. Btree *pSib;
  38874. for(i=0; i<db->nDb; i++){
  38875. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  38876. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  38877. if( p->pBt<pSib->pBt ){
  38878. p->pNext = pSib;
  38879. p->pPrev = 0;
  38880. pSib->pPrev = p;
  38881. }else{
  38882. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  38883. pSib = pSib->pNext;
  38884. }
  38885. p->pNext = pSib->pNext;
  38886. p->pPrev = pSib;
  38887. if( p->pNext ){
  38888. p->pNext->pPrev = p;
  38889. }
  38890. pSib->pNext = p;
  38891. }
  38892. break;
  38893. }
  38894. }
  38895. }
  38896. #endif
  38897. *ppBtree = p;
  38898. btree_open_out:
  38899. if( rc!=SQLITE_OK ){
  38900. if( pBt && pBt->pPager ){
  38901. sqlite3PagerClose(pBt->pPager);
  38902. }
  38903. sqlite3_free(pBt);
  38904. sqlite3_free(p);
  38905. *ppBtree = 0;
  38906. }else{
  38907. /* If the B-Tree was successfully opened, set the pager-cache size to the
  38908. ** default value. Except, when opening on an existing shared pager-cache,
  38909. ** do not change the pager-cache size.
  38910. */
  38911. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  38912. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  38913. }
  38914. }
  38915. if( mutexOpen ){
  38916. assert( sqlite3_mutex_held(mutexOpen) );
  38917. sqlite3_mutex_leave(mutexOpen);
  38918. }
  38919. return rc;
  38920. }
  38921. /*
  38922. ** Decrement the BtShared.nRef counter. When it reaches zero,
  38923. ** remove the BtShared structure from the sharing list. Return
  38924. ** true if the BtShared.nRef counter reaches zero and return
  38925. ** false if it is still positive.
  38926. */
  38927. static int removeFromSharingList(BtShared *pBt){
  38928. #ifndef SQLITE_OMIT_SHARED_CACHE
  38929. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  38930. BtShared *pList;
  38931. int removed = 0;
  38932. assert( sqlite3_mutex_notheld(pBt->mutex) );
  38933. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  38934. sqlite3_mutex_enter(pMaster);
  38935. pBt->nRef--;
  38936. if( pBt->nRef<=0 ){
  38937. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  38938. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  38939. }else{
  38940. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  38941. while( ALWAYS(pList) && pList->pNext!=pBt ){
  38942. pList=pList->pNext;
  38943. }
  38944. if( ALWAYS(pList) ){
  38945. pList->pNext = pBt->pNext;
  38946. }
  38947. }
  38948. if( SQLITE_THREADSAFE ){
  38949. sqlite3_mutex_free(pBt->mutex);
  38950. }
  38951. removed = 1;
  38952. }
  38953. sqlite3_mutex_leave(pMaster);
  38954. return removed;
  38955. #else
  38956. return 1;
  38957. #endif
  38958. }
  38959. /*
  38960. ** Make sure pBt->pTmpSpace points to an allocation of
  38961. ** MX_CELL_SIZE(pBt) bytes.
  38962. */
  38963. static void allocateTempSpace(BtShared *pBt){
  38964. if( !pBt->pTmpSpace ){
  38965. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  38966. /* One of the uses of pBt->pTmpSpace is to format cells before
  38967. ** inserting them into a leaf page (function fillInCell()). If
  38968. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  38969. ** by the various routines that manipulate binary cells. Which
  38970. ** can mean that fillInCell() only initializes the first 2 or 3
  38971. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  38972. ** it into a database page. This is not actually a problem, but it
  38973. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  38974. ** data is passed to system call write(). So to avoid this error,
  38975. ** zero the first 4 bytes of temp space here. */
  38976. if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
  38977. }
  38978. }
  38979. /*
  38980. ** Free the pBt->pTmpSpace allocation
  38981. */
  38982. static void freeTempSpace(BtShared *pBt){
  38983. sqlite3PageFree( pBt->pTmpSpace);
  38984. pBt->pTmpSpace = 0;
  38985. }
  38986. /*
  38987. ** Close an open database and invalidate all cursors.
  38988. */
  38989. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  38990. BtShared *pBt = p->pBt;
  38991. BtCursor *pCur;
  38992. /* Close all cursors opened via this handle. */
  38993. assert( sqlite3_mutex_held(p->db->mutex) );
  38994. sqlite3BtreeEnter(p);
  38995. pCur = pBt->pCursor;
  38996. while( pCur ){
  38997. BtCursor *pTmp = pCur;
  38998. pCur = pCur->pNext;
  38999. if( pTmp->pBtree==p ){
  39000. sqlite3BtreeCloseCursor(pTmp);
  39001. }
  39002. }
  39003. /* Rollback any active transaction and free the handle structure.
  39004. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  39005. ** this handle.
  39006. */
  39007. sqlite3BtreeRollback(p, SQLITE_OK);
  39008. sqlite3BtreeLeave(p);
  39009. /* If there are still other outstanding references to the shared-btree
  39010. ** structure, return now. The remainder of this procedure cleans
  39011. ** up the shared-btree.
  39012. */
  39013. assert( p->wantToLock==0 && p->locked==0 );
  39014. if( !p->sharable || removeFromSharingList(pBt) ){
  39015. /* The pBt is no longer on the sharing list, so we can access
  39016. ** it without having to hold the mutex.
  39017. **
  39018. ** Clean out and delete the BtShared object.
  39019. */
  39020. assert( !pBt->pCursor );
  39021. sqlite3PagerClose(pBt->pPager);
  39022. if( pBt->xFreeSchema && pBt->pSchema ){
  39023. pBt->xFreeSchema(pBt->pSchema);
  39024. }
  39025. sqlite3DbFree(0, pBt->pSchema);
  39026. freeTempSpace(pBt);
  39027. sqlite3_free(pBt);
  39028. }
  39029. #ifndef SQLITE_OMIT_SHARED_CACHE
  39030. assert( p->wantToLock==0 );
  39031. assert( p->locked==0 );
  39032. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  39033. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  39034. #endif
  39035. sqlite3_free(p);
  39036. return SQLITE_OK;
  39037. }
  39038. /*
  39039. ** Change the limit on the number of pages allowed in the cache.
  39040. **
  39041. ** The maximum number of cache pages is set to the absolute
  39042. ** value of mxPage. If mxPage is negative, the pager will
  39043. ** operate asynchronously - it will not stop to do fsync()s
  39044. ** to insure data is written to the disk surface before
  39045. ** continuing. Transactions still work if synchronous is off,
  39046. ** and the database cannot be corrupted if this program
  39047. ** crashes. But if the operating system crashes or there is
  39048. ** an abrupt power failure when synchronous is off, the database
  39049. ** could be left in an inconsistent and unrecoverable state.
  39050. ** Synchronous is on by default so database corruption is not
  39051. ** normally a worry.
  39052. */
  39053. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  39054. BtShared *pBt = p->pBt;
  39055. assert( sqlite3_mutex_held(p->db->mutex) );
  39056. sqlite3BtreeEnter(p);
  39057. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  39058. sqlite3BtreeLeave(p);
  39059. return SQLITE_OK;
  39060. }
  39061. /*
  39062. ** Change the limit on the amount of the database file that may be
  39063. ** memory mapped.
  39064. */
  39065. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  39066. BtShared *pBt = p->pBt;
  39067. assert( sqlite3_mutex_held(p->db->mutex) );
  39068. sqlite3BtreeEnter(p);
  39069. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  39070. sqlite3BtreeLeave(p);
  39071. return SQLITE_OK;
  39072. }
  39073. /*
  39074. ** Change the way data is synced to disk in order to increase or decrease
  39075. ** how well the database resists damage due to OS crashes and power
  39076. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  39077. ** there is a high probability of damage) Level 2 is the default. There
  39078. ** is a very low but non-zero probability of damage. Level 3 reduces the
  39079. ** probability of damage to near zero but with a write performance reduction.
  39080. */
  39081. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  39082. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  39083. Btree *p, /* The btree to set the safety level on */
  39084. unsigned pgFlags /* Various PAGER_* flags */
  39085. ){
  39086. BtShared *pBt = p->pBt;
  39087. assert( sqlite3_mutex_held(p->db->mutex) );
  39088. sqlite3BtreeEnter(p);
  39089. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  39090. sqlite3BtreeLeave(p);
  39091. return SQLITE_OK;
  39092. }
  39093. #endif
  39094. /*
  39095. ** Return TRUE if the given btree is set to safety level 1. In other
  39096. ** words, return TRUE if no sync() occurs on the disk files.
  39097. */
  39098. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  39099. BtShared *pBt = p->pBt;
  39100. int rc;
  39101. assert( sqlite3_mutex_held(p->db->mutex) );
  39102. sqlite3BtreeEnter(p);
  39103. assert( pBt && pBt->pPager );
  39104. rc = sqlite3PagerNosync(pBt->pPager);
  39105. sqlite3BtreeLeave(p);
  39106. return rc;
  39107. }
  39108. /*
  39109. ** Change the default pages size and the number of reserved bytes per page.
  39110. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  39111. ** without changing anything.
  39112. **
  39113. ** The page size must be a power of 2 between 512 and 65536. If the page
  39114. ** size supplied does not meet this constraint then the page size is not
  39115. ** changed.
  39116. **
  39117. ** Page sizes are constrained to be a power of two so that the region
  39118. ** of the database file used for locking (beginning at PENDING_BYTE,
  39119. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  39120. ** at the beginning of a page.
  39121. **
  39122. ** If parameter nReserve is less than zero, then the number of reserved
  39123. ** bytes per page is left unchanged.
  39124. **
  39125. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  39126. ** and autovacuum mode can no longer be changed.
  39127. */
  39128. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  39129. int rc = SQLITE_OK;
  39130. BtShared *pBt = p->pBt;
  39131. assert( nReserve>=-1 && nReserve<=255 );
  39132. sqlite3BtreeEnter(p);
  39133. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  39134. sqlite3BtreeLeave(p);
  39135. return SQLITE_READONLY;
  39136. }
  39137. if( nReserve<0 ){
  39138. nReserve = pBt->pageSize - pBt->usableSize;
  39139. }
  39140. assert( nReserve>=0 && nReserve<=255 );
  39141. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  39142. ((pageSize-1)&pageSize)==0 ){
  39143. assert( (pageSize & 7)==0 );
  39144. assert( !pBt->pPage1 && !pBt->pCursor );
  39145. pBt->pageSize = (u32)pageSize;
  39146. freeTempSpace(pBt);
  39147. }
  39148. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  39149. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  39150. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  39151. sqlite3BtreeLeave(p);
  39152. return rc;
  39153. }
  39154. /*
  39155. ** Return the currently defined page size
  39156. */
  39157. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  39158. return p->pBt->pageSize;
  39159. }
  39160. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  39161. /*
  39162. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  39163. ** may only be called if it is guaranteed that the b-tree mutex is already
  39164. ** held.
  39165. **
  39166. ** This is useful in one special case in the backup API code where it is
  39167. ** known that the shared b-tree mutex is held, but the mutex on the
  39168. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  39169. ** were to be called, it might collide with some other operation on the
  39170. ** database handle that owns *p, causing undefined behavior.
  39171. */
  39172. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  39173. assert( sqlite3_mutex_held(p->pBt->mutex) );
  39174. return p->pBt->pageSize - p->pBt->usableSize;
  39175. }
  39176. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  39177. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  39178. /*
  39179. ** Return the number of bytes of space at the end of every page that
  39180. ** are intentually left unused. This is the "reserved" space that is
  39181. ** sometimes used by extensions.
  39182. */
  39183. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  39184. int n;
  39185. sqlite3BtreeEnter(p);
  39186. n = p->pBt->pageSize - p->pBt->usableSize;
  39187. sqlite3BtreeLeave(p);
  39188. return n;
  39189. }
  39190. /*
  39191. ** Set the maximum page count for a database if mxPage is positive.
  39192. ** No changes are made if mxPage is 0 or negative.
  39193. ** Regardless of the value of mxPage, return the maximum page count.
  39194. */
  39195. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  39196. int n;
  39197. sqlite3BtreeEnter(p);
  39198. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  39199. sqlite3BtreeLeave(p);
  39200. return n;
  39201. }
  39202. /*
  39203. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  39204. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  39205. ** setting after the change.
  39206. */
  39207. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  39208. int b;
  39209. if( p==0 ) return 0;
  39210. sqlite3BtreeEnter(p);
  39211. if( newFlag>=0 ){
  39212. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  39213. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  39214. }
  39215. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  39216. sqlite3BtreeLeave(p);
  39217. return b;
  39218. }
  39219. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  39220. /*
  39221. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  39222. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  39223. ** is disabled. The default value for the auto-vacuum property is
  39224. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  39225. */
  39226. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  39227. #ifdef SQLITE_OMIT_AUTOVACUUM
  39228. return SQLITE_READONLY;
  39229. #else
  39230. BtShared *pBt = p->pBt;
  39231. int rc = SQLITE_OK;
  39232. u8 av = (u8)autoVacuum;
  39233. sqlite3BtreeEnter(p);
  39234. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  39235. rc = SQLITE_READONLY;
  39236. }else{
  39237. pBt->autoVacuum = av ?1:0;
  39238. pBt->incrVacuum = av==2 ?1:0;
  39239. }
  39240. sqlite3BtreeLeave(p);
  39241. return rc;
  39242. #endif
  39243. }
  39244. /*
  39245. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  39246. ** enabled 1 is returned. Otherwise 0.
  39247. */
  39248. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  39249. #ifdef SQLITE_OMIT_AUTOVACUUM
  39250. return BTREE_AUTOVACUUM_NONE;
  39251. #else
  39252. int rc;
  39253. sqlite3BtreeEnter(p);
  39254. rc = (
  39255. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  39256. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  39257. BTREE_AUTOVACUUM_INCR
  39258. );
  39259. sqlite3BtreeLeave(p);
  39260. return rc;
  39261. #endif
  39262. }
  39263. /*
  39264. ** Get a reference to pPage1 of the database file. This will
  39265. ** also acquire a readlock on that file.
  39266. **
  39267. ** SQLITE_OK is returned on success. If the file is not a
  39268. ** well-formed database file, then SQLITE_CORRUPT is returned.
  39269. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  39270. ** is returned if we run out of memory.
  39271. */
  39272. static int lockBtree(BtShared *pBt){
  39273. int rc; /* Result code from subfunctions */
  39274. MemPage *pPage1; /* Page 1 of the database file */
  39275. int nPage; /* Number of pages in the database */
  39276. int nPageFile = 0; /* Number of pages in the database file */
  39277. int nPageHeader; /* Number of pages in the database according to hdr */
  39278. assert( sqlite3_mutex_held(pBt->mutex) );
  39279. assert( pBt->pPage1==0 );
  39280. rc = sqlite3PagerSharedLock(pBt->pPager);
  39281. if( rc!=SQLITE_OK ) return rc;
  39282. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  39283. if( rc!=SQLITE_OK ) return rc;
  39284. /* Do some checking to help insure the file we opened really is
  39285. ** a valid database file.
  39286. */
  39287. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  39288. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  39289. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  39290. nPage = nPageFile;
  39291. }
  39292. if( nPage>0 ){
  39293. u32 pageSize;
  39294. u32 usableSize;
  39295. u8 *page1 = pPage1->aData;
  39296. rc = SQLITE_NOTADB;
  39297. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  39298. goto page1_init_failed;
  39299. }
  39300. #ifdef SQLITE_OMIT_WAL
  39301. if( page1[18]>1 ){
  39302. pBt->btsFlags |= BTS_READ_ONLY;
  39303. }
  39304. if( page1[19]>1 ){
  39305. goto page1_init_failed;
  39306. }
  39307. #else
  39308. if( page1[18]>2 ){
  39309. pBt->btsFlags |= BTS_READ_ONLY;
  39310. }
  39311. if( page1[19]>2 ){
  39312. goto page1_init_failed;
  39313. }
  39314. /* If the write version is set to 2, this database should be accessed
  39315. ** in WAL mode. If the log is not already open, open it now. Then
  39316. ** return SQLITE_OK and return without populating BtShared.pPage1.
  39317. ** The caller detects this and calls this function again. This is
  39318. ** required as the version of page 1 currently in the page1 buffer
  39319. ** may not be the latest version - there may be a newer one in the log
  39320. ** file.
  39321. */
  39322. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  39323. int isOpen = 0;
  39324. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  39325. if( rc!=SQLITE_OK ){
  39326. goto page1_init_failed;
  39327. }else if( isOpen==0 ){
  39328. releasePage(pPage1);
  39329. return SQLITE_OK;
  39330. }
  39331. rc = SQLITE_NOTADB;
  39332. }
  39333. #endif
  39334. /* The maximum embedded fraction must be exactly 25%. And the minimum
  39335. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  39336. ** The original design allowed these amounts to vary, but as of
  39337. ** version 3.6.0, we require them to be fixed.
  39338. */
  39339. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  39340. goto page1_init_failed;
  39341. }
  39342. pageSize = (page1[16]<<8) | (page1[17]<<16);
  39343. if( ((pageSize-1)&pageSize)!=0
  39344. || pageSize>SQLITE_MAX_PAGE_SIZE
  39345. || pageSize<=256
  39346. ){
  39347. goto page1_init_failed;
  39348. }
  39349. assert( (pageSize & 7)==0 );
  39350. usableSize = pageSize - page1[20];
  39351. if( (u32)pageSize!=pBt->pageSize ){
  39352. /* After reading the first page of the database assuming a page size
  39353. ** of BtShared.pageSize, we have discovered that the page-size is
  39354. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  39355. ** zero and return SQLITE_OK. The caller will call this function
  39356. ** again with the correct page-size.
  39357. */
  39358. releasePage(pPage1);
  39359. pBt->usableSize = usableSize;
  39360. pBt->pageSize = pageSize;
  39361. freeTempSpace(pBt);
  39362. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  39363. pageSize-usableSize);
  39364. return rc;
  39365. }
  39366. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  39367. rc = SQLITE_CORRUPT_BKPT;
  39368. goto page1_init_failed;
  39369. }
  39370. if( usableSize<480 ){
  39371. goto page1_init_failed;
  39372. }
  39373. pBt->pageSize = pageSize;
  39374. pBt->usableSize = usableSize;
  39375. #ifndef SQLITE_OMIT_AUTOVACUUM
  39376. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  39377. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  39378. #endif
  39379. }
  39380. /* maxLocal is the maximum amount of payload to store locally for
  39381. ** a cell. Make sure it is small enough so that at least minFanout
  39382. ** cells can will fit on one page. We assume a 10-byte page header.
  39383. ** Besides the payload, the cell must store:
  39384. ** 2-byte pointer to the cell
  39385. ** 4-byte child pointer
  39386. ** 9-byte nKey value
  39387. ** 4-byte nData value
  39388. ** 4-byte overflow page pointer
  39389. ** So a cell consists of a 2-byte pointer, a header which is as much as
  39390. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  39391. ** page pointer.
  39392. */
  39393. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  39394. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  39395. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  39396. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  39397. if( pBt->maxLocal>127 ){
  39398. pBt->max1bytePayload = 127;
  39399. }else{
  39400. pBt->max1bytePayload = (u8)pBt->maxLocal;
  39401. }
  39402. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  39403. pBt->pPage1 = pPage1;
  39404. pBt->nPage = nPage;
  39405. return SQLITE_OK;
  39406. page1_init_failed:
  39407. releasePage(pPage1);
  39408. pBt->pPage1 = 0;
  39409. return rc;
  39410. }
  39411. #ifndef NDEBUG
  39412. /*
  39413. ** Return the number of cursors open on pBt. This is for use
  39414. ** in assert() expressions, so it is only compiled if NDEBUG is not
  39415. ** defined.
  39416. **
  39417. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  39418. ** false then all cursors are counted.
  39419. **
  39420. ** For the purposes of this routine, a cursor is any cursor that
  39421. ** is capable of reading or writing to the databse. Cursors that
  39422. ** have been tripped into the CURSOR_FAULT state are not counted.
  39423. */
  39424. static int countValidCursors(BtShared *pBt, int wrOnly){
  39425. BtCursor *pCur;
  39426. int r = 0;
  39427. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  39428. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  39429. }
  39430. return r;
  39431. }
  39432. #endif
  39433. /*
  39434. ** If there are no outstanding cursors and we are not in the middle
  39435. ** of a transaction but there is a read lock on the database, then
  39436. ** this routine unrefs the first page of the database file which
  39437. ** has the effect of releasing the read lock.
  39438. **
  39439. ** If there is a transaction in progress, this routine is a no-op.
  39440. */
  39441. static void unlockBtreeIfUnused(BtShared *pBt){
  39442. assert( sqlite3_mutex_held(pBt->mutex) );
  39443. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  39444. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  39445. assert( pBt->pPage1->aData );
  39446. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  39447. assert( pBt->pPage1->aData );
  39448. releasePage(pBt->pPage1);
  39449. pBt->pPage1 = 0;
  39450. }
  39451. }
  39452. /*
  39453. ** If pBt points to an empty file then convert that empty file
  39454. ** into a new empty database by initializing the first page of
  39455. ** the database.
  39456. */
  39457. static int newDatabase(BtShared *pBt){
  39458. MemPage *pP1;
  39459. unsigned char *data;
  39460. int rc;
  39461. assert( sqlite3_mutex_held(pBt->mutex) );
  39462. if( pBt->nPage>0 ){
  39463. return SQLITE_OK;
  39464. }
  39465. pP1 = pBt->pPage1;
  39466. assert( pP1!=0 );
  39467. data = pP1->aData;
  39468. rc = sqlite3PagerWrite(pP1->pDbPage);
  39469. if( rc ) return rc;
  39470. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  39471. assert( sizeof(zMagicHeader)==16 );
  39472. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  39473. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  39474. data[18] = 1;
  39475. data[19] = 1;
  39476. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  39477. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  39478. data[21] = 64;
  39479. data[22] = 32;
  39480. data[23] = 32;
  39481. memset(&data[24], 0, 100-24);
  39482. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  39483. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  39484. #ifndef SQLITE_OMIT_AUTOVACUUM
  39485. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  39486. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  39487. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  39488. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  39489. #endif
  39490. pBt->nPage = 1;
  39491. data[31] = 1;
  39492. return SQLITE_OK;
  39493. }
  39494. /*
  39495. ** Initialize the first page of the database file (creating a database
  39496. ** consisting of a single page and no schema objects). Return SQLITE_OK
  39497. ** if successful, or an SQLite error code otherwise.
  39498. */
  39499. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  39500. int rc;
  39501. sqlite3BtreeEnter(p);
  39502. p->pBt->nPage = 0;
  39503. rc = newDatabase(p->pBt);
  39504. sqlite3BtreeLeave(p);
  39505. return rc;
  39506. }
  39507. /*
  39508. ** Attempt to start a new transaction. A write-transaction
  39509. ** is started if the second argument is nonzero, otherwise a read-
  39510. ** transaction. If the second argument is 2 or more and exclusive
  39511. ** transaction is started, meaning that no other process is allowed
  39512. ** to access the database. A preexisting transaction may not be
  39513. ** upgraded to exclusive by calling this routine a second time - the
  39514. ** exclusivity flag only works for a new transaction.
  39515. **
  39516. ** A write-transaction must be started before attempting any
  39517. ** changes to the database. None of the following routines
  39518. ** will work unless a transaction is started first:
  39519. **
  39520. ** sqlite3BtreeCreateTable()
  39521. ** sqlite3BtreeCreateIndex()
  39522. ** sqlite3BtreeClearTable()
  39523. ** sqlite3BtreeDropTable()
  39524. ** sqlite3BtreeInsert()
  39525. ** sqlite3BtreeDelete()
  39526. ** sqlite3BtreeUpdateMeta()
  39527. **
  39528. ** If an initial attempt to acquire the lock fails because of lock contention
  39529. ** and the database was previously unlocked, then invoke the busy handler
  39530. ** if there is one. But if there was previously a read-lock, do not
  39531. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  39532. ** returned when there is already a read-lock in order to avoid a deadlock.
  39533. **
  39534. ** Suppose there are two processes A and B. A has a read lock and B has
  39535. ** a reserved lock. B tries to promote to exclusive but is blocked because
  39536. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  39537. ** One or the other of the two processes must give way or there can be
  39538. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  39539. ** when A already has a read lock, we encourage A to give up and let B
  39540. ** proceed.
  39541. */
  39542. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  39543. sqlite3 *pBlock = 0;
  39544. BtShared *pBt = p->pBt;
  39545. int rc = SQLITE_OK;
  39546. sqlite3BtreeEnter(p);
  39547. btreeIntegrity(p);
  39548. /* If the btree is already in a write-transaction, or it
  39549. ** is already in a read-transaction and a read-transaction
  39550. ** is requested, this is a no-op.
  39551. */
  39552. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  39553. goto trans_begun;
  39554. }
  39555. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  39556. /* Write transactions are not possible on a read-only database */
  39557. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  39558. rc = SQLITE_READONLY;
  39559. goto trans_begun;
  39560. }
  39561. #ifndef SQLITE_OMIT_SHARED_CACHE
  39562. /* If another database handle has already opened a write transaction
  39563. ** on this shared-btree structure and a second write transaction is
  39564. ** requested, return SQLITE_LOCKED.
  39565. */
  39566. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  39567. || (pBt->btsFlags & BTS_PENDING)!=0
  39568. ){
  39569. pBlock = pBt->pWriter->db;
  39570. }else if( wrflag>1 ){
  39571. BtLock *pIter;
  39572. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  39573. if( pIter->pBtree!=p ){
  39574. pBlock = pIter->pBtree->db;
  39575. break;
  39576. }
  39577. }
  39578. }
  39579. if( pBlock ){
  39580. sqlite3ConnectionBlocked(p->db, pBlock);
  39581. rc = SQLITE_LOCKED_SHAREDCACHE;
  39582. goto trans_begun;
  39583. }
  39584. #endif
  39585. /* Any read-only or read-write transaction implies a read-lock on
  39586. ** page 1. So if some other shared-cache client already has a write-lock
  39587. ** on page 1, the transaction cannot be opened. */
  39588. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  39589. if( SQLITE_OK!=rc ) goto trans_begun;
  39590. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  39591. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  39592. do {
  39593. /* Call lockBtree() until either pBt->pPage1 is populated or
  39594. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  39595. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  39596. ** reading page 1 it discovers that the page-size of the database
  39597. ** file is not pBt->pageSize. In this case lockBtree() will update
  39598. ** pBt->pageSize to the page-size of the file on disk.
  39599. */
  39600. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  39601. if( rc==SQLITE_OK && wrflag ){
  39602. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  39603. rc = SQLITE_READONLY;
  39604. }else{
  39605. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  39606. if( rc==SQLITE_OK ){
  39607. rc = newDatabase(pBt);
  39608. }
  39609. }
  39610. }
  39611. if( rc!=SQLITE_OK ){
  39612. unlockBtreeIfUnused(pBt);
  39613. }
  39614. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  39615. btreeInvokeBusyHandler(pBt) );
  39616. if( rc==SQLITE_OK ){
  39617. if( p->inTrans==TRANS_NONE ){
  39618. pBt->nTransaction++;
  39619. #ifndef SQLITE_OMIT_SHARED_CACHE
  39620. if( p->sharable ){
  39621. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  39622. p->lock.eLock = READ_LOCK;
  39623. p->lock.pNext = pBt->pLock;
  39624. pBt->pLock = &p->lock;
  39625. }
  39626. #endif
  39627. }
  39628. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  39629. if( p->inTrans>pBt->inTransaction ){
  39630. pBt->inTransaction = p->inTrans;
  39631. }
  39632. if( wrflag ){
  39633. MemPage *pPage1 = pBt->pPage1;
  39634. #ifndef SQLITE_OMIT_SHARED_CACHE
  39635. assert( !pBt->pWriter );
  39636. pBt->pWriter = p;
  39637. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  39638. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  39639. #endif
  39640. /* If the db-size header field is incorrect (as it may be if an old
  39641. ** client has been writing the database file), update it now. Doing
  39642. ** this sooner rather than later means the database size can safely
  39643. ** re-read the database size from page 1 if a savepoint or transaction
  39644. ** rollback occurs within the transaction.
  39645. */
  39646. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  39647. rc = sqlite3PagerWrite(pPage1->pDbPage);
  39648. if( rc==SQLITE_OK ){
  39649. put4byte(&pPage1->aData[28], pBt->nPage);
  39650. }
  39651. }
  39652. }
  39653. }
  39654. trans_begun:
  39655. if( rc==SQLITE_OK && wrflag ){
  39656. /* This call makes sure that the pager has the correct number of
  39657. ** open savepoints. If the second parameter is greater than 0 and
  39658. ** the sub-journal is not already open, then it will be opened here.
  39659. */
  39660. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  39661. }
  39662. btreeIntegrity(p);
  39663. sqlite3BtreeLeave(p);
  39664. return rc;
  39665. }
  39666. #ifndef SQLITE_OMIT_AUTOVACUUM
  39667. /*
  39668. ** Set the pointer-map entries for all children of page pPage. Also, if
  39669. ** pPage contains cells that point to overflow pages, set the pointer
  39670. ** map entries for the overflow pages as well.
  39671. */
  39672. static int setChildPtrmaps(MemPage *pPage){
  39673. int i; /* Counter variable */
  39674. int nCell; /* Number of cells in page pPage */
  39675. int rc; /* Return code */
  39676. BtShared *pBt = pPage->pBt;
  39677. u8 isInitOrig = pPage->isInit;
  39678. Pgno pgno = pPage->pgno;
  39679. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39680. rc = btreeInitPage(pPage);
  39681. if( rc!=SQLITE_OK ){
  39682. goto set_child_ptrmaps_out;
  39683. }
  39684. nCell = pPage->nCell;
  39685. for(i=0; i<nCell; i++){
  39686. u8 *pCell = findCell(pPage, i);
  39687. ptrmapPutOvflPtr(pPage, pCell, &rc);
  39688. if( !pPage->leaf ){
  39689. Pgno childPgno = get4byte(pCell);
  39690. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  39691. }
  39692. }
  39693. if( !pPage->leaf ){
  39694. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  39695. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  39696. }
  39697. set_child_ptrmaps_out:
  39698. pPage->isInit = isInitOrig;
  39699. return rc;
  39700. }
  39701. /*
  39702. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  39703. ** that it points to iTo. Parameter eType describes the type of pointer to
  39704. ** be modified, as follows:
  39705. **
  39706. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  39707. ** page of pPage.
  39708. **
  39709. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  39710. ** page pointed to by one of the cells on pPage.
  39711. **
  39712. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  39713. ** overflow page in the list.
  39714. */
  39715. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  39716. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39717. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39718. if( eType==PTRMAP_OVERFLOW2 ){
  39719. /* The pointer is always the first 4 bytes of the page in this case. */
  39720. if( get4byte(pPage->aData)!=iFrom ){
  39721. return SQLITE_CORRUPT_BKPT;
  39722. }
  39723. put4byte(pPage->aData, iTo);
  39724. }else{
  39725. u8 isInitOrig = pPage->isInit;
  39726. int i;
  39727. int nCell;
  39728. btreeInitPage(pPage);
  39729. nCell = pPage->nCell;
  39730. for(i=0; i<nCell; i++){
  39731. u8 *pCell = findCell(pPage, i);
  39732. if( eType==PTRMAP_OVERFLOW1 ){
  39733. CellInfo info;
  39734. btreeParseCellPtr(pPage, pCell, &info);
  39735. if( info.iOverflow
  39736. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  39737. && iFrom==get4byte(&pCell[info.iOverflow])
  39738. ){
  39739. put4byte(&pCell[info.iOverflow], iTo);
  39740. break;
  39741. }
  39742. }else{
  39743. if( get4byte(pCell)==iFrom ){
  39744. put4byte(pCell, iTo);
  39745. break;
  39746. }
  39747. }
  39748. }
  39749. if( i==nCell ){
  39750. if( eType!=PTRMAP_BTREE ||
  39751. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  39752. return SQLITE_CORRUPT_BKPT;
  39753. }
  39754. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  39755. }
  39756. pPage->isInit = isInitOrig;
  39757. }
  39758. return SQLITE_OK;
  39759. }
  39760. /*
  39761. ** Move the open database page pDbPage to location iFreePage in the
  39762. ** database. The pDbPage reference remains valid.
  39763. **
  39764. ** The isCommit flag indicates that there is no need to remember that
  39765. ** the journal needs to be sync()ed before database page pDbPage->pgno
  39766. ** can be written to. The caller has already promised not to write to that
  39767. ** page.
  39768. */
  39769. static int relocatePage(
  39770. BtShared *pBt, /* Btree */
  39771. MemPage *pDbPage, /* Open page to move */
  39772. u8 eType, /* Pointer map 'type' entry for pDbPage */
  39773. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  39774. Pgno iFreePage, /* The location to move pDbPage to */
  39775. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  39776. ){
  39777. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  39778. Pgno iDbPage = pDbPage->pgno;
  39779. Pager *pPager = pBt->pPager;
  39780. int rc;
  39781. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  39782. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  39783. assert( sqlite3_mutex_held(pBt->mutex) );
  39784. assert( pDbPage->pBt==pBt );
  39785. /* Move page iDbPage from its current location to page number iFreePage */
  39786. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  39787. iDbPage, iFreePage, iPtrPage, eType));
  39788. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  39789. if( rc!=SQLITE_OK ){
  39790. return rc;
  39791. }
  39792. pDbPage->pgno = iFreePage;
  39793. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  39794. ** that point to overflow pages. The pointer map entries for all these
  39795. ** pages need to be changed.
  39796. **
  39797. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  39798. ** pointer to a subsequent overflow page. If this is the case, then
  39799. ** the pointer map needs to be updated for the subsequent overflow page.
  39800. */
  39801. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  39802. rc = setChildPtrmaps(pDbPage);
  39803. if( rc!=SQLITE_OK ){
  39804. return rc;
  39805. }
  39806. }else{
  39807. Pgno nextOvfl = get4byte(pDbPage->aData);
  39808. if( nextOvfl!=0 ){
  39809. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  39810. if( rc!=SQLITE_OK ){
  39811. return rc;
  39812. }
  39813. }
  39814. }
  39815. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  39816. ** that it points at iFreePage. Also fix the pointer map entry for
  39817. ** iPtrPage.
  39818. */
  39819. if( eType!=PTRMAP_ROOTPAGE ){
  39820. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  39821. if( rc!=SQLITE_OK ){
  39822. return rc;
  39823. }
  39824. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  39825. if( rc!=SQLITE_OK ){
  39826. releasePage(pPtrPage);
  39827. return rc;
  39828. }
  39829. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  39830. releasePage(pPtrPage);
  39831. if( rc==SQLITE_OK ){
  39832. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  39833. }
  39834. }
  39835. return rc;
  39836. }
  39837. /* Forward declaration required by incrVacuumStep(). */
  39838. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  39839. /*
  39840. ** Perform a single step of an incremental-vacuum. If successful, return
  39841. ** SQLITE_OK. If there is no work to do (and therefore no point in
  39842. ** calling this function again), return SQLITE_DONE. Or, if an error
  39843. ** occurs, return some other error code.
  39844. **
  39845. ** More specificly, this function attempts to re-organize the database so
  39846. ** that the last page of the file currently in use is no longer in use.
  39847. **
  39848. ** Parameter nFin is the number of pages that this database would contain
  39849. ** were this function called until it returns SQLITE_DONE.
  39850. **
  39851. ** If the bCommit parameter is non-zero, this function assumes that the
  39852. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  39853. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  39854. ** operation, or false for an incremental vacuum.
  39855. */
  39856. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  39857. Pgno nFreeList; /* Number of pages still on the free-list */
  39858. int rc;
  39859. assert( sqlite3_mutex_held(pBt->mutex) );
  39860. assert( iLastPg>nFin );
  39861. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  39862. u8 eType;
  39863. Pgno iPtrPage;
  39864. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  39865. if( nFreeList==0 ){
  39866. return SQLITE_DONE;
  39867. }
  39868. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  39869. if( rc!=SQLITE_OK ){
  39870. return rc;
  39871. }
  39872. if( eType==PTRMAP_ROOTPAGE ){
  39873. return SQLITE_CORRUPT_BKPT;
  39874. }
  39875. if( eType==PTRMAP_FREEPAGE ){
  39876. if( bCommit==0 ){
  39877. /* Remove the page from the files free-list. This is not required
  39878. ** if bCommit is non-zero. In that case, the free-list will be
  39879. ** truncated to zero after this function returns, so it doesn't
  39880. ** matter if it still contains some garbage entries.
  39881. */
  39882. Pgno iFreePg;
  39883. MemPage *pFreePg;
  39884. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  39885. if( rc!=SQLITE_OK ){
  39886. return rc;
  39887. }
  39888. assert( iFreePg==iLastPg );
  39889. releasePage(pFreePg);
  39890. }
  39891. } else {
  39892. Pgno iFreePg; /* Index of free page to move pLastPg to */
  39893. MemPage *pLastPg;
  39894. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  39895. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  39896. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  39897. if( rc!=SQLITE_OK ){
  39898. return rc;
  39899. }
  39900. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  39901. ** is swapped with the first free page pulled off the free list.
  39902. **
  39903. ** On the other hand, if bCommit is greater than zero, then keep
  39904. ** looping until a free-page located within the first nFin pages
  39905. ** of the file is found.
  39906. */
  39907. if( bCommit==0 ){
  39908. eMode = BTALLOC_LE;
  39909. iNear = nFin;
  39910. }
  39911. do {
  39912. MemPage *pFreePg;
  39913. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  39914. if( rc!=SQLITE_OK ){
  39915. releasePage(pLastPg);
  39916. return rc;
  39917. }
  39918. releasePage(pFreePg);
  39919. }while( bCommit && iFreePg>nFin );
  39920. assert( iFreePg<iLastPg );
  39921. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  39922. releasePage(pLastPg);
  39923. if( rc!=SQLITE_OK ){
  39924. return rc;
  39925. }
  39926. }
  39927. }
  39928. if( bCommit==0 ){
  39929. do {
  39930. iLastPg--;
  39931. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  39932. pBt->bDoTruncate = 1;
  39933. pBt->nPage = iLastPg;
  39934. }
  39935. return SQLITE_OK;
  39936. }
  39937. /*
  39938. ** The database opened by the first argument is an auto-vacuum database
  39939. ** nOrig pages in size containing nFree free pages. Return the expected
  39940. ** size of the database in pages following an auto-vacuum operation.
  39941. */
  39942. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  39943. int nEntry; /* Number of entries on one ptrmap page */
  39944. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  39945. Pgno nFin; /* Return value */
  39946. nEntry = pBt->usableSize/5;
  39947. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  39948. nFin = nOrig - nFree - nPtrmap;
  39949. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  39950. nFin--;
  39951. }
  39952. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  39953. nFin--;
  39954. }
  39955. return nFin;
  39956. }
  39957. /*
  39958. ** A write-transaction must be opened before calling this function.
  39959. ** It performs a single unit of work towards an incremental vacuum.
  39960. **
  39961. ** If the incremental vacuum is finished after this function has run,
  39962. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  39963. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  39964. */
  39965. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  39966. int rc;
  39967. BtShared *pBt = p->pBt;
  39968. sqlite3BtreeEnter(p);
  39969. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  39970. if( !pBt->autoVacuum ){
  39971. rc = SQLITE_DONE;
  39972. }else{
  39973. Pgno nOrig = btreePagecount(pBt);
  39974. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  39975. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  39976. if( nOrig<nFin ){
  39977. rc = SQLITE_CORRUPT_BKPT;
  39978. }else if( nFree>0 ){
  39979. rc = saveAllCursors(pBt, 0, 0);
  39980. if( rc==SQLITE_OK ){
  39981. invalidateAllOverflowCache(pBt);
  39982. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  39983. }
  39984. if( rc==SQLITE_OK ){
  39985. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  39986. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  39987. }
  39988. }else{
  39989. rc = SQLITE_DONE;
  39990. }
  39991. }
  39992. sqlite3BtreeLeave(p);
  39993. return rc;
  39994. }
  39995. /*
  39996. ** This routine is called prior to sqlite3PagerCommit when a transaction
  39997. ** is committed for an auto-vacuum database.
  39998. **
  39999. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  40000. ** the database file should be truncated to during the commit process.
  40001. ** i.e. the database has been reorganized so that only the first *pnTrunc
  40002. ** pages are in use.
  40003. */
  40004. static int autoVacuumCommit(BtShared *pBt){
  40005. int rc = SQLITE_OK;
  40006. Pager *pPager = pBt->pPager;
  40007. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  40008. assert( sqlite3_mutex_held(pBt->mutex) );
  40009. invalidateAllOverflowCache(pBt);
  40010. assert(pBt->autoVacuum);
  40011. if( !pBt->incrVacuum ){
  40012. Pgno nFin; /* Number of pages in database after autovacuuming */
  40013. Pgno nFree; /* Number of pages on the freelist initially */
  40014. Pgno iFree; /* The next page to be freed */
  40015. Pgno nOrig; /* Database size before freeing */
  40016. nOrig = btreePagecount(pBt);
  40017. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  40018. /* It is not possible to create a database for which the final page
  40019. ** is either a pointer-map page or the pending-byte page. If one
  40020. ** is encountered, this indicates corruption.
  40021. */
  40022. return SQLITE_CORRUPT_BKPT;
  40023. }
  40024. nFree = get4byte(&pBt->pPage1->aData[36]);
  40025. nFin = finalDbSize(pBt, nOrig, nFree);
  40026. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  40027. if( nFin<nOrig ){
  40028. rc = saveAllCursors(pBt, 0, 0);
  40029. }
  40030. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  40031. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  40032. }
  40033. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  40034. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  40035. put4byte(&pBt->pPage1->aData[32], 0);
  40036. put4byte(&pBt->pPage1->aData[36], 0);
  40037. put4byte(&pBt->pPage1->aData[28], nFin);
  40038. pBt->bDoTruncate = 1;
  40039. pBt->nPage = nFin;
  40040. }
  40041. if( rc!=SQLITE_OK ){
  40042. sqlite3PagerRollback(pPager);
  40043. }
  40044. }
  40045. assert( nRef>=sqlite3PagerRefcount(pPager) );
  40046. return rc;
  40047. }
  40048. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  40049. # define setChildPtrmaps(x) SQLITE_OK
  40050. #endif
  40051. /*
  40052. ** This routine does the first phase of a two-phase commit. This routine
  40053. ** causes a rollback journal to be created (if it does not already exist)
  40054. ** and populated with enough information so that if a power loss occurs
  40055. ** the database can be restored to its original state by playing back
  40056. ** the journal. Then the contents of the journal are flushed out to
  40057. ** the disk. After the journal is safely on oxide, the changes to the
  40058. ** database are written into the database file and flushed to oxide.
  40059. ** At the end of this call, the rollback journal still exists on the
  40060. ** disk and we are still holding all locks, so the transaction has not
  40061. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  40062. ** commit process.
  40063. **
  40064. ** This call is a no-op if no write-transaction is currently active on pBt.
  40065. **
  40066. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  40067. ** the name of a master journal file that should be written into the
  40068. ** individual journal file, or is NULL, indicating no master journal file
  40069. ** (single database transaction).
  40070. **
  40071. ** When this is called, the master journal should already have been
  40072. ** created, populated with this journal pointer and synced to disk.
  40073. **
  40074. ** Once this is routine has returned, the only thing required to commit
  40075. ** the write-transaction for this database file is to delete the journal.
  40076. */
  40077. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  40078. int rc = SQLITE_OK;
  40079. if( p->inTrans==TRANS_WRITE ){
  40080. BtShared *pBt = p->pBt;
  40081. sqlite3BtreeEnter(p);
  40082. #ifndef SQLITE_OMIT_AUTOVACUUM
  40083. if( pBt->autoVacuum ){
  40084. rc = autoVacuumCommit(pBt);
  40085. if( rc!=SQLITE_OK ){
  40086. sqlite3BtreeLeave(p);
  40087. return rc;
  40088. }
  40089. }
  40090. if( pBt->bDoTruncate ){
  40091. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  40092. }
  40093. #endif
  40094. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  40095. sqlite3BtreeLeave(p);
  40096. }
  40097. return rc;
  40098. }
  40099. /*
  40100. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  40101. ** at the conclusion of a transaction.
  40102. */
  40103. static void btreeEndTransaction(Btree *p){
  40104. BtShared *pBt = p->pBt;
  40105. sqlite3 *db = p->db;
  40106. assert( sqlite3BtreeHoldsMutex(p) );
  40107. #ifndef SQLITE_OMIT_AUTOVACUUM
  40108. pBt->bDoTruncate = 0;
  40109. #endif
  40110. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  40111. /* If there are other active statements that belong to this database
  40112. ** handle, downgrade to a read-only transaction. The other statements
  40113. ** may still be reading from the database. */
  40114. downgradeAllSharedCacheTableLocks(p);
  40115. p->inTrans = TRANS_READ;
  40116. }else{
  40117. /* If the handle had any kind of transaction open, decrement the
  40118. ** transaction count of the shared btree. If the transaction count
  40119. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  40120. ** call below will unlock the pager. */
  40121. if( p->inTrans!=TRANS_NONE ){
  40122. clearAllSharedCacheTableLocks(p);
  40123. pBt->nTransaction--;
  40124. if( 0==pBt->nTransaction ){
  40125. pBt->inTransaction = TRANS_NONE;
  40126. }
  40127. }
  40128. /* Set the current transaction state to TRANS_NONE and unlock the
  40129. ** pager if this call closed the only read or write transaction. */
  40130. p->inTrans = TRANS_NONE;
  40131. unlockBtreeIfUnused(pBt);
  40132. }
  40133. btreeIntegrity(p);
  40134. }
  40135. /*
  40136. ** Commit the transaction currently in progress.
  40137. **
  40138. ** This routine implements the second phase of a 2-phase commit. The
  40139. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  40140. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  40141. ** routine did all the work of writing information out to disk and flushing the
  40142. ** contents so that they are written onto the disk platter. All this
  40143. ** routine has to do is delete or truncate or zero the header in the
  40144. ** the rollback journal (which causes the transaction to commit) and
  40145. ** drop locks.
  40146. **
  40147. ** Normally, if an error occurs while the pager layer is attempting to
  40148. ** finalize the underlying journal file, this function returns an error and
  40149. ** the upper layer will attempt a rollback. However, if the second argument
  40150. ** is non-zero then this b-tree transaction is part of a multi-file
  40151. ** transaction. In this case, the transaction has already been committed
  40152. ** (by deleting a master journal file) and the caller will ignore this
  40153. ** functions return code. So, even if an error occurs in the pager layer,
  40154. ** reset the b-tree objects internal state to indicate that the write
  40155. ** transaction has been closed. This is quite safe, as the pager will have
  40156. ** transitioned to the error state.
  40157. **
  40158. ** This will release the write lock on the database file. If there
  40159. ** are no active cursors, it also releases the read lock.
  40160. */
  40161. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  40162. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  40163. sqlite3BtreeEnter(p);
  40164. btreeIntegrity(p);
  40165. /* If the handle has a write-transaction open, commit the shared-btrees
  40166. ** transaction and set the shared state to TRANS_READ.
  40167. */
  40168. if( p->inTrans==TRANS_WRITE ){
  40169. int rc;
  40170. BtShared *pBt = p->pBt;
  40171. assert( pBt->inTransaction==TRANS_WRITE );
  40172. assert( pBt->nTransaction>0 );
  40173. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  40174. if( rc!=SQLITE_OK && bCleanup==0 ){
  40175. sqlite3BtreeLeave(p);
  40176. return rc;
  40177. }
  40178. pBt->inTransaction = TRANS_READ;
  40179. btreeClearHasContent(pBt);
  40180. }
  40181. btreeEndTransaction(p);
  40182. sqlite3BtreeLeave(p);
  40183. return SQLITE_OK;
  40184. }
  40185. /*
  40186. ** Do both phases of a commit.
  40187. */
  40188. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  40189. int rc;
  40190. sqlite3BtreeEnter(p);
  40191. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  40192. if( rc==SQLITE_OK ){
  40193. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  40194. }
  40195. sqlite3BtreeLeave(p);
  40196. return rc;
  40197. }
  40198. /*
  40199. ** This routine sets the state to CURSOR_FAULT and the error
  40200. ** code to errCode for every cursor on BtShared that pBtree
  40201. ** references.
  40202. **
  40203. ** Every cursor is tripped, including cursors that belong
  40204. ** to other database connections that happen to be sharing
  40205. ** the cache with pBtree.
  40206. **
  40207. ** This routine gets called when a rollback occurs.
  40208. ** All cursors using the same cache must be tripped
  40209. ** to prevent them from trying to use the btree after
  40210. ** the rollback. The rollback may have deleted tables
  40211. ** or moved root pages, so it is not sufficient to
  40212. ** save the state of the cursor. The cursor must be
  40213. ** invalidated.
  40214. */
  40215. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  40216. BtCursor *p;
  40217. if( pBtree==0 ) return;
  40218. sqlite3BtreeEnter(pBtree);
  40219. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  40220. int i;
  40221. sqlite3BtreeClearCursor(p);
  40222. p->eState = CURSOR_FAULT;
  40223. p->skipNext = errCode;
  40224. for(i=0; i<=p->iPage; i++){
  40225. releasePage(p->apPage[i]);
  40226. p->apPage[i] = 0;
  40227. }
  40228. }
  40229. sqlite3BtreeLeave(pBtree);
  40230. }
  40231. /*
  40232. ** Rollback the transaction in progress. All cursors will be
  40233. ** invalided by this operation. Any attempt to use a cursor
  40234. ** that was open at the beginning of this operation will result
  40235. ** in an error.
  40236. **
  40237. ** This will release the write lock on the database file. If there
  40238. ** are no active cursors, it also releases the read lock.
  40239. */
  40240. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  40241. int rc;
  40242. BtShared *pBt = p->pBt;
  40243. MemPage *pPage1;
  40244. sqlite3BtreeEnter(p);
  40245. if( tripCode==SQLITE_OK ){
  40246. rc = tripCode = saveAllCursors(pBt, 0, 0);
  40247. }else{
  40248. rc = SQLITE_OK;
  40249. }
  40250. if( tripCode ){
  40251. sqlite3BtreeTripAllCursors(p, tripCode);
  40252. }
  40253. btreeIntegrity(p);
  40254. if( p->inTrans==TRANS_WRITE ){
  40255. int rc2;
  40256. assert( TRANS_WRITE==pBt->inTransaction );
  40257. rc2 = sqlite3PagerRollback(pBt->pPager);
  40258. if( rc2!=SQLITE_OK ){
  40259. rc = rc2;
  40260. }
  40261. /* The rollback may have destroyed the pPage1->aData value. So
  40262. ** call btreeGetPage() on page 1 again to make
  40263. ** sure pPage1->aData is set correctly. */
  40264. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  40265. int nPage = get4byte(28+(u8*)pPage1->aData);
  40266. testcase( nPage==0 );
  40267. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  40268. testcase( pBt->nPage!=nPage );
  40269. pBt->nPage = nPage;
  40270. releasePage(pPage1);
  40271. }
  40272. assert( countValidCursors(pBt, 1)==0 );
  40273. pBt->inTransaction = TRANS_READ;
  40274. btreeClearHasContent(pBt);
  40275. }
  40276. btreeEndTransaction(p);
  40277. sqlite3BtreeLeave(p);
  40278. return rc;
  40279. }
  40280. /*
  40281. ** Start a statement subtransaction. The subtransaction can can be rolled
  40282. ** back independently of the main transaction. You must start a transaction
  40283. ** before starting a subtransaction. The subtransaction is ended automatically
  40284. ** if the main transaction commits or rolls back.
  40285. **
  40286. ** Statement subtransactions are used around individual SQL statements
  40287. ** that are contained within a BEGIN...COMMIT block. If a constraint
  40288. ** error occurs within the statement, the effect of that one statement
  40289. ** can be rolled back without having to rollback the entire transaction.
  40290. **
  40291. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  40292. ** value passed as the second parameter is the total number of savepoints,
  40293. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  40294. ** are no active savepoints and no other statement-transactions open,
  40295. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  40296. ** using the sqlite3BtreeSavepoint() function.
  40297. */
  40298. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  40299. int rc;
  40300. BtShared *pBt = p->pBt;
  40301. sqlite3BtreeEnter(p);
  40302. assert( p->inTrans==TRANS_WRITE );
  40303. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  40304. assert( iStatement>0 );
  40305. assert( iStatement>p->db->nSavepoint );
  40306. assert( pBt->inTransaction==TRANS_WRITE );
  40307. /* At the pager level, a statement transaction is a savepoint with
  40308. ** an index greater than all savepoints created explicitly using
  40309. ** SQL statements. It is illegal to open, release or rollback any
  40310. ** such savepoints while the statement transaction savepoint is active.
  40311. */
  40312. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  40313. sqlite3BtreeLeave(p);
  40314. return rc;
  40315. }
  40316. /*
  40317. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  40318. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  40319. ** savepoint identified by parameter iSavepoint, depending on the value
  40320. ** of op.
  40321. **
  40322. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  40323. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  40324. ** contents of the entire transaction are rolled back. This is different
  40325. ** from a normal transaction rollback, as no locks are released and the
  40326. ** transaction remains open.
  40327. */
  40328. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  40329. int rc = SQLITE_OK;
  40330. if( p && p->inTrans==TRANS_WRITE ){
  40331. BtShared *pBt = p->pBt;
  40332. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  40333. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  40334. sqlite3BtreeEnter(p);
  40335. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  40336. if( rc==SQLITE_OK ){
  40337. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  40338. pBt->nPage = 0;
  40339. }
  40340. rc = newDatabase(pBt);
  40341. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  40342. /* The database size was written into the offset 28 of the header
  40343. ** when the transaction started, so we know that the value at offset
  40344. ** 28 is nonzero. */
  40345. assert( pBt->nPage>0 );
  40346. }
  40347. sqlite3BtreeLeave(p);
  40348. }
  40349. return rc;
  40350. }
  40351. /*
  40352. ** Create a new cursor for the BTree whose root is on the page
  40353. ** iTable. If a read-only cursor is requested, it is assumed that
  40354. ** the caller already has at least a read-only transaction open
  40355. ** on the database already. If a write-cursor is requested, then
  40356. ** the caller is assumed to have an open write transaction.
  40357. **
  40358. ** If wrFlag==0, then the cursor can only be used for reading.
  40359. ** If wrFlag==1, then the cursor can be used for reading or for
  40360. ** writing if other conditions for writing are also met. These
  40361. ** are the conditions that must be met in order for writing to
  40362. ** be allowed:
  40363. **
  40364. ** 1: The cursor must have been opened with wrFlag==1
  40365. **
  40366. ** 2: Other database connections that share the same pager cache
  40367. ** but which are not in the READ_UNCOMMITTED state may not have
  40368. ** cursors open with wrFlag==0 on the same table. Otherwise
  40369. ** the changes made by this write cursor would be visible to
  40370. ** the read cursors in the other database connection.
  40371. **
  40372. ** 3: The database must be writable (not on read-only media)
  40373. **
  40374. ** 4: There must be an active transaction.
  40375. **
  40376. ** No checking is done to make sure that page iTable really is the
  40377. ** root page of a b-tree. If it is not, then the cursor acquired
  40378. ** will not work correctly.
  40379. **
  40380. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  40381. ** on pCur to initialize the memory space prior to invoking this routine.
  40382. */
  40383. static int btreeCursor(
  40384. Btree *p, /* The btree */
  40385. int iTable, /* Root page of table to open */
  40386. int wrFlag, /* 1 to write. 0 read-only */
  40387. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  40388. BtCursor *pCur /* Space for new cursor */
  40389. ){
  40390. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  40391. assert( sqlite3BtreeHoldsMutex(p) );
  40392. assert( wrFlag==0 || wrFlag==1 );
  40393. /* The following assert statements verify that if this is a sharable
  40394. ** b-tree database, the connection is holding the required table locks,
  40395. ** and that no other connection has any open cursor that conflicts with
  40396. ** this lock. */
  40397. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  40398. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  40399. /* Assert that the caller has opened the required transaction. */
  40400. assert( p->inTrans>TRANS_NONE );
  40401. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  40402. assert( pBt->pPage1 && pBt->pPage1->aData );
  40403. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  40404. return SQLITE_READONLY;
  40405. }
  40406. if( iTable==1 && btreePagecount(pBt)==0 ){
  40407. assert( wrFlag==0 );
  40408. iTable = 0;
  40409. }
  40410. /* Now that no other errors can occur, finish filling in the BtCursor
  40411. ** variables and link the cursor into the BtShared list. */
  40412. pCur->pgnoRoot = (Pgno)iTable;
  40413. pCur->iPage = -1;
  40414. pCur->pKeyInfo = pKeyInfo;
  40415. pCur->pBtree = p;
  40416. pCur->pBt = pBt;
  40417. pCur->wrFlag = (u8)wrFlag;
  40418. pCur->pNext = pBt->pCursor;
  40419. if( pCur->pNext ){
  40420. pCur->pNext->pPrev = pCur;
  40421. }
  40422. pBt->pCursor = pCur;
  40423. pCur->eState = CURSOR_INVALID;
  40424. pCur->cachedRowid = 0;
  40425. return SQLITE_OK;
  40426. }
  40427. SQLITE_PRIVATE int sqlite3BtreeCursor(
  40428. Btree *p, /* The btree */
  40429. int iTable, /* Root page of table to open */
  40430. int wrFlag, /* 1 to write. 0 read-only */
  40431. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  40432. BtCursor *pCur /* Write new cursor here */
  40433. ){
  40434. int rc;
  40435. sqlite3BtreeEnter(p);
  40436. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  40437. sqlite3BtreeLeave(p);
  40438. return rc;
  40439. }
  40440. /*
  40441. ** Return the size of a BtCursor object in bytes.
  40442. **
  40443. ** This interfaces is needed so that users of cursors can preallocate
  40444. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  40445. ** to users so they cannot do the sizeof() themselves - they must call
  40446. ** this routine.
  40447. */
  40448. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  40449. return ROUND8(sizeof(BtCursor));
  40450. }
  40451. /*
  40452. ** Initialize memory that will be converted into a BtCursor object.
  40453. **
  40454. ** The simple approach here would be to memset() the entire object
  40455. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  40456. ** do not need to be zeroed and they are large, so we can save a lot
  40457. ** of run-time by skipping the initialization of those elements.
  40458. */
  40459. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  40460. memset(p, 0, offsetof(BtCursor, iPage));
  40461. }
  40462. /*
  40463. ** Set the cached rowid value of every cursor in the same database file
  40464. ** as pCur and having the same root page number as pCur. The value is
  40465. ** set to iRowid.
  40466. **
  40467. ** Only positive rowid values are considered valid for this cache.
  40468. ** The cache is initialized to zero, indicating an invalid cache.
  40469. ** A btree will work fine with zero or negative rowids. We just cannot
  40470. ** cache zero or negative rowids, which means tables that use zero or
  40471. ** negative rowids might run a little slower. But in practice, zero
  40472. ** or negative rowids are very uncommon so this should not be a problem.
  40473. */
  40474. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  40475. BtCursor *p;
  40476. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  40477. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  40478. }
  40479. assert( pCur->cachedRowid==iRowid );
  40480. }
  40481. /*
  40482. ** Return the cached rowid for the given cursor. A negative or zero
  40483. ** return value indicates that the rowid cache is invalid and should be
  40484. ** ignored. If the rowid cache has never before been set, then a
  40485. ** zero is returned.
  40486. */
  40487. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  40488. return pCur->cachedRowid;
  40489. }
  40490. /*
  40491. ** Close a cursor. The read lock on the database file is released
  40492. ** when the last cursor is closed.
  40493. */
  40494. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  40495. Btree *pBtree = pCur->pBtree;
  40496. if( pBtree ){
  40497. int i;
  40498. BtShared *pBt = pCur->pBt;
  40499. sqlite3BtreeEnter(pBtree);
  40500. sqlite3BtreeClearCursor(pCur);
  40501. if( pCur->pPrev ){
  40502. pCur->pPrev->pNext = pCur->pNext;
  40503. }else{
  40504. pBt->pCursor = pCur->pNext;
  40505. }
  40506. if( pCur->pNext ){
  40507. pCur->pNext->pPrev = pCur->pPrev;
  40508. }
  40509. for(i=0; i<=pCur->iPage; i++){
  40510. releasePage(pCur->apPage[i]);
  40511. }
  40512. unlockBtreeIfUnused(pBt);
  40513. invalidateOverflowCache(pCur);
  40514. /* sqlite3_free(pCur); */
  40515. sqlite3BtreeLeave(pBtree);
  40516. }
  40517. return SQLITE_OK;
  40518. }
  40519. /*
  40520. ** Make sure the BtCursor* given in the argument has a valid
  40521. ** BtCursor.info structure. If it is not already valid, call
  40522. ** btreeParseCell() to fill it in.
  40523. **
  40524. ** BtCursor.info is a cache of the information in the current cell.
  40525. ** Using this cache reduces the number of calls to btreeParseCell().
  40526. **
  40527. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  40528. ** compiler to crash when getCellInfo() is implemented as a macro.
  40529. ** But there is a measureable speed advantage to using the macro on gcc
  40530. ** (when less compiler optimizations like -Os or -O0 are used and the
  40531. ** compiler is not doing agressive inlining.) So we use a real function
  40532. ** for MSVC and a macro for everything else. Ticket #2457.
  40533. */
  40534. #ifndef NDEBUG
  40535. static void assertCellInfo(BtCursor *pCur){
  40536. CellInfo info;
  40537. int iPage = pCur->iPage;
  40538. memset(&info, 0, sizeof(info));
  40539. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  40540. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  40541. }
  40542. #else
  40543. #define assertCellInfo(x)
  40544. #endif
  40545. #ifdef _MSC_VER
  40546. /* Use a real function in MSVC to work around bugs in that compiler. */
  40547. static void getCellInfo(BtCursor *pCur){
  40548. if( pCur->info.nSize==0 ){
  40549. int iPage = pCur->iPage;
  40550. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  40551. pCur->validNKey = 1;
  40552. }else{
  40553. assertCellInfo(pCur);
  40554. }
  40555. }
  40556. #else /* if not _MSC_VER */
  40557. /* Use a macro in all other compilers so that the function is inlined */
  40558. #define getCellInfo(pCur) \
  40559. if( pCur->info.nSize==0 ){ \
  40560. int iPage = pCur->iPage; \
  40561. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  40562. pCur->validNKey = 1; \
  40563. }else{ \
  40564. assertCellInfo(pCur); \
  40565. }
  40566. #endif /* _MSC_VER */
  40567. #ifndef NDEBUG /* The next routine used only within assert() statements */
  40568. /*
  40569. ** Return true if the given BtCursor is valid. A valid cursor is one
  40570. ** that is currently pointing to a row in a (non-empty) table.
  40571. ** This is a verification routine is used only within assert() statements.
  40572. */
  40573. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  40574. return pCur && pCur->eState==CURSOR_VALID;
  40575. }
  40576. #endif /* NDEBUG */
  40577. /*
  40578. ** Set *pSize to the size of the buffer needed to hold the value of
  40579. ** the key for the current entry. If the cursor is not pointing
  40580. ** to a valid entry, *pSize is set to 0.
  40581. **
  40582. ** For a table with the INTKEY flag set, this routine returns the key
  40583. ** itself, not the number of bytes in the key.
  40584. **
  40585. ** The caller must position the cursor prior to invoking this routine.
  40586. **
  40587. ** This routine cannot fail. It always returns SQLITE_OK.
  40588. */
  40589. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  40590. assert( cursorHoldsMutex(pCur) );
  40591. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  40592. if( pCur->eState!=CURSOR_VALID ){
  40593. *pSize = 0;
  40594. }else{
  40595. getCellInfo(pCur);
  40596. *pSize = pCur->info.nKey;
  40597. }
  40598. return SQLITE_OK;
  40599. }
  40600. /*
  40601. ** Set *pSize to the number of bytes of data in the entry the
  40602. ** cursor currently points to.
  40603. **
  40604. ** The caller must guarantee that the cursor is pointing to a non-NULL
  40605. ** valid entry. In other words, the calling procedure must guarantee
  40606. ** that the cursor has Cursor.eState==CURSOR_VALID.
  40607. **
  40608. ** Failure is not possible. This function always returns SQLITE_OK.
  40609. ** It might just as well be a procedure (returning void) but we continue
  40610. ** to return an integer result code for historical reasons.
  40611. */
  40612. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  40613. assert( cursorHoldsMutex(pCur) );
  40614. assert( pCur->eState==CURSOR_VALID );
  40615. getCellInfo(pCur);
  40616. *pSize = pCur->info.nData;
  40617. return SQLITE_OK;
  40618. }
  40619. /*
  40620. ** Given the page number of an overflow page in the database (parameter
  40621. ** ovfl), this function finds the page number of the next page in the
  40622. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  40623. ** pointer-map data instead of reading the content of page ovfl to do so.
  40624. **
  40625. ** If an error occurs an SQLite error code is returned. Otherwise:
  40626. **
  40627. ** The page number of the next overflow page in the linked list is
  40628. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  40629. ** list, *pPgnoNext is set to zero.
  40630. **
  40631. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  40632. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  40633. ** reference. It is the responsibility of the caller to call releasePage()
  40634. ** on *ppPage to free the reference. In no reference was obtained (because
  40635. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  40636. ** *ppPage is set to zero.
  40637. */
  40638. static int getOverflowPage(
  40639. BtShared *pBt, /* The database file */
  40640. Pgno ovfl, /* Current overflow page number */
  40641. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  40642. Pgno *pPgnoNext /* OUT: Next overflow page number */
  40643. ){
  40644. Pgno next = 0;
  40645. MemPage *pPage = 0;
  40646. int rc = SQLITE_OK;
  40647. assert( sqlite3_mutex_held(pBt->mutex) );
  40648. assert(pPgnoNext);
  40649. #ifndef SQLITE_OMIT_AUTOVACUUM
  40650. /* Try to find the next page in the overflow list using the
  40651. ** autovacuum pointer-map pages. Guess that the next page in
  40652. ** the overflow list is page number (ovfl+1). If that guess turns
  40653. ** out to be wrong, fall back to loading the data of page
  40654. ** number ovfl to determine the next page number.
  40655. */
  40656. if( pBt->autoVacuum ){
  40657. Pgno pgno;
  40658. Pgno iGuess = ovfl+1;
  40659. u8 eType;
  40660. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  40661. iGuess++;
  40662. }
  40663. if( iGuess<=btreePagecount(pBt) ){
  40664. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  40665. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  40666. next = iGuess;
  40667. rc = SQLITE_DONE;
  40668. }
  40669. }
  40670. }
  40671. #endif
  40672. assert( next==0 || rc==SQLITE_DONE );
  40673. if( rc==SQLITE_OK ){
  40674. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  40675. assert( rc==SQLITE_OK || pPage==0 );
  40676. if( rc==SQLITE_OK ){
  40677. next = get4byte(pPage->aData);
  40678. }
  40679. }
  40680. *pPgnoNext = next;
  40681. if( ppPage ){
  40682. *ppPage = pPage;
  40683. }else{
  40684. releasePage(pPage);
  40685. }
  40686. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  40687. }
  40688. /*
  40689. ** Copy data from a buffer to a page, or from a page to a buffer.
  40690. **
  40691. ** pPayload is a pointer to data stored on database page pDbPage.
  40692. ** If argument eOp is false, then nByte bytes of data are copied
  40693. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  40694. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  40695. ** of data are copied from the buffer pBuf to pPayload.
  40696. **
  40697. ** SQLITE_OK is returned on success, otherwise an error code.
  40698. */
  40699. static int copyPayload(
  40700. void *pPayload, /* Pointer to page data */
  40701. void *pBuf, /* Pointer to buffer */
  40702. int nByte, /* Number of bytes to copy */
  40703. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  40704. DbPage *pDbPage /* Page containing pPayload */
  40705. ){
  40706. if( eOp ){
  40707. /* Copy data from buffer to page (a write operation) */
  40708. int rc = sqlite3PagerWrite(pDbPage);
  40709. if( rc!=SQLITE_OK ){
  40710. return rc;
  40711. }
  40712. memcpy(pPayload, pBuf, nByte);
  40713. }else{
  40714. /* Copy data from page to buffer (a read operation) */
  40715. memcpy(pBuf, pPayload, nByte);
  40716. }
  40717. return SQLITE_OK;
  40718. }
  40719. /*
  40720. ** This function is used to read or overwrite payload information
  40721. ** for the entry that the pCur cursor is pointing to. If the eOp
  40722. ** parameter is 0, this is a read operation (data copied into
  40723. ** buffer pBuf). If it is non-zero, a write (data copied from
  40724. ** buffer pBuf).
  40725. **
  40726. ** A total of "amt" bytes are read or written beginning at "offset".
  40727. ** Data is read to or from the buffer pBuf.
  40728. **
  40729. ** The content being read or written might appear on the main page
  40730. ** or be scattered out on multiple overflow pages.
  40731. **
  40732. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  40733. ** cursor entry uses one or more overflow pages, this function
  40734. ** allocates space for and lazily popluates the overflow page-list
  40735. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  40736. ** cache to make seeking to the supplied offset more efficient.
  40737. **
  40738. ** Once an overflow page-list cache has been allocated, it may be
  40739. ** invalidated if some other cursor writes to the same table, or if
  40740. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  40741. ** mode, the following events may invalidate an overflow page-list cache.
  40742. **
  40743. ** * An incremental vacuum,
  40744. ** * A commit in auto_vacuum="full" mode,
  40745. ** * Creating a table (may require moving an overflow page).
  40746. */
  40747. static int accessPayload(
  40748. BtCursor *pCur, /* Cursor pointing to entry to read from */
  40749. u32 offset, /* Begin reading this far into payload */
  40750. u32 amt, /* Read this many bytes */
  40751. unsigned char *pBuf, /* Write the bytes into this buffer */
  40752. int eOp /* zero to read. non-zero to write. */
  40753. ){
  40754. unsigned char *aPayload;
  40755. int rc = SQLITE_OK;
  40756. u32 nKey;
  40757. int iIdx = 0;
  40758. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  40759. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  40760. assert( pPage );
  40761. assert( pCur->eState==CURSOR_VALID );
  40762. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  40763. assert( cursorHoldsMutex(pCur) );
  40764. getCellInfo(pCur);
  40765. aPayload = pCur->info.pCell + pCur->info.nHeader;
  40766. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  40767. if( NEVER(offset+amt > nKey+pCur->info.nData)
  40768. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  40769. ){
  40770. /* Trying to read or write past the end of the data is an error */
  40771. return SQLITE_CORRUPT_BKPT;
  40772. }
  40773. /* Check if data must be read/written to/from the btree page itself. */
  40774. if( offset<pCur->info.nLocal ){
  40775. int a = amt;
  40776. if( a+offset>pCur->info.nLocal ){
  40777. a = pCur->info.nLocal - offset;
  40778. }
  40779. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  40780. offset = 0;
  40781. pBuf += a;
  40782. amt -= a;
  40783. }else{
  40784. offset -= pCur->info.nLocal;
  40785. }
  40786. if( rc==SQLITE_OK && amt>0 ){
  40787. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  40788. Pgno nextPage;
  40789. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  40790. #ifndef SQLITE_OMIT_INCRBLOB
  40791. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  40792. ** has not been allocated, allocate it now. The array is sized at
  40793. ** one entry for each overflow page in the overflow chain. The
  40794. ** page number of the first overflow page is stored in aOverflow[0],
  40795. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  40796. ** (the cache is lazily populated).
  40797. */
  40798. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  40799. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  40800. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  40801. /* nOvfl is always positive. If it were zero, fetchPayload would have
  40802. ** been used instead of this routine. */
  40803. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  40804. rc = SQLITE_NOMEM;
  40805. }
  40806. }
  40807. /* If the overflow page-list cache has been allocated and the
  40808. ** entry for the first required overflow page is valid, skip
  40809. ** directly to it.
  40810. */
  40811. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  40812. iIdx = (offset/ovflSize);
  40813. nextPage = pCur->aOverflow[iIdx];
  40814. offset = (offset%ovflSize);
  40815. }
  40816. #endif
  40817. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  40818. #ifndef SQLITE_OMIT_INCRBLOB
  40819. /* If required, populate the overflow page-list cache. */
  40820. if( pCur->aOverflow ){
  40821. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  40822. pCur->aOverflow[iIdx] = nextPage;
  40823. }
  40824. #endif
  40825. if( offset>=ovflSize ){
  40826. /* The only reason to read this page is to obtain the page
  40827. ** number for the next page in the overflow chain. The page
  40828. ** data is not required. So first try to lookup the overflow
  40829. ** page-list cache, if any, then fall back to the getOverflowPage()
  40830. ** function.
  40831. */
  40832. #ifndef SQLITE_OMIT_INCRBLOB
  40833. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  40834. nextPage = pCur->aOverflow[iIdx+1];
  40835. } else
  40836. #endif
  40837. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  40838. offset -= ovflSize;
  40839. }else{
  40840. /* Need to read this page properly. It contains some of the
  40841. ** range of data that is being read (eOp==0) or written (eOp!=0).
  40842. */
  40843. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  40844. sqlite3_file *fd;
  40845. #endif
  40846. int a = amt;
  40847. if( a + offset > ovflSize ){
  40848. a = ovflSize - offset;
  40849. }
  40850. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  40851. /* If all the following are true:
  40852. **
  40853. ** 1) this is a read operation, and
  40854. ** 2) data is required from the start of this overflow page, and
  40855. ** 3) the database is file-backed, and
  40856. ** 4) there is no open write-transaction, and
  40857. ** 5) the database is not a WAL database,
  40858. **
  40859. ** then data can be read directly from the database file into the
  40860. ** output buffer, bypassing the page-cache altogether. This speeds
  40861. ** up loading large records that span many overflow pages.
  40862. */
  40863. if( eOp==0 /* (1) */
  40864. && offset==0 /* (2) */
  40865. && pBt->inTransaction==TRANS_READ /* (4) */
  40866. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  40867. && pBt->pPage1->aData[19]==0x01 /* (5) */
  40868. ){
  40869. u8 aSave[4];
  40870. u8 *aWrite = &pBuf[-4];
  40871. memcpy(aSave, aWrite, 4);
  40872. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  40873. nextPage = get4byte(aWrite);
  40874. memcpy(aWrite, aSave, 4);
  40875. }else
  40876. #endif
  40877. {
  40878. DbPage *pDbPage;
  40879. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  40880. (eOp==0 ? PAGER_GET_READONLY : 0)
  40881. );
  40882. if( rc==SQLITE_OK ){
  40883. aPayload = sqlite3PagerGetData(pDbPage);
  40884. nextPage = get4byte(aPayload);
  40885. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  40886. sqlite3PagerUnref(pDbPage);
  40887. offset = 0;
  40888. }
  40889. }
  40890. amt -= a;
  40891. pBuf += a;
  40892. }
  40893. }
  40894. }
  40895. if( rc==SQLITE_OK && amt>0 ){
  40896. return SQLITE_CORRUPT_BKPT;
  40897. }
  40898. return rc;
  40899. }
  40900. /*
  40901. ** Read part of the key associated with cursor pCur. Exactly
  40902. ** "amt" bytes will be transfered into pBuf[]. The transfer
  40903. ** begins at "offset".
  40904. **
  40905. ** The caller must ensure that pCur is pointing to a valid row
  40906. ** in the table.
  40907. **
  40908. ** Return SQLITE_OK on success or an error code if anything goes
  40909. ** wrong. An error is returned if "offset+amt" is larger than
  40910. ** the available payload.
  40911. */
  40912. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  40913. assert( cursorHoldsMutex(pCur) );
  40914. assert( pCur->eState==CURSOR_VALID );
  40915. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  40916. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  40917. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  40918. }
  40919. /*
  40920. ** Read part of the data associated with cursor pCur. Exactly
  40921. ** "amt" bytes will be transfered into pBuf[]. The transfer
  40922. ** begins at "offset".
  40923. **
  40924. ** Return SQLITE_OK on success or an error code if anything goes
  40925. ** wrong. An error is returned if "offset+amt" is larger than
  40926. ** the available payload.
  40927. */
  40928. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  40929. int rc;
  40930. #ifndef SQLITE_OMIT_INCRBLOB
  40931. if ( pCur->eState==CURSOR_INVALID ){
  40932. return SQLITE_ABORT;
  40933. }
  40934. #endif
  40935. assert( cursorHoldsMutex(pCur) );
  40936. rc = restoreCursorPosition(pCur);
  40937. if( rc==SQLITE_OK ){
  40938. assert( pCur->eState==CURSOR_VALID );
  40939. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  40940. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  40941. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  40942. }
  40943. return rc;
  40944. }
  40945. /*
  40946. ** Return a pointer to payload information from the entry that the
  40947. ** pCur cursor is pointing to. The pointer is to the beginning of
  40948. ** the key if skipKey==0 and it points to the beginning of data if
  40949. ** skipKey==1. The number of bytes of available key/data is written
  40950. ** into *pAmt. If *pAmt==0, then the value returned will not be
  40951. ** a valid pointer.
  40952. **
  40953. ** This routine is an optimization. It is common for the entire key
  40954. ** and data to fit on the local page and for there to be no overflow
  40955. ** pages. When that is so, this routine can be used to access the
  40956. ** key and data without making a copy. If the key and/or data spills
  40957. ** onto overflow pages, then accessPayload() must be used to reassemble
  40958. ** the key/data and copy it into a preallocated buffer.
  40959. **
  40960. ** The pointer returned by this routine looks directly into the cached
  40961. ** page of the database. The data might change or move the next time
  40962. ** any btree routine is called.
  40963. */
  40964. static const unsigned char *fetchPayload(
  40965. BtCursor *pCur, /* Cursor pointing to entry to read from */
  40966. int *pAmt, /* Write the number of available bytes here */
  40967. int skipKey /* read beginning at data if this is true */
  40968. ){
  40969. unsigned char *aPayload;
  40970. MemPage *pPage;
  40971. u32 nKey;
  40972. u32 nLocal;
  40973. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  40974. assert( pCur->eState==CURSOR_VALID );
  40975. assert( cursorHoldsMutex(pCur) );
  40976. pPage = pCur->apPage[pCur->iPage];
  40977. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  40978. if( NEVER(pCur->info.nSize==0) ){
  40979. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  40980. &pCur->info);
  40981. }
  40982. aPayload = pCur->info.pCell;
  40983. aPayload += pCur->info.nHeader;
  40984. if( pPage->intKey ){
  40985. nKey = 0;
  40986. }else{
  40987. nKey = (int)pCur->info.nKey;
  40988. }
  40989. if( skipKey ){
  40990. aPayload += nKey;
  40991. nLocal = pCur->info.nLocal - nKey;
  40992. }else{
  40993. nLocal = pCur->info.nLocal;
  40994. assert( nLocal<=nKey );
  40995. }
  40996. *pAmt = nLocal;
  40997. return aPayload;
  40998. }
  40999. /*
  41000. ** For the entry that cursor pCur is point to, return as
  41001. ** many bytes of the key or data as are available on the local
  41002. ** b-tree page. Write the number of available bytes into *pAmt.
  41003. **
  41004. ** The pointer returned is ephemeral. The key/data may move
  41005. ** or be destroyed on the next call to any Btree routine,
  41006. ** including calls from other threads against the same cache.
  41007. ** Hence, a mutex on the BtShared should be held prior to calling
  41008. ** this routine.
  41009. **
  41010. ** These routines is used to get quick access to key and data
  41011. ** in the common case where no overflow pages are used.
  41012. */
  41013. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  41014. const void *p = 0;
  41015. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41016. assert( cursorHoldsMutex(pCur) );
  41017. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  41018. p = (const void*)fetchPayload(pCur, pAmt, 0);
  41019. }
  41020. return p;
  41021. }
  41022. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  41023. const void *p = 0;
  41024. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41025. assert( cursorHoldsMutex(pCur) );
  41026. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  41027. p = (const void*)fetchPayload(pCur, pAmt, 1);
  41028. }
  41029. return p;
  41030. }
  41031. /*
  41032. ** Move the cursor down to a new child page. The newPgno argument is the
  41033. ** page number of the child page to move to.
  41034. **
  41035. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  41036. ** the new child page does not match the flags field of the parent (i.e.
  41037. ** if an intkey page appears to be the parent of a non-intkey page, or
  41038. ** vice-versa).
  41039. */
  41040. static int moveToChild(BtCursor *pCur, u32 newPgno){
  41041. int rc;
  41042. int i = pCur->iPage;
  41043. MemPage *pNewPage;
  41044. BtShared *pBt = pCur->pBt;
  41045. assert( cursorHoldsMutex(pCur) );
  41046. assert( pCur->eState==CURSOR_VALID );
  41047. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  41048. assert( pCur->iPage>=0 );
  41049. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  41050. return SQLITE_CORRUPT_BKPT;
  41051. }
  41052. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  41053. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  41054. if( rc ) return rc;
  41055. pCur->apPage[i+1] = pNewPage;
  41056. pCur->aiIdx[i+1] = 0;
  41057. pCur->iPage++;
  41058. pCur->info.nSize = 0;
  41059. pCur->validNKey = 0;
  41060. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  41061. return SQLITE_CORRUPT_BKPT;
  41062. }
  41063. return SQLITE_OK;
  41064. }
  41065. #if 0
  41066. /*
  41067. ** Page pParent is an internal (non-leaf) tree page. This function
  41068. ** asserts that page number iChild is the left-child if the iIdx'th
  41069. ** cell in page pParent. Or, if iIdx is equal to the total number of
  41070. ** cells in pParent, that page number iChild is the right-child of
  41071. ** the page.
  41072. */
  41073. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  41074. assert( iIdx<=pParent->nCell );
  41075. if( iIdx==pParent->nCell ){
  41076. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  41077. }else{
  41078. assert( get4byte(findCell(pParent, iIdx))==iChild );
  41079. }
  41080. }
  41081. #else
  41082. # define assertParentIndex(x,y,z)
  41083. #endif
  41084. /*
  41085. ** Move the cursor up to the parent page.
  41086. **
  41087. ** pCur->idx is set to the cell index that contains the pointer
  41088. ** to the page we are coming from. If we are coming from the
  41089. ** right-most child page then pCur->idx is set to one more than
  41090. ** the largest cell index.
  41091. */
  41092. static void moveToParent(BtCursor *pCur){
  41093. assert( cursorHoldsMutex(pCur) );
  41094. assert( pCur->eState==CURSOR_VALID );
  41095. assert( pCur->iPage>0 );
  41096. assert( pCur->apPage[pCur->iPage] );
  41097. /* UPDATE: It is actually possible for the condition tested by the assert
  41098. ** below to be untrue if the database file is corrupt. This can occur if
  41099. ** one cursor has modified page pParent while a reference to it is held
  41100. ** by a second cursor. Which can only happen if a single page is linked
  41101. ** into more than one b-tree structure in a corrupt database. */
  41102. #if 0
  41103. assertParentIndex(
  41104. pCur->apPage[pCur->iPage-1],
  41105. pCur->aiIdx[pCur->iPage-1],
  41106. pCur->apPage[pCur->iPage]->pgno
  41107. );
  41108. #endif
  41109. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  41110. releasePage(pCur->apPage[pCur->iPage]);
  41111. pCur->iPage--;
  41112. pCur->info.nSize = 0;
  41113. pCur->validNKey = 0;
  41114. }
  41115. /*
  41116. ** Move the cursor to point to the root page of its b-tree structure.
  41117. **
  41118. ** If the table has a virtual root page, then the cursor is moved to point
  41119. ** to the virtual root page instead of the actual root page. A table has a
  41120. ** virtual root page when the actual root page contains no cells and a
  41121. ** single child page. This can only happen with the table rooted at page 1.
  41122. **
  41123. ** If the b-tree structure is empty, the cursor state is set to
  41124. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  41125. ** cell located on the root (or virtual root) page and the cursor state
  41126. ** is set to CURSOR_VALID.
  41127. **
  41128. ** If this function returns successfully, it may be assumed that the
  41129. ** page-header flags indicate that the [virtual] root-page is the expected
  41130. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  41131. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  41132. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  41133. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  41134. ** b-tree).
  41135. */
  41136. static int moveToRoot(BtCursor *pCur){
  41137. MemPage *pRoot;
  41138. int rc = SQLITE_OK;
  41139. Btree *p = pCur->pBtree;
  41140. BtShared *pBt = p->pBt;
  41141. assert( cursorHoldsMutex(pCur) );
  41142. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  41143. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  41144. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  41145. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  41146. if( pCur->eState==CURSOR_FAULT ){
  41147. assert( pCur->skipNext!=SQLITE_OK );
  41148. return pCur->skipNext;
  41149. }
  41150. sqlite3BtreeClearCursor(pCur);
  41151. }
  41152. if( pCur->iPage>=0 ){
  41153. int i;
  41154. for(i=1; i<=pCur->iPage; i++){
  41155. releasePage(pCur->apPage[i]);
  41156. }
  41157. pCur->iPage = 0;
  41158. }else if( pCur->pgnoRoot==0 ){
  41159. pCur->eState = CURSOR_INVALID;
  41160. return SQLITE_OK;
  41161. }else{
  41162. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
  41163. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  41164. if( rc!=SQLITE_OK ){
  41165. pCur->eState = CURSOR_INVALID;
  41166. return rc;
  41167. }
  41168. pCur->iPage = 0;
  41169. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  41170. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  41171. ** NULL, the caller expects a table b-tree. If this is not the case,
  41172. ** return an SQLITE_CORRUPT error. */
  41173. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  41174. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  41175. return SQLITE_CORRUPT_BKPT;
  41176. }
  41177. }
  41178. /* Assert that the root page is of the correct type. This must be the
  41179. ** case as the call to this function that loaded the root-page (either
  41180. ** this call or a previous invocation) would have detected corruption
  41181. ** if the assumption were not true, and it is not possible for the flags
  41182. ** byte to have been modified while this cursor is holding a reference
  41183. ** to the page. */
  41184. pRoot = pCur->apPage[0];
  41185. assert( pRoot->pgno==pCur->pgnoRoot );
  41186. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  41187. pCur->aiIdx[0] = 0;
  41188. pCur->info.nSize = 0;
  41189. pCur->atLast = 0;
  41190. pCur->validNKey = 0;
  41191. if( pRoot->nCell==0 && !pRoot->leaf ){
  41192. Pgno subpage;
  41193. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  41194. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  41195. pCur->eState = CURSOR_VALID;
  41196. rc = moveToChild(pCur, subpage);
  41197. }else{
  41198. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  41199. }
  41200. return rc;
  41201. }
  41202. /*
  41203. ** Move the cursor down to the left-most leaf entry beneath the
  41204. ** entry to which it is currently pointing.
  41205. **
  41206. ** The left-most leaf is the one with the smallest key - the first
  41207. ** in ascending order.
  41208. */
  41209. static int moveToLeftmost(BtCursor *pCur){
  41210. Pgno pgno;
  41211. int rc = SQLITE_OK;
  41212. MemPage *pPage;
  41213. assert( cursorHoldsMutex(pCur) );
  41214. assert( pCur->eState==CURSOR_VALID );
  41215. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  41216. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  41217. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  41218. rc = moveToChild(pCur, pgno);
  41219. }
  41220. return rc;
  41221. }
  41222. /*
  41223. ** Move the cursor down to the right-most leaf entry beneath the
  41224. ** page to which it is currently pointing. Notice the difference
  41225. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  41226. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  41227. ** finds the right-most entry beneath the *page*.
  41228. **
  41229. ** The right-most entry is the one with the largest key - the last
  41230. ** key in ascending order.
  41231. */
  41232. static int moveToRightmost(BtCursor *pCur){
  41233. Pgno pgno;
  41234. int rc = SQLITE_OK;
  41235. MemPage *pPage = 0;
  41236. assert( cursorHoldsMutex(pCur) );
  41237. assert( pCur->eState==CURSOR_VALID );
  41238. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  41239. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  41240. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  41241. rc = moveToChild(pCur, pgno);
  41242. }
  41243. if( rc==SQLITE_OK ){
  41244. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  41245. pCur->info.nSize = 0;
  41246. pCur->validNKey = 0;
  41247. }
  41248. return rc;
  41249. }
  41250. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  41251. ** on success. Set *pRes to 0 if the cursor actually points to something
  41252. ** or set *pRes to 1 if the table is empty.
  41253. */
  41254. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  41255. int rc;
  41256. assert( cursorHoldsMutex(pCur) );
  41257. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41258. rc = moveToRoot(pCur);
  41259. if( rc==SQLITE_OK ){
  41260. if( pCur->eState==CURSOR_INVALID ){
  41261. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41262. *pRes = 1;
  41263. }else{
  41264. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  41265. *pRes = 0;
  41266. rc = moveToLeftmost(pCur);
  41267. }
  41268. }
  41269. return rc;
  41270. }
  41271. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  41272. ** on success. Set *pRes to 0 if the cursor actually points to something
  41273. ** or set *pRes to 1 if the table is empty.
  41274. */
  41275. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  41276. int rc;
  41277. assert( cursorHoldsMutex(pCur) );
  41278. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41279. /* If the cursor already points to the last entry, this is a no-op. */
  41280. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  41281. #ifdef SQLITE_DEBUG
  41282. /* This block serves to assert() that the cursor really does point
  41283. ** to the last entry in the b-tree. */
  41284. int ii;
  41285. for(ii=0; ii<pCur->iPage; ii++){
  41286. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  41287. }
  41288. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  41289. assert( pCur->apPage[pCur->iPage]->leaf );
  41290. #endif
  41291. return SQLITE_OK;
  41292. }
  41293. rc = moveToRoot(pCur);
  41294. if( rc==SQLITE_OK ){
  41295. if( CURSOR_INVALID==pCur->eState ){
  41296. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41297. *pRes = 1;
  41298. }else{
  41299. assert( pCur->eState==CURSOR_VALID );
  41300. *pRes = 0;
  41301. rc = moveToRightmost(pCur);
  41302. pCur->atLast = rc==SQLITE_OK ?1:0;
  41303. }
  41304. }
  41305. return rc;
  41306. }
  41307. /* Move the cursor so that it points to an entry near the key
  41308. ** specified by pIdxKey or intKey. Return a success code.
  41309. **
  41310. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  41311. ** must be NULL. For index tables, pIdxKey is used and intKey
  41312. ** is ignored.
  41313. **
  41314. ** If an exact match is not found, then the cursor is always
  41315. ** left pointing at a leaf page which would hold the entry if it
  41316. ** were present. The cursor might point to an entry that comes
  41317. ** before or after the key.
  41318. **
  41319. ** An integer is written into *pRes which is the result of
  41320. ** comparing the key with the entry to which the cursor is
  41321. ** pointing. The meaning of the integer written into
  41322. ** *pRes is as follows:
  41323. **
  41324. ** *pRes<0 The cursor is left pointing at an entry that
  41325. ** is smaller than intKey/pIdxKey or if the table is empty
  41326. ** and the cursor is therefore left point to nothing.
  41327. **
  41328. ** *pRes==0 The cursor is left pointing at an entry that
  41329. ** exactly matches intKey/pIdxKey.
  41330. **
  41331. ** *pRes>0 The cursor is left pointing at an entry that
  41332. ** is larger than intKey/pIdxKey.
  41333. **
  41334. */
  41335. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  41336. BtCursor *pCur, /* The cursor to be moved */
  41337. UnpackedRecord *pIdxKey, /* Unpacked index key */
  41338. i64 intKey, /* The table key */
  41339. int biasRight, /* If true, bias the search to the high end */
  41340. int *pRes /* Write search results here */
  41341. ){
  41342. int rc;
  41343. assert( cursorHoldsMutex(pCur) );
  41344. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41345. assert( pRes );
  41346. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  41347. /* If the cursor is already positioned at the point we are trying
  41348. ** to move to, then just return without doing any work */
  41349. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  41350. && pCur->apPage[0]->intKey
  41351. ){
  41352. if( pCur->info.nKey==intKey ){
  41353. *pRes = 0;
  41354. return SQLITE_OK;
  41355. }
  41356. if( pCur->atLast && pCur->info.nKey<intKey ){
  41357. *pRes = -1;
  41358. return SQLITE_OK;
  41359. }
  41360. }
  41361. rc = moveToRoot(pCur);
  41362. if( rc ){
  41363. return rc;
  41364. }
  41365. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  41366. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  41367. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  41368. if( pCur->eState==CURSOR_INVALID ){
  41369. *pRes = -1;
  41370. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41371. return SQLITE_OK;
  41372. }
  41373. assert( pCur->apPage[0]->intKey || pIdxKey );
  41374. for(;;){
  41375. int lwr, upr, idx;
  41376. Pgno chldPg;
  41377. MemPage *pPage = pCur->apPage[pCur->iPage];
  41378. int c;
  41379. /* pPage->nCell must be greater than zero. If this is the root-page
  41380. ** the cursor would have been INVALID above and this for(;;) loop
  41381. ** not run. If this is not the root-page, then the moveToChild() routine
  41382. ** would have already detected db corruption. Similarly, pPage must
  41383. ** be the right kind (index or table) of b-tree page. Otherwise
  41384. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  41385. assert( pPage->nCell>0 );
  41386. assert( pPage->intKey==(pIdxKey==0) );
  41387. lwr = 0;
  41388. upr = pPage->nCell-1;
  41389. if( biasRight ){
  41390. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  41391. }else{
  41392. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  41393. }
  41394. for(;;){
  41395. u8 *pCell; /* Pointer to current cell in pPage */
  41396. assert( idx==pCur->aiIdx[pCur->iPage] );
  41397. pCur->info.nSize = 0;
  41398. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  41399. if( pPage->intKey ){
  41400. i64 nCellKey;
  41401. if( pPage->hasData ){
  41402. u32 dummy;
  41403. pCell += getVarint32(pCell, dummy);
  41404. }
  41405. getVarint(pCell, (u64*)&nCellKey);
  41406. if( nCellKey==intKey ){
  41407. c = 0;
  41408. }else if( nCellKey<intKey ){
  41409. c = -1;
  41410. }else{
  41411. assert( nCellKey>intKey );
  41412. c = +1;
  41413. }
  41414. pCur->validNKey = 1;
  41415. pCur->info.nKey = nCellKey;
  41416. }else{
  41417. /* The maximum supported page-size is 65536 bytes. This means that
  41418. ** the maximum number of record bytes stored on an index B-Tree
  41419. ** page is less than 16384 bytes and may be stored as a 2-byte
  41420. ** varint. This information is used to attempt to avoid parsing
  41421. ** the entire cell by checking for the cases where the record is
  41422. ** stored entirely within the b-tree page by inspecting the first
  41423. ** 2 bytes of the cell.
  41424. */
  41425. int nCell = pCell[0];
  41426. if( nCell<=pPage->max1bytePayload
  41427. /* && (pCell+nCell)<pPage->aDataEnd */
  41428. ){
  41429. /* This branch runs if the record-size field of the cell is a
  41430. ** single byte varint and the record fits entirely on the main
  41431. ** b-tree page. */
  41432. testcase( pCell+nCell+1==pPage->aDataEnd );
  41433. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  41434. }else if( !(pCell[1] & 0x80)
  41435. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  41436. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  41437. ){
  41438. /* The record-size field is a 2 byte varint and the record
  41439. ** fits entirely on the main b-tree page. */
  41440. testcase( pCell+nCell+2==pPage->aDataEnd );
  41441. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  41442. }else{
  41443. /* The record flows over onto one or more overflow pages. In
  41444. ** this case the whole cell needs to be parsed, a buffer allocated
  41445. ** and accessPayload() used to retrieve the record into the
  41446. ** buffer before VdbeRecordCompare() can be called. */
  41447. void *pCellKey;
  41448. u8 * const pCellBody = pCell - pPage->childPtrSize;
  41449. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  41450. nCell = (int)pCur->info.nKey;
  41451. pCellKey = sqlite3Malloc( nCell );
  41452. if( pCellKey==0 ){
  41453. rc = SQLITE_NOMEM;
  41454. goto moveto_finish;
  41455. }
  41456. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  41457. if( rc ){
  41458. sqlite3_free(pCellKey);
  41459. goto moveto_finish;
  41460. }
  41461. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  41462. sqlite3_free(pCellKey);
  41463. }
  41464. }
  41465. if( c==0 ){
  41466. if( pPage->intKey && !pPage->leaf ){
  41467. lwr = idx;
  41468. break;
  41469. }else{
  41470. *pRes = 0;
  41471. rc = SQLITE_OK;
  41472. goto moveto_finish;
  41473. }
  41474. }
  41475. if( c<0 ){
  41476. lwr = idx+1;
  41477. }else{
  41478. upr = idx-1;
  41479. }
  41480. if( lwr>upr ){
  41481. break;
  41482. }
  41483. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  41484. }
  41485. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  41486. assert( pPage->isInit );
  41487. if( pPage->leaf ){
  41488. chldPg = 0;
  41489. }else if( lwr>=pPage->nCell ){
  41490. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  41491. }else{
  41492. chldPg = get4byte(findCell(pPage, lwr));
  41493. }
  41494. if( chldPg==0 ){
  41495. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  41496. *pRes = c;
  41497. rc = SQLITE_OK;
  41498. goto moveto_finish;
  41499. }
  41500. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  41501. pCur->info.nSize = 0;
  41502. pCur->validNKey = 0;
  41503. rc = moveToChild(pCur, chldPg);
  41504. if( rc ) goto moveto_finish;
  41505. }
  41506. moveto_finish:
  41507. return rc;
  41508. }
  41509. /*
  41510. ** Return TRUE if the cursor is not pointing at an entry of the table.
  41511. **
  41512. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  41513. ** past the last entry in the table or sqlite3BtreePrev() moves past
  41514. ** the first entry. TRUE is also returned if the table is empty.
  41515. */
  41516. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  41517. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  41518. ** have been deleted? This API will need to change to return an error code
  41519. ** as well as the boolean result value.
  41520. */
  41521. return (CURSOR_VALID!=pCur->eState);
  41522. }
  41523. /*
  41524. ** Advance the cursor to the next entry in the database. If
  41525. ** successful then set *pRes=0. If the cursor
  41526. ** was already pointing to the last entry in the database before
  41527. ** this routine was called, then set *pRes=1.
  41528. */
  41529. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  41530. int rc;
  41531. int idx;
  41532. MemPage *pPage;
  41533. assert( cursorHoldsMutex(pCur) );
  41534. assert( pRes!=0 );
  41535. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  41536. if( pCur->eState!=CURSOR_VALID ){
  41537. rc = restoreCursorPosition(pCur);
  41538. if( rc!=SQLITE_OK ){
  41539. *pRes = 0;
  41540. return rc;
  41541. }
  41542. if( CURSOR_INVALID==pCur->eState ){
  41543. *pRes = 1;
  41544. return SQLITE_OK;
  41545. }
  41546. if( pCur->skipNext ){
  41547. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  41548. pCur->eState = CURSOR_VALID;
  41549. if( pCur->skipNext>0 ){
  41550. pCur->skipNext = 0;
  41551. *pRes = 0;
  41552. return SQLITE_OK;
  41553. }
  41554. pCur->skipNext = 0;
  41555. }
  41556. }
  41557. pPage = pCur->apPage[pCur->iPage];
  41558. idx = ++pCur->aiIdx[pCur->iPage];
  41559. assert( pPage->isInit );
  41560. /* If the database file is corrupt, it is possible for the value of idx
  41561. ** to be invalid here. This can only occur if a second cursor modifies
  41562. ** the page while cursor pCur is holding a reference to it. Which can
  41563. ** only happen if the database is corrupt in such a way as to link the
  41564. ** page into more than one b-tree structure. */
  41565. testcase( idx>pPage->nCell );
  41566. pCur->info.nSize = 0;
  41567. pCur->validNKey = 0;
  41568. if( idx>=pPage->nCell ){
  41569. if( !pPage->leaf ){
  41570. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  41571. if( rc ){
  41572. *pRes = 0;
  41573. return rc;
  41574. }
  41575. rc = moveToLeftmost(pCur);
  41576. *pRes = 0;
  41577. return rc;
  41578. }
  41579. do{
  41580. if( pCur->iPage==0 ){
  41581. *pRes = 1;
  41582. pCur->eState = CURSOR_INVALID;
  41583. return SQLITE_OK;
  41584. }
  41585. moveToParent(pCur);
  41586. pPage = pCur->apPage[pCur->iPage];
  41587. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  41588. *pRes = 0;
  41589. if( pPage->intKey ){
  41590. rc = sqlite3BtreeNext(pCur, pRes);
  41591. }else{
  41592. rc = SQLITE_OK;
  41593. }
  41594. return rc;
  41595. }
  41596. *pRes = 0;
  41597. if( pPage->leaf ){
  41598. return SQLITE_OK;
  41599. }
  41600. rc = moveToLeftmost(pCur);
  41601. return rc;
  41602. }
  41603. /*
  41604. ** Step the cursor to the back to the previous entry in the database. If
  41605. ** successful then set *pRes=0. If the cursor
  41606. ** was already pointing to the first entry in the database before
  41607. ** this routine was called, then set *pRes=1.
  41608. */
  41609. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  41610. int rc;
  41611. MemPage *pPage;
  41612. assert( cursorHoldsMutex(pCur) );
  41613. assert( pRes!=0 );
  41614. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  41615. pCur->atLast = 0;
  41616. if( pCur->eState!=CURSOR_VALID ){
  41617. if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
  41618. rc = btreeRestoreCursorPosition(pCur);
  41619. if( rc!=SQLITE_OK ){
  41620. *pRes = 0;
  41621. return rc;
  41622. }
  41623. }
  41624. if( CURSOR_INVALID==pCur->eState ){
  41625. *pRes = 1;
  41626. return SQLITE_OK;
  41627. }
  41628. if( pCur->skipNext ){
  41629. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  41630. pCur->eState = CURSOR_VALID;
  41631. if( pCur->skipNext<0 ){
  41632. pCur->skipNext = 0;
  41633. *pRes = 0;
  41634. return SQLITE_OK;
  41635. }
  41636. pCur->skipNext = 0;
  41637. }
  41638. }
  41639. pPage = pCur->apPage[pCur->iPage];
  41640. assert( pPage->isInit );
  41641. if( !pPage->leaf ){
  41642. int idx = pCur->aiIdx[pCur->iPage];
  41643. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  41644. if( rc ){
  41645. *pRes = 0;
  41646. return rc;
  41647. }
  41648. rc = moveToRightmost(pCur);
  41649. }else{
  41650. while( pCur->aiIdx[pCur->iPage]==0 ){
  41651. if( pCur->iPage==0 ){
  41652. pCur->eState = CURSOR_INVALID;
  41653. *pRes = 1;
  41654. return SQLITE_OK;
  41655. }
  41656. moveToParent(pCur);
  41657. }
  41658. pCur->info.nSize = 0;
  41659. pCur->validNKey = 0;
  41660. pCur->aiIdx[pCur->iPage]--;
  41661. pPage = pCur->apPage[pCur->iPage];
  41662. if( pPage->intKey && !pPage->leaf ){
  41663. rc = sqlite3BtreePrevious(pCur, pRes);
  41664. }else{
  41665. rc = SQLITE_OK;
  41666. }
  41667. }
  41668. *pRes = 0;
  41669. return rc;
  41670. }
  41671. /*
  41672. ** Allocate a new page from the database file.
  41673. **
  41674. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  41675. ** has already been called on the new page.) The new page has also
  41676. ** been referenced and the calling routine is responsible for calling
  41677. ** sqlite3PagerUnref() on the new page when it is done.
  41678. **
  41679. ** SQLITE_OK is returned on success. Any other return value indicates
  41680. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  41681. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  41682. **
  41683. ** If the "nearby" parameter is not 0, then an effort is made to
  41684. ** locate a page close to the page number "nearby". This can be used in an
  41685. ** attempt to keep related pages close to each other in the database file,
  41686. ** which in turn can make database access faster.
  41687. **
  41688. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  41689. ** anywhere on the free-list, then it is guaranteed to be returned. If
  41690. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  41691. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  41692. ** are no restrictions on which page is returned.
  41693. */
  41694. static int allocateBtreePage(
  41695. BtShared *pBt, /* The btree */
  41696. MemPage **ppPage, /* Store pointer to the allocated page here */
  41697. Pgno *pPgno, /* Store the page number here */
  41698. Pgno nearby, /* Search for a page near this one */
  41699. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  41700. ){
  41701. MemPage *pPage1;
  41702. int rc;
  41703. u32 n; /* Number of pages on the freelist */
  41704. u32 k; /* Number of leaves on the trunk of the freelist */
  41705. MemPage *pTrunk = 0;
  41706. MemPage *pPrevTrunk = 0;
  41707. Pgno mxPage; /* Total size of the database file */
  41708. assert( sqlite3_mutex_held(pBt->mutex) );
  41709. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  41710. pPage1 = pBt->pPage1;
  41711. mxPage = btreePagecount(pBt);
  41712. n = get4byte(&pPage1->aData[36]);
  41713. testcase( n==mxPage-1 );
  41714. if( n>=mxPage ){
  41715. return SQLITE_CORRUPT_BKPT;
  41716. }
  41717. if( n>0 ){
  41718. /* There are pages on the freelist. Reuse one of those pages. */
  41719. Pgno iTrunk;
  41720. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  41721. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  41722. ** shows that the page 'nearby' is somewhere on the free-list, then
  41723. ** the entire-list will be searched for that page.
  41724. */
  41725. #ifndef SQLITE_OMIT_AUTOVACUUM
  41726. if( eMode==BTALLOC_EXACT ){
  41727. if( nearby<=mxPage ){
  41728. u8 eType;
  41729. assert( nearby>0 );
  41730. assert( pBt->autoVacuum );
  41731. rc = ptrmapGet(pBt, nearby, &eType, 0);
  41732. if( rc ) return rc;
  41733. if( eType==PTRMAP_FREEPAGE ){
  41734. searchList = 1;
  41735. }
  41736. }
  41737. }else if( eMode==BTALLOC_LE ){
  41738. searchList = 1;
  41739. }
  41740. #endif
  41741. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  41742. ** first free-list trunk page. iPrevTrunk is initially 1.
  41743. */
  41744. rc = sqlite3PagerWrite(pPage1->pDbPage);
  41745. if( rc ) return rc;
  41746. put4byte(&pPage1->aData[36], n-1);
  41747. /* The code within this loop is run only once if the 'searchList' variable
  41748. ** is not true. Otherwise, it runs once for each trunk-page on the
  41749. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  41750. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  41751. */
  41752. do {
  41753. pPrevTrunk = pTrunk;
  41754. if( pPrevTrunk ){
  41755. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  41756. }else{
  41757. iTrunk = get4byte(&pPage1->aData[32]);
  41758. }
  41759. testcase( iTrunk==mxPage );
  41760. if( iTrunk>mxPage ){
  41761. rc = SQLITE_CORRUPT_BKPT;
  41762. }else{
  41763. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  41764. }
  41765. if( rc ){
  41766. pTrunk = 0;
  41767. goto end_allocate_page;
  41768. }
  41769. assert( pTrunk!=0 );
  41770. assert( pTrunk->aData!=0 );
  41771. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  41772. if( k==0 && !searchList ){
  41773. /* The trunk has no leaves and the list is not being searched.
  41774. ** So extract the trunk page itself and use it as the newly
  41775. ** allocated page */
  41776. assert( pPrevTrunk==0 );
  41777. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41778. if( rc ){
  41779. goto end_allocate_page;
  41780. }
  41781. *pPgno = iTrunk;
  41782. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  41783. *ppPage = pTrunk;
  41784. pTrunk = 0;
  41785. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  41786. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  41787. /* Value of k is out of range. Database corruption */
  41788. rc = SQLITE_CORRUPT_BKPT;
  41789. goto end_allocate_page;
  41790. #ifndef SQLITE_OMIT_AUTOVACUUM
  41791. }else if( searchList
  41792. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  41793. ){
  41794. /* The list is being searched and this trunk page is the page
  41795. ** to allocate, regardless of whether it has leaves.
  41796. */
  41797. *pPgno = iTrunk;
  41798. *ppPage = pTrunk;
  41799. searchList = 0;
  41800. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41801. if( rc ){
  41802. goto end_allocate_page;
  41803. }
  41804. if( k==0 ){
  41805. if( !pPrevTrunk ){
  41806. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  41807. }else{
  41808. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  41809. if( rc!=SQLITE_OK ){
  41810. goto end_allocate_page;
  41811. }
  41812. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  41813. }
  41814. }else{
  41815. /* The trunk page is required by the caller but it contains
  41816. ** pointers to free-list leaves. The first leaf becomes a trunk
  41817. ** page in this case.
  41818. */
  41819. MemPage *pNewTrunk;
  41820. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  41821. if( iNewTrunk>mxPage ){
  41822. rc = SQLITE_CORRUPT_BKPT;
  41823. goto end_allocate_page;
  41824. }
  41825. testcase( iNewTrunk==mxPage );
  41826. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  41827. if( rc!=SQLITE_OK ){
  41828. goto end_allocate_page;
  41829. }
  41830. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  41831. if( rc!=SQLITE_OK ){
  41832. releasePage(pNewTrunk);
  41833. goto end_allocate_page;
  41834. }
  41835. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  41836. put4byte(&pNewTrunk->aData[4], k-1);
  41837. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  41838. releasePage(pNewTrunk);
  41839. if( !pPrevTrunk ){
  41840. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  41841. put4byte(&pPage1->aData[32], iNewTrunk);
  41842. }else{
  41843. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  41844. if( rc ){
  41845. goto end_allocate_page;
  41846. }
  41847. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  41848. }
  41849. }
  41850. pTrunk = 0;
  41851. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  41852. #endif
  41853. }else if( k>0 ){
  41854. /* Extract a leaf from the trunk */
  41855. u32 closest;
  41856. Pgno iPage;
  41857. unsigned char *aData = pTrunk->aData;
  41858. if( nearby>0 ){
  41859. u32 i;
  41860. closest = 0;
  41861. if( eMode==BTALLOC_LE ){
  41862. for(i=0; i<k; i++){
  41863. iPage = get4byte(&aData[8+i*4]);
  41864. if( iPage<=nearby ){
  41865. closest = i;
  41866. break;
  41867. }
  41868. }
  41869. }else{
  41870. int dist;
  41871. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  41872. for(i=1; i<k; i++){
  41873. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  41874. if( d2<dist ){
  41875. closest = i;
  41876. dist = d2;
  41877. }
  41878. }
  41879. }
  41880. }else{
  41881. closest = 0;
  41882. }
  41883. iPage = get4byte(&aData[8+closest*4]);
  41884. testcase( iPage==mxPage );
  41885. if( iPage>mxPage ){
  41886. rc = SQLITE_CORRUPT_BKPT;
  41887. goto end_allocate_page;
  41888. }
  41889. testcase( iPage==mxPage );
  41890. if( !searchList
  41891. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  41892. ){
  41893. int noContent;
  41894. *pPgno = iPage;
  41895. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  41896. ": %d more free pages\n",
  41897. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  41898. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41899. if( rc ) goto end_allocate_page;
  41900. if( closest<k-1 ){
  41901. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  41902. }
  41903. put4byte(&aData[4], k-1);
  41904. noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
  41905. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  41906. if( rc==SQLITE_OK ){
  41907. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  41908. if( rc!=SQLITE_OK ){
  41909. releasePage(*ppPage);
  41910. }
  41911. }
  41912. searchList = 0;
  41913. }
  41914. }
  41915. releasePage(pPrevTrunk);
  41916. pPrevTrunk = 0;
  41917. }while( searchList );
  41918. }else{
  41919. /* There are no pages on the freelist, so append a new page to the
  41920. ** database image.
  41921. **
  41922. ** Normally, new pages allocated by this block can be requested from the
  41923. ** pager layer with the 'no-content' flag set. This prevents the pager
  41924. ** from trying to read the pages content from disk. However, if the
  41925. ** current transaction has already run one or more incremental-vacuum
  41926. ** steps, then the page we are about to allocate may contain content
  41927. ** that is required in the event of a rollback. In this case, do
  41928. ** not set the no-content flag. This causes the pager to load and journal
  41929. ** the current page content before overwriting it.
  41930. **
  41931. ** Note that the pager will not actually attempt to load or journal
  41932. ** content for any page that really does lie past the end of the database
  41933. ** file on disk. So the effects of disabling the no-content optimization
  41934. ** here are confined to those pages that lie between the end of the
  41935. ** database image and the end of the database file.
  41936. */
  41937. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
  41938. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  41939. if( rc ) return rc;
  41940. pBt->nPage++;
  41941. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  41942. #ifndef SQLITE_OMIT_AUTOVACUUM
  41943. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  41944. /* If *pPgno refers to a pointer-map page, allocate two new pages
  41945. ** at the end of the file instead of one. The first allocated page
  41946. ** becomes a new pointer-map page, the second is used by the caller.
  41947. */
  41948. MemPage *pPg = 0;
  41949. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  41950. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  41951. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  41952. if( rc==SQLITE_OK ){
  41953. rc = sqlite3PagerWrite(pPg->pDbPage);
  41954. releasePage(pPg);
  41955. }
  41956. if( rc ) return rc;
  41957. pBt->nPage++;
  41958. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  41959. }
  41960. #endif
  41961. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  41962. *pPgno = pBt->nPage;
  41963. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  41964. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  41965. if( rc ) return rc;
  41966. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  41967. if( rc!=SQLITE_OK ){
  41968. releasePage(*ppPage);
  41969. }
  41970. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  41971. }
  41972. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  41973. end_allocate_page:
  41974. releasePage(pTrunk);
  41975. releasePage(pPrevTrunk);
  41976. if( rc==SQLITE_OK ){
  41977. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  41978. releasePage(*ppPage);
  41979. return SQLITE_CORRUPT_BKPT;
  41980. }
  41981. (*ppPage)->isInit = 0;
  41982. }else{
  41983. *ppPage = 0;
  41984. }
  41985. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  41986. return rc;
  41987. }
  41988. /*
  41989. ** This function is used to add page iPage to the database file free-list.
  41990. ** It is assumed that the page is not already a part of the free-list.
  41991. **
  41992. ** The value passed as the second argument to this function is optional.
  41993. ** If the caller happens to have a pointer to the MemPage object
  41994. ** corresponding to page iPage handy, it may pass it as the second value.
  41995. ** Otherwise, it may pass NULL.
  41996. **
  41997. ** If a pointer to a MemPage object is passed as the second argument,
  41998. ** its reference count is not altered by this function.
  41999. */
  42000. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  42001. MemPage *pTrunk = 0; /* Free-list trunk page */
  42002. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  42003. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  42004. MemPage *pPage; /* Page being freed. May be NULL. */
  42005. int rc; /* Return Code */
  42006. int nFree; /* Initial number of pages on free-list */
  42007. assert( sqlite3_mutex_held(pBt->mutex) );
  42008. assert( iPage>1 );
  42009. assert( !pMemPage || pMemPage->pgno==iPage );
  42010. if( pMemPage ){
  42011. pPage = pMemPage;
  42012. sqlite3PagerRef(pPage->pDbPage);
  42013. }else{
  42014. pPage = btreePageLookup(pBt, iPage);
  42015. }
  42016. /* Increment the free page count on pPage1 */
  42017. rc = sqlite3PagerWrite(pPage1->pDbPage);
  42018. if( rc ) goto freepage_out;
  42019. nFree = get4byte(&pPage1->aData[36]);
  42020. put4byte(&pPage1->aData[36], nFree+1);
  42021. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  42022. /* If the secure_delete option is enabled, then
  42023. ** always fully overwrite deleted information with zeros.
  42024. */
  42025. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  42026. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  42027. ){
  42028. goto freepage_out;
  42029. }
  42030. memset(pPage->aData, 0, pPage->pBt->pageSize);
  42031. }
  42032. /* If the database supports auto-vacuum, write an entry in the pointer-map
  42033. ** to indicate that the page is free.
  42034. */
  42035. if( ISAUTOVACUUM ){
  42036. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  42037. if( rc ) goto freepage_out;
  42038. }
  42039. /* Now manipulate the actual database free-list structure. There are two
  42040. ** possibilities. If the free-list is currently empty, or if the first
  42041. ** trunk page in the free-list is full, then this page will become a
  42042. ** new free-list trunk page. Otherwise, it will become a leaf of the
  42043. ** first trunk page in the current free-list. This block tests if it
  42044. ** is possible to add the page as a new free-list leaf.
  42045. */
  42046. if( nFree!=0 ){
  42047. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  42048. iTrunk = get4byte(&pPage1->aData[32]);
  42049. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  42050. if( rc!=SQLITE_OK ){
  42051. goto freepage_out;
  42052. }
  42053. nLeaf = get4byte(&pTrunk->aData[4]);
  42054. assert( pBt->usableSize>32 );
  42055. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  42056. rc = SQLITE_CORRUPT_BKPT;
  42057. goto freepage_out;
  42058. }
  42059. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  42060. /* In this case there is room on the trunk page to insert the page
  42061. ** being freed as a new leaf.
  42062. **
  42063. ** Note that the trunk page is not really full until it contains
  42064. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  42065. ** coded. But due to a coding error in versions of SQLite prior to
  42066. ** 3.6.0, databases with freelist trunk pages holding more than
  42067. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  42068. ** to maintain backwards compatibility with older versions of SQLite,
  42069. ** we will continue to restrict the number of entries to usableSize/4 - 8
  42070. ** for now. At some point in the future (once everyone has upgraded
  42071. ** to 3.6.0 or later) we should consider fixing the conditional above
  42072. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  42073. */
  42074. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  42075. if( rc==SQLITE_OK ){
  42076. put4byte(&pTrunk->aData[4], nLeaf+1);
  42077. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  42078. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  42079. sqlite3PagerDontWrite(pPage->pDbPage);
  42080. }
  42081. rc = btreeSetHasContent(pBt, iPage);
  42082. }
  42083. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  42084. goto freepage_out;
  42085. }
  42086. }
  42087. /* If control flows to this point, then it was not possible to add the
  42088. ** the page being freed as a leaf page of the first trunk in the free-list.
  42089. ** Possibly because the free-list is empty, or possibly because the
  42090. ** first trunk in the free-list is full. Either way, the page being freed
  42091. ** will become the new first trunk page in the free-list.
  42092. */
  42093. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  42094. goto freepage_out;
  42095. }
  42096. rc = sqlite3PagerWrite(pPage->pDbPage);
  42097. if( rc!=SQLITE_OK ){
  42098. goto freepage_out;
  42099. }
  42100. put4byte(pPage->aData, iTrunk);
  42101. put4byte(&pPage->aData[4], 0);
  42102. put4byte(&pPage1->aData[32], iPage);
  42103. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  42104. freepage_out:
  42105. if( pPage ){
  42106. pPage->isInit = 0;
  42107. }
  42108. releasePage(pPage);
  42109. releasePage(pTrunk);
  42110. return rc;
  42111. }
  42112. static void freePage(MemPage *pPage, int *pRC){
  42113. if( (*pRC)==SQLITE_OK ){
  42114. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  42115. }
  42116. }
  42117. /*
  42118. ** Free any overflow pages associated with the given Cell.
  42119. */
  42120. static int clearCell(MemPage *pPage, unsigned char *pCell){
  42121. BtShared *pBt = pPage->pBt;
  42122. CellInfo info;
  42123. Pgno ovflPgno;
  42124. int rc;
  42125. int nOvfl;
  42126. u32 ovflPageSize;
  42127. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42128. btreeParseCellPtr(pPage, pCell, &info);
  42129. if( info.iOverflow==0 ){
  42130. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  42131. }
  42132. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  42133. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  42134. }
  42135. ovflPgno = get4byte(&pCell[info.iOverflow]);
  42136. assert( pBt->usableSize > 4 );
  42137. ovflPageSize = pBt->usableSize - 4;
  42138. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  42139. assert( ovflPgno==0 || nOvfl>0 );
  42140. while( nOvfl-- ){
  42141. Pgno iNext = 0;
  42142. MemPage *pOvfl = 0;
  42143. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  42144. /* 0 is not a legal page number and page 1 cannot be an
  42145. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  42146. ** file the database must be corrupt. */
  42147. return SQLITE_CORRUPT_BKPT;
  42148. }
  42149. if( nOvfl ){
  42150. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  42151. if( rc ) return rc;
  42152. }
  42153. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  42154. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  42155. ){
  42156. /* There is no reason any cursor should have an outstanding reference
  42157. ** to an overflow page belonging to a cell that is being deleted/updated.
  42158. ** So if there exists more than one reference to this page, then it
  42159. ** must not really be an overflow page and the database must be corrupt.
  42160. ** It is helpful to detect this before calling freePage2(), as
  42161. ** freePage2() may zero the page contents if secure-delete mode is
  42162. ** enabled. If this 'overflow' page happens to be a page that the
  42163. ** caller is iterating through or using in some other way, this
  42164. ** can be problematic.
  42165. */
  42166. rc = SQLITE_CORRUPT_BKPT;
  42167. }else{
  42168. rc = freePage2(pBt, pOvfl, ovflPgno);
  42169. }
  42170. if( pOvfl ){
  42171. sqlite3PagerUnref(pOvfl->pDbPage);
  42172. }
  42173. if( rc ) return rc;
  42174. ovflPgno = iNext;
  42175. }
  42176. return SQLITE_OK;
  42177. }
  42178. /*
  42179. ** Create the byte sequence used to represent a cell on page pPage
  42180. ** and write that byte sequence into pCell[]. Overflow pages are
  42181. ** allocated and filled in as necessary. The calling procedure
  42182. ** is responsible for making sure sufficient space has been allocated
  42183. ** for pCell[].
  42184. **
  42185. ** Note that pCell does not necessary need to point to the pPage->aData
  42186. ** area. pCell might point to some temporary storage. The cell will
  42187. ** be constructed in this temporary area then copied into pPage->aData
  42188. ** later.
  42189. */
  42190. static int fillInCell(
  42191. MemPage *pPage, /* The page that contains the cell */
  42192. unsigned char *pCell, /* Complete text of the cell */
  42193. const void *pKey, i64 nKey, /* The key */
  42194. const void *pData,int nData, /* The data */
  42195. int nZero, /* Extra zero bytes to append to pData */
  42196. int *pnSize /* Write cell size here */
  42197. ){
  42198. int nPayload;
  42199. const u8 *pSrc;
  42200. int nSrc, n, rc;
  42201. int spaceLeft;
  42202. MemPage *pOvfl = 0;
  42203. MemPage *pToRelease = 0;
  42204. unsigned char *pPrior;
  42205. unsigned char *pPayload;
  42206. BtShared *pBt = pPage->pBt;
  42207. Pgno pgnoOvfl = 0;
  42208. int nHeader;
  42209. CellInfo info;
  42210. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42211. /* pPage is not necessarily writeable since pCell might be auxiliary
  42212. ** buffer space that is separate from the pPage buffer area */
  42213. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  42214. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42215. /* Fill in the header. */
  42216. nHeader = 0;
  42217. if( !pPage->leaf ){
  42218. nHeader += 4;
  42219. }
  42220. if( pPage->hasData ){
  42221. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  42222. }else{
  42223. nData = nZero = 0;
  42224. }
  42225. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  42226. btreeParseCellPtr(pPage, pCell, &info);
  42227. assert( info.nHeader==nHeader );
  42228. assert( info.nKey==nKey );
  42229. assert( info.nData==(u32)(nData+nZero) );
  42230. /* Fill in the payload */
  42231. nPayload = nData + nZero;
  42232. if( pPage->intKey ){
  42233. pSrc = pData;
  42234. nSrc = nData;
  42235. nData = 0;
  42236. }else{
  42237. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  42238. return SQLITE_CORRUPT_BKPT;
  42239. }
  42240. nPayload += (int)nKey;
  42241. pSrc = pKey;
  42242. nSrc = (int)nKey;
  42243. }
  42244. *pnSize = info.nSize;
  42245. spaceLeft = info.nLocal;
  42246. pPayload = &pCell[nHeader];
  42247. pPrior = &pCell[info.iOverflow];
  42248. while( nPayload>0 ){
  42249. if( spaceLeft==0 ){
  42250. #ifndef SQLITE_OMIT_AUTOVACUUM
  42251. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  42252. if( pBt->autoVacuum ){
  42253. do{
  42254. pgnoOvfl++;
  42255. } while(
  42256. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  42257. );
  42258. }
  42259. #endif
  42260. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  42261. #ifndef SQLITE_OMIT_AUTOVACUUM
  42262. /* If the database supports auto-vacuum, and the second or subsequent
  42263. ** overflow page is being allocated, add an entry to the pointer-map
  42264. ** for that page now.
  42265. **
  42266. ** If this is the first overflow page, then write a partial entry
  42267. ** to the pointer-map. If we write nothing to this pointer-map slot,
  42268. ** then the optimistic overflow chain processing in clearCell()
  42269. ** may misinterpret the uninitialized values and delete the
  42270. ** wrong pages from the database.
  42271. */
  42272. if( pBt->autoVacuum && rc==SQLITE_OK ){
  42273. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  42274. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  42275. if( rc ){
  42276. releasePage(pOvfl);
  42277. }
  42278. }
  42279. #endif
  42280. if( rc ){
  42281. releasePage(pToRelease);
  42282. return rc;
  42283. }
  42284. /* If pToRelease is not zero than pPrior points into the data area
  42285. ** of pToRelease. Make sure pToRelease is still writeable. */
  42286. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  42287. /* If pPrior is part of the data area of pPage, then make sure pPage
  42288. ** is still writeable */
  42289. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  42290. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42291. put4byte(pPrior, pgnoOvfl);
  42292. releasePage(pToRelease);
  42293. pToRelease = pOvfl;
  42294. pPrior = pOvfl->aData;
  42295. put4byte(pPrior, 0);
  42296. pPayload = &pOvfl->aData[4];
  42297. spaceLeft = pBt->usableSize - 4;
  42298. }
  42299. n = nPayload;
  42300. if( n>spaceLeft ) n = spaceLeft;
  42301. /* If pToRelease is not zero than pPayload points into the data area
  42302. ** of pToRelease. Make sure pToRelease is still writeable. */
  42303. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  42304. /* If pPayload is part of the data area of pPage, then make sure pPage
  42305. ** is still writeable */
  42306. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  42307. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42308. if( nSrc>0 ){
  42309. if( n>nSrc ) n = nSrc;
  42310. assert( pSrc );
  42311. memcpy(pPayload, pSrc, n);
  42312. }else{
  42313. memset(pPayload, 0, n);
  42314. }
  42315. nPayload -= n;
  42316. pPayload += n;
  42317. pSrc += n;
  42318. nSrc -= n;
  42319. spaceLeft -= n;
  42320. if( nSrc==0 ){
  42321. nSrc = nData;
  42322. pSrc = pData;
  42323. }
  42324. }
  42325. releasePage(pToRelease);
  42326. return SQLITE_OK;
  42327. }
  42328. /*
  42329. ** Remove the i-th cell from pPage. This routine effects pPage only.
  42330. ** The cell content is not freed or deallocated. It is assumed that
  42331. ** the cell content has been copied someplace else. This routine just
  42332. ** removes the reference to the cell from pPage.
  42333. **
  42334. ** "sz" must be the number of bytes in the cell.
  42335. */
  42336. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  42337. u32 pc; /* Offset to cell content of cell being deleted */
  42338. u8 *data; /* pPage->aData */
  42339. u8 *ptr; /* Used to move bytes around within data[] */
  42340. u8 *endPtr; /* End of loop */
  42341. int rc; /* The return code */
  42342. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  42343. if( *pRC ) return;
  42344. assert( idx>=0 && idx<pPage->nCell );
  42345. assert( sz==cellSize(pPage, idx) );
  42346. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42347. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42348. data = pPage->aData;
  42349. ptr = &pPage->aCellIdx[2*idx];
  42350. pc = get2byte(ptr);
  42351. hdr = pPage->hdrOffset;
  42352. testcase( pc==get2byte(&data[hdr+5]) );
  42353. testcase( pc+sz==pPage->pBt->usableSize );
  42354. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  42355. *pRC = SQLITE_CORRUPT_BKPT;
  42356. return;
  42357. }
  42358. rc = freeSpace(pPage, pc, sz);
  42359. if( rc ){
  42360. *pRC = rc;
  42361. return;
  42362. }
  42363. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  42364. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  42365. while( ptr<endPtr ){
  42366. *(u16*)ptr = *(u16*)&ptr[2];
  42367. ptr += 2;
  42368. }
  42369. pPage->nCell--;
  42370. put2byte(&data[hdr+3], pPage->nCell);
  42371. pPage->nFree += 2;
  42372. }
  42373. /*
  42374. ** Insert a new cell on pPage at cell index "i". pCell points to the
  42375. ** content of the cell.
  42376. **
  42377. ** If the cell content will fit on the page, then put it there. If it
  42378. ** will not fit, then make a copy of the cell content into pTemp if
  42379. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  42380. ** in pPage->apOvfl[] and make it point to the cell content (either
  42381. ** in pTemp or the original pCell) and also record its index.
  42382. ** Allocating a new entry in pPage->aCell[] implies that
  42383. ** pPage->nOverflow is incremented.
  42384. **
  42385. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  42386. ** cell. The caller will overwrite them after this function returns. If
  42387. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  42388. ** (but pCell+nSkip is always valid).
  42389. */
  42390. static void insertCell(
  42391. MemPage *pPage, /* Page into which we are copying */
  42392. int i, /* New cell becomes the i-th cell of the page */
  42393. u8 *pCell, /* Content of the new cell */
  42394. int sz, /* Bytes of content in pCell */
  42395. u8 *pTemp, /* Temp storage space for pCell, if needed */
  42396. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  42397. int *pRC /* Read and write return code from here */
  42398. ){
  42399. int idx = 0; /* Where to write new cell content in data[] */
  42400. int j; /* Loop counter */
  42401. int end; /* First byte past the last cell pointer in data[] */
  42402. int ins; /* Index in data[] where new cell pointer is inserted */
  42403. int cellOffset; /* Address of first cell pointer in data[] */
  42404. u8 *data; /* The content of the whole page */
  42405. u8 *ptr; /* Used for moving information around in data[] */
  42406. u8 *endPtr; /* End of the loop */
  42407. int nSkip = (iChild ? 4 : 0);
  42408. if( *pRC ) return;
  42409. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  42410. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  42411. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  42412. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  42413. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42414. /* The cell should normally be sized correctly. However, when moving a
  42415. ** malformed cell from a leaf page to an interior page, if the cell size
  42416. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  42417. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  42418. ** the term after the || in the following assert(). */
  42419. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  42420. if( pPage->nOverflow || sz+2>pPage->nFree ){
  42421. if( pTemp ){
  42422. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  42423. pCell = pTemp;
  42424. }
  42425. if( iChild ){
  42426. put4byte(pCell, iChild);
  42427. }
  42428. j = pPage->nOverflow++;
  42429. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  42430. pPage->apOvfl[j] = pCell;
  42431. pPage->aiOvfl[j] = (u16)i;
  42432. }else{
  42433. int rc = sqlite3PagerWrite(pPage->pDbPage);
  42434. if( rc!=SQLITE_OK ){
  42435. *pRC = rc;
  42436. return;
  42437. }
  42438. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42439. data = pPage->aData;
  42440. cellOffset = pPage->cellOffset;
  42441. end = cellOffset + 2*pPage->nCell;
  42442. ins = cellOffset + 2*i;
  42443. rc = allocateSpace(pPage, sz, &idx);
  42444. if( rc ){ *pRC = rc; return; }
  42445. /* The allocateSpace() routine guarantees the following two properties
  42446. ** if it returns success */
  42447. assert( idx >= end+2 );
  42448. assert( idx+sz <= (int)pPage->pBt->usableSize );
  42449. pPage->nCell++;
  42450. pPage->nFree -= (u16)(2 + sz);
  42451. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  42452. if( iChild ){
  42453. put4byte(&data[idx], iChild);
  42454. }
  42455. ptr = &data[end];
  42456. endPtr = &data[ins];
  42457. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  42458. while( ptr>endPtr ){
  42459. *(u16*)ptr = *(u16*)&ptr[-2];
  42460. ptr -= 2;
  42461. }
  42462. put2byte(&data[ins], idx);
  42463. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  42464. #ifndef SQLITE_OMIT_AUTOVACUUM
  42465. if( pPage->pBt->autoVacuum ){
  42466. /* The cell may contain a pointer to an overflow page. If so, write
  42467. ** the entry for the overflow page into the pointer map.
  42468. */
  42469. ptrmapPutOvflPtr(pPage, pCell, pRC);
  42470. }
  42471. #endif
  42472. }
  42473. }
  42474. /*
  42475. ** Add a list of cells to a page. The page should be initially empty.
  42476. ** The cells are guaranteed to fit on the page.
  42477. */
  42478. static void assemblePage(
  42479. MemPage *pPage, /* The page to be assemblied */
  42480. int nCell, /* The number of cells to add to this page */
  42481. u8 **apCell, /* Pointers to cell bodies */
  42482. u16 *aSize /* Sizes of the cells */
  42483. ){
  42484. int i; /* Loop counter */
  42485. u8 *pCellptr; /* Address of next cell pointer */
  42486. int cellbody; /* Address of next cell body */
  42487. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  42488. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  42489. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  42490. assert( pPage->nOverflow==0 );
  42491. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42492. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  42493. && (int)MX_CELL(pPage->pBt)<=10921);
  42494. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42495. /* Check that the page has just been zeroed by zeroPage() */
  42496. assert( pPage->nCell==0 );
  42497. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  42498. pCellptr = &pPage->aCellIdx[nCell*2];
  42499. cellbody = nUsable;
  42500. for(i=nCell-1; i>=0; i--){
  42501. u16 sz = aSize[i];
  42502. pCellptr -= 2;
  42503. cellbody -= sz;
  42504. put2byte(pCellptr, cellbody);
  42505. memcpy(&data[cellbody], apCell[i], sz);
  42506. }
  42507. put2byte(&data[hdr+3], nCell);
  42508. put2byte(&data[hdr+5], cellbody);
  42509. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  42510. pPage->nCell = (u16)nCell;
  42511. }
  42512. /*
  42513. ** The following parameters determine how many adjacent pages get involved
  42514. ** in a balancing operation. NN is the number of neighbors on either side
  42515. ** of the page that participate in the balancing operation. NB is the
  42516. ** total number of pages that participate, including the target page and
  42517. ** NN neighbors on either side.
  42518. **
  42519. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  42520. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  42521. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  42522. ** The value of NN appears to give the best results overall.
  42523. */
  42524. #define NN 1 /* Number of neighbors on either side of pPage */
  42525. #define NB (NN*2+1) /* Total pages involved in the balance */
  42526. #ifndef SQLITE_OMIT_QUICKBALANCE
  42527. /*
  42528. ** This version of balance() handles the common special case where
  42529. ** a new entry is being inserted on the extreme right-end of the
  42530. ** tree, in other words, when the new entry will become the largest
  42531. ** entry in the tree.
  42532. **
  42533. ** Instead of trying to balance the 3 right-most leaf pages, just add
  42534. ** a new page to the right-hand side and put the one new entry in
  42535. ** that page. This leaves the right side of the tree somewhat
  42536. ** unbalanced. But odds are that we will be inserting new entries
  42537. ** at the end soon afterwards so the nearly empty page will quickly
  42538. ** fill up. On average.
  42539. **
  42540. ** pPage is the leaf page which is the right-most page in the tree.
  42541. ** pParent is its parent. pPage must have a single overflow entry
  42542. ** which is also the right-most entry on the page.
  42543. **
  42544. ** The pSpace buffer is used to store a temporary copy of the divider
  42545. ** cell that will be inserted into pParent. Such a cell consists of a 4
  42546. ** byte page number followed by a variable length integer. In other
  42547. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  42548. ** least 13 bytes in size.
  42549. */
  42550. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  42551. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  42552. MemPage *pNew; /* Newly allocated page */
  42553. int rc; /* Return Code */
  42554. Pgno pgnoNew; /* Page number of pNew */
  42555. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42556. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  42557. assert( pPage->nOverflow==1 );
  42558. /* This error condition is now caught prior to reaching this function */
  42559. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  42560. /* Allocate a new page. This page will become the right-sibling of
  42561. ** pPage. Make the parent page writable, so that the new divider cell
  42562. ** may be inserted. If both these operations are successful, proceed.
  42563. */
  42564. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  42565. if( rc==SQLITE_OK ){
  42566. u8 *pOut = &pSpace[4];
  42567. u8 *pCell = pPage->apOvfl[0];
  42568. u16 szCell = cellSizePtr(pPage, pCell);
  42569. u8 *pStop;
  42570. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  42571. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  42572. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  42573. assemblePage(pNew, 1, &pCell, &szCell);
  42574. /* If this is an auto-vacuum database, update the pointer map
  42575. ** with entries for the new page, and any pointer from the
  42576. ** cell on the page to an overflow page. If either of these
  42577. ** operations fails, the return code is set, but the contents
  42578. ** of the parent page are still manipulated by thh code below.
  42579. ** That is Ok, at this point the parent page is guaranteed to
  42580. ** be marked as dirty. Returning an error code will cause a
  42581. ** rollback, undoing any changes made to the parent page.
  42582. */
  42583. if( ISAUTOVACUUM ){
  42584. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  42585. if( szCell>pNew->minLocal ){
  42586. ptrmapPutOvflPtr(pNew, pCell, &rc);
  42587. }
  42588. }
  42589. /* Create a divider cell to insert into pParent. The divider cell
  42590. ** consists of a 4-byte page number (the page number of pPage) and
  42591. ** a variable length key value (which must be the same value as the
  42592. ** largest key on pPage).
  42593. **
  42594. ** To find the largest key value on pPage, first find the right-most
  42595. ** cell on pPage. The first two fields of this cell are the
  42596. ** record-length (a variable length integer at most 32-bits in size)
  42597. ** and the key value (a variable length integer, may have any value).
  42598. ** The first of the while(...) loops below skips over the record-length
  42599. ** field. The second while(...) loop copies the key value from the
  42600. ** cell on pPage into the pSpace buffer.
  42601. */
  42602. pCell = findCell(pPage, pPage->nCell-1);
  42603. pStop = &pCell[9];
  42604. while( (*(pCell++)&0x80) && pCell<pStop );
  42605. pStop = &pCell[9];
  42606. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  42607. /* Insert the new divider cell into pParent. */
  42608. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  42609. 0, pPage->pgno, &rc);
  42610. /* Set the right-child pointer of pParent to point to the new page. */
  42611. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  42612. /* Release the reference to the new page. */
  42613. releasePage(pNew);
  42614. }
  42615. return rc;
  42616. }
  42617. #endif /* SQLITE_OMIT_QUICKBALANCE */
  42618. #if 0
  42619. /*
  42620. ** This function does not contribute anything to the operation of SQLite.
  42621. ** it is sometimes activated temporarily while debugging code responsible
  42622. ** for setting pointer-map entries.
  42623. */
  42624. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  42625. int i, j;
  42626. for(i=0; i<nPage; i++){
  42627. Pgno n;
  42628. u8 e;
  42629. MemPage *pPage = apPage[i];
  42630. BtShared *pBt = pPage->pBt;
  42631. assert( pPage->isInit );
  42632. for(j=0; j<pPage->nCell; j++){
  42633. CellInfo info;
  42634. u8 *z;
  42635. z = findCell(pPage, j);
  42636. btreeParseCellPtr(pPage, z, &info);
  42637. if( info.iOverflow ){
  42638. Pgno ovfl = get4byte(&z[info.iOverflow]);
  42639. ptrmapGet(pBt, ovfl, &e, &n);
  42640. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  42641. }
  42642. if( !pPage->leaf ){
  42643. Pgno child = get4byte(z);
  42644. ptrmapGet(pBt, child, &e, &n);
  42645. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  42646. }
  42647. }
  42648. if( !pPage->leaf ){
  42649. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  42650. ptrmapGet(pBt, child, &e, &n);
  42651. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  42652. }
  42653. }
  42654. return 1;
  42655. }
  42656. #endif
  42657. /*
  42658. ** This function is used to copy the contents of the b-tree node stored
  42659. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  42660. ** the pointer-map entries for each child page are updated so that the
  42661. ** parent page stored in the pointer map is page pTo. If pFrom contained
  42662. ** any cells with overflow page pointers, then the corresponding pointer
  42663. ** map entries are also updated so that the parent page is page pTo.
  42664. **
  42665. ** If pFrom is currently carrying any overflow cells (entries in the
  42666. ** MemPage.apOvfl[] array), they are not copied to pTo.
  42667. **
  42668. ** Before returning, page pTo is reinitialized using btreeInitPage().
  42669. **
  42670. ** The performance of this function is not critical. It is only used by
  42671. ** the balance_shallower() and balance_deeper() procedures, neither of
  42672. ** which are called often under normal circumstances.
  42673. */
  42674. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  42675. if( (*pRC)==SQLITE_OK ){
  42676. BtShared * const pBt = pFrom->pBt;
  42677. u8 * const aFrom = pFrom->aData;
  42678. u8 * const aTo = pTo->aData;
  42679. int const iFromHdr = pFrom->hdrOffset;
  42680. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  42681. int rc;
  42682. int iData;
  42683. assert( pFrom->isInit );
  42684. assert( pFrom->nFree>=iToHdr );
  42685. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  42686. /* Copy the b-tree node content from page pFrom to page pTo. */
  42687. iData = get2byte(&aFrom[iFromHdr+5]);
  42688. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  42689. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  42690. /* Reinitialize page pTo so that the contents of the MemPage structure
  42691. ** match the new data. The initialization of pTo can actually fail under
  42692. ** fairly obscure circumstances, even though it is a copy of initialized
  42693. ** page pFrom.
  42694. */
  42695. pTo->isInit = 0;
  42696. rc = btreeInitPage(pTo);
  42697. if( rc!=SQLITE_OK ){
  42698. *pRC = rc;
  42699. return;
  42700. }
  42701. /* If this is an auto-vacuum database, update the pointer-map entries
  42702. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  42703. */
  42704. if( ISAUTOVACUUM ){
  42705. *pRC = setChildPtrmaps(pTo);
  42706. }
  42707. }
  42708. }
  42709. /*
  42710. ** This routine redistributes cells on the iParentIdx'th child of pParent
  42711. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  42712. ** same amount of free space. Usually a single sibling on either side of the
  42713. ** page are used in the balancing, though both siblings might come from one
  42714. ** side if the page is the first or last child of its parent. If the page
  42715. ** has fewer than 2 siblings (something which can only happen if the page
  42716. ** is a root page or a child of a root page) then all available siblings
  42717. ** participate in the balancing.
  42718. **
  42719. ** The number of siblings of the page might be increased or decreased by
  42720. ** one or two in an effort to keep pages nearly full but not over full.
  42721. **
  42722. ** Note that when this routine is called, some of the cells on the page
  42723. ** might not actually be stored in MemPage.aData[]. This can happen
  42724. ** if the page is overfull. This routine ensures that all cells allocated
  42725. ** to the page and its siblings fit into MemPage.aData[] before returning.
  42726. **
  42727. ** In the course of balancing the page and its siblings, cells may be
  42728. ** inserted into or removed from the parent page (pParent). Doing so
  42729. ** may cause the parent page to become overfull or underfull. If this
  42730. ** happens, it is the responsibility of the caller to invoke the correct
  42731. ** balancing routine to fix this problem (see the balance() routine).
  42732. **
  42733. ** If this routine fails for any reason, it might leave the database
  42734. ** in a corrupted state. So if this routine fails, the database should
  42735. ** be rolled back.
  42736. **
  42737. ** The third argument to this function, aOvflSpace, is a pointer to a
  42738. ** buffer big enough to hold one page. If while inserting cells into the parent
  42739. ** page (pParent) the parent page becomes overfull, this buffer is
  42740. ** used to store the parent's overflow cells. Because this function inserts
  42741. ** a maximum of four divider cells into the parent page, and the maximum
  42742. ** size of a cell stored within an internal node is always less than 1/4
  42743. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  42744. ** enough for all overflow cells.
  42745. **
  42746. ** If aOvflSpace is set to a null pointer, this function returns
  42747. ** SQLITE_NOMEM.
  42748. */
  42749. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  42750. #pragma optimize("", off)
  42751. #endif
  42752. static int balance_nonroot(
  42753. MemPage *pParent, /* Parent page of siblings being balanced */
  42754. int iParentIdx, /* Index of "the page" in pParent */
  42755. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  42756. int isRoot, /* True if pParent is a root-page */
  42757. int bBulk /* True if this call is part of a bulk load */
  42758. ){
  42759. BtShared *pBt; /* The whole database */
  42760. int nCell = 0; /* Number of cells in apCell[] */
  42761. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  42762. int nNew = 0; /* Number of pages in apNew[] */
  42763. int nOld; /* Number of pages in apOld[] */
  42764. int i, j, k; /* Loop counters */
  42765. int nxDiv; /* Next divider slot in pParent->aCell[] */
  42766. int rc = SQLITE_OK; /* The return code */
  42767. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  42768. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  42769. int usableSpace; /* Bytes in pPage beyond the header */
  42770. int pageFlags; /* Value of pPage->aData[0] */
  42771. int subtotal; /* Subtotal of bytes in cells on one page */
  42772. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  42773. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  42774. int szScratch; /* Size of scratch memory requested */
  42775. MemPage *apOld[NB]; /* pPage and up to two siblings */
  42776. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  42777. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  42778. u8 *pRight; /* Location in parent of right-sibling pointer */
  42779. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  42780. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  42781. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  42782. u8 **apCell = 0; /* All cells begin balanced */
  42783. u16 *szCell; /* Local size of all cells in apCell[] */
  42784. u8 *aSpace1; /* Space for copies of dividers cells */
  42785. Pgno pgno; /* Temp var to store a page number in */
  42786. pBt = pParent->pBt;
  42787. assert( sqlite3_mutex_held(pBt->mutex) );
  42788. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  42789. #if 0
  42790. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  42791. #endif
  42792. /* At this point pParent may have at most one overflow cell. And if
  42793. ** this overflow cell is present, it must be the cell with
  42794. ** index iParentIdx. This scenario comes about when this function
  42795. ** is called (indirectly) from sqlite3BtreeDelete().
  42796. */
  42797. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  42798. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  42799. if( !aOvflSpace ){
  42800. return SQLITE_NOMEM;
  42801. }
  42802. /* Find the sibling pages to balance. Also locate the cells in pParent
  42803. ** that divide the siblings. An attempt is made to find NN siblings on
  42804. ** either side of pPage. More siblings are taken from one side, however,
  42805. ** if there are fewer than NN siblings on the other side. If pParent
  42806. ** has NB or fewer children then all children of pParent are taken.
  42807. **
  42808. ** This loop also drops the divider cells from the parent page. This
  42809. ** way, the remainder of the function does not have to deal with any
  42810. ** overflow cells in the parent page, since if any existed they will
  42811. ** have already been removed.
  42812. */
  42813. i = pParent->nOverflow + pParent->nCell;
  42814. if( i<2 ){
  42815. nxDiv = 0;
  42816. }else{
  42817. assert( bBulk==0 || bBulk==1 );
  42818. if( iParentIdx==0 ){
  42819. nxDiv = 0;
  42820. }else if( iParentIdx==i ){
  42821. nxDiv = i-2+bBulk;
  42822. }else{
  42823. assert( bBulk==0 );
  42824. nxDiv = iParentIdx-1;
  42825. }
  42826. i = 2-bBulk;
  42827. }
  42828. nOld = i+1;
  42829. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  42830. pRight = &pParent->aData[pParent->hdrOffset+8];
  42831. }else{
  42832. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  42833. }
  42834. pgno = get4byte(pRight);
  42835. while( 1 ){
  42836. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  42837. if( rc ){
  42838. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  42839. goto balance_cleanup;
  42840. }
  42841. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  42842. if( (i--)==0 ) break;
  42843. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  42844. apDiv[i] = pParent->apOvfl[0];
  42845. pgno = get4byte(apDiv[i]);
  42846. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  42847. pParent->nOverflow = 0;
  42848. }else{
  42849. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  42850. pgno = get4byte(apDiv[i]);
  42851. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  42852. /* Drop the cell from the parent page. apDiv[i] still points to
  42853. ** the cell within the parent, even though it has been dropped.
  42854. ** This is safe because dropping a cell only overwrites the first
  42855. ** four bytes of it, and this function does not need the first
  42856. ** four bytes of the divider cell. So the pointer is safe to use
  42857. ** later on.
  42858. **
  42859. ** But not if we are in secure-delete mode. In secure-delete mode,
  42860. ** the dropCell() routine will overwrite the entire cell with zeroes.
  42861. ** In this case, temporarily copy the cell into the aOvflSpace[]
  42862. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  42863. ** is allocated. */
  42864. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  42865. int iOff;
  42866. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  42867. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  42868. rc = SQLITE_CORRUPT_BKPT;
  42869. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  42870. goto balance_cleanup;
  42871. }else{
  42872. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  42873. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  42874. }
  42875. }
  42876. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  42877. }
  42878. }
  42879. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  42880. ** alignment */
  42881. nMaxCells = (nMaxCells + 3)&~3;
  42882. /*
  42883. ** Allocate space for memory structures
  42884. */
  42885. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  42886. szScratch =
  42887. nMaxCells*sizeof(u8*) /* apCell */
  42888. + nMaxCells*sizeof(u16) /* szCell */
  42889. + pBt->pageSize /* aSpace1 */
  42890. + k*nOld; /* Page copies (apCopy) */
  42891. apCell = sqlite3ScratchMalloc( szScratch );
  42892. if( apCell==0 ){
  42893. rc = SQLITE_NOMEM;
  42894. goto balance_cleanup;
  42895. }
  42896. szCell = (u16*)&apCell[nMaxCells];
  42897. aSpace1 = (u8*)&szCell[nMaxCells];
  42898. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  42899. /*
  42900. ** Load pointers to all cells on sibling pages and the divider cells
  42901. ** into the local apCell[] array. Make copies of the divider cells
  42902. ** into space obtained from aSpace1[] and remove the divider cells
  42903. ** from pParent.
  42904. **
  42905. ** If the siblings are on leaf pages, then the child pointers of the
  42906. ** divider cells are stripped from the cells before they are copied
  42907. ** into aSpace1[]. In this way, all cells in apCell[] are without
  42908. ** child pointers. If siblings are not leaves, then all cell in
  42909. ** apCell[] include child pointers. Either way, all cells in apCell[]
  42910. ** are alike.
  42911. **
  42912. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  42913. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  42914. */
  42915. leafCorrection = apOld[0]->leaf*4;
  42916. leafData = apOld[0]->hasData;
  42917. for(i=0; i<nOld; i++){
  42918. int limit;
  42919. /* Before doing anything else, take a copy of the i'th original sibling
  42920. ** The rest of this function will use data from the copies rather
  42921. ** that the original pages since the original pages will be in the
  42922. ** process of being overwritten. */
  42923. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  42924. memcpy(pOld, apOld[i], sizeof(MemPage));
  42925. pOld->aData = (void*)&pOld[1];
  42926. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  42927. limit = pOld->nCell+pOld->nOverflow;
  42928. if( pOld->nOverflow>0 ){
  42929. for(j=0; j<limit; j++){
  42930. assert( nCell<nMaxCells );
  42931. apCell[nCell] = findOverflowCell(pOld, j);
  42932. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  42933. nCell++;
  42934. }
  42935. }else{
  42936. u8 *aData = pOld->aData;
  42937. u16 maskPage = pOld->maskPage;
  42938. u16 cellOffset = pOld->cellOffset;
  42939. for(j=0; j<limit; j++){
  42940. assert( nCell<nMaxCells );
  42941. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  42942. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  42943. nCell++;
  42944. }
  42945. }
  42946. if( i<nOld-1 && !leafData){
  42947. u16 sz = (u16)szNew[i];
  42948. u8 *pTemp;
  42949. assert( nCell<nMaxCells );
  42950. szCell[nCell] = sz;
  42951. pTemp = &aSpace1[iSpace1];
  42952. iSpace1 += sz;
  42953. assert( sz<=pBt->maxLocal+23 );
  42954. assert( iSpace1 <= (int)pBt->pageSize );
  42955. memcpy(pTemp, apDiv[i], sz);
  42956. apCell[nCell] = pTemp+leafCorrection;
  42957. assert( leafCorrection==0 || leafCorrection==4 );
  42958. szCell[nCell] = szCell[nCell] - leafCorrection;
  42959. if( !pOld->leaf ){
  42960. assert( leafCorrection==0 );
  42961. assert( pOld->hdrOffset==0 );
  42962. /* The right pointer of the child page pOld becomes the left
  42963. ** pointer of the divider cell */
  42964. memcpy(apCell[nCell], &pOld->aData[8], 4);
  42965. }else{
  42966. assert( leafCorrection==4 );
  42967. if( szCell[nCell]<4 ){
  42968. /* Do not allow any cells smaller than 4 bytes. */
  42969. szCell[nCell] = 4;
  42970. }
  42971. }
  42972. nCell++;
  42973. }
  42974. }
  42975. /*
  42976. ** Figure out the number of pages needed to hold all nCell cells.
  42977. ** Store this number in "k". Also compute szNew[] which is the total
  42978. ** size of all cells on the i-th page and cntNew[] which is the index
  42979. ** in apCell[] of the cell that divides page i from page i+1.
  42980. ** cntNew[k] should equal nCell.
  42981. **
  42982. ** Values computed by this block:
  42983. **
  42984. ** k: The total number of sibling pages
  42985. ** szNew[i]: Spaced used on the i-th sibling page.
  42986. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  42987. ** the right of the i-th sibling page.
  42988. ** usableSpace: Number of bytes of space available on each sibling.
  42989. **
  42990. */
  42991. usableSpace = pBt->usableSize - 12 + leafCorrection;
  42992. for(subtotal=k=i=0; i<nCell; i++){
  42993. assert( i<nMaxCells );
  42994. subtotal += szCell[i] + 2;
  42995. if( subtotal > usableSpace ){
  42996. szNew[k] = subtotal - szCell[i];
  42997. cntNew[k] = i;
  42998. if( leafData ){ i--; }
  42999. subtotal = 0;
  43000. k++;
  43001. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  43002. }
  43003. }
  43004. szNew[k] = subtotal;
  43005. cntNew[k] = nCell;
  43006. k++;
  43007. /*
  43008. ** The packing computed by the previous block is biased toward the siblings
  43009. ** on the left side. The left siblings are always nearly full, while the
  43010. ** right-most sibling might be nearly empty. This block of code attempts
  43011. ** to adjust the packing of siblings to get a better balance.
  43012. **
  43013. ** This adjustment is more than an optimization. The packing above might
  43014. ** be so out of balance as to be illegal. For example, the right-most
  43015. ** sibling might be completely empty. This adjustment is not optional.
  43016. */
  43017. for(i=k-1; i>0; i--){
  43018. int szRight = szNew[i]; /* Size of sibling on the right */
  43019. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  43020. int r; /* Index of right-most cell in left sibling */
  43021. int d; /* Index of first cell to the left of right sibling */
  43022. r = cntNew[i-1] - 1;
  43023. d = r + 1 - leafData;
  43024. assert( d<nMaxCells );
  43025. assert( r<nMaxCells );
  43026. while( szRight==0
  43027. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  43028. ){
  43029. szRight += szCell[d] + 2;
  43030. szLeft -= szCell[r] + 2;
  43031. cntNew[i-1]--;
  43032. r = cntNew[i-1] - 1;
  43033. d = r + 1 - leafData;
  43034. }
  43035. szNew[i] = szRight;
  43036. szNew[i-1] = szLeft;
  43037. }
  43038. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  43039. ** a virtual root page. A virtual root page is when the real root
  43040. ** page is page 1 and we are the only child of that page.
  43041. **
  43042. ** UPDATE: The assert() below is not necessarily true if the database
  43043. ** file is corrupt. The corruption will be detected and reported later
  43044. ** in this procedure so there is no need to act upon it now.
  43045. */
  43046. #if 0
  43047. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  43048. #endif
  43049. TRACE(("BALANCE: old: %d %d %d ",
  43050. apOld[0]->pgno,
  43051. nOld>=2 ? apOld[1]->pgno : 0,
  43052. nOld>=3 ? apOld[2]->pgno : 0
  43053. ));
  43054. /*
  43055. ** Allocate k new pages. Reuse old pages where possible.
  43056. */
  43057. if( apOld[0]->pgno<=1 ){
  43058. rc = SQLITE_CORRUPT_BKPT;
  43059. goto balance_cleanup;
  43060. }
  43061. pageFlags = apOld[0]->aData[0];
  43062. for(i=0; i<k; i++){
  43063. MemPage *pNew;
  43064. if( i<nOld ){
  43065. pNew = apNew[i] = apOld[i];
  43066. apOld[i] = 0;
  43067. rc = sqlite3PagerWrite(pNew->pDbPage);
  43068. nNew++;
  43069. if( rc ) goto balance_cleanup;
  43070. }else{
  43071. assert( i>0 );
  43072. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  43073. if( rc ) goto balance_cleanup;
  43074. apNew[i] = pNew;
  43075. nNew++;
  43076. /* Set the pointer-map entry for the new sibling page. */
  43077. if( ISAUTOVACUUM ){
  43078. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  43079. if( rc!=SQLITE_OK ){
  43080. goto balance_cleanup;
  43081. }
  43082. }
  43083. }
  43084. }
  43085. /* Free any old pages that were not reused as new pages.
  43086. */
  43087. while( i<nOld ){
  43088. freePage(apOld[i], &rc);
  43089. if( rc ) goto balance_cleanup;
  43090. releasePage(apOld[i]);
  43091. apOld[i] = 0;
  43092. i++;
  43093. }
  43094. /*
  43095. ** Put the new pages in accending order. This helps to
  43096. ** keep entries in the disk file in order so that a scan
  43097. ** of the table is a linear scan through the file. That
  43098. ** in turn helps the operating system to deliver pages
  43099. ** from the disk more rapidly.
  43100. **
  43101. ** An O(n^2) insertion sort algorithm is used, but since
  43102. ** n is never more than NB (a small constant), that should
  43103. ** not be a problem.
  43104. **
  43105. ** When NB==3, this one optimization makes the database
  43106. ** about 25% faster for large insertions and deletions.
  43107. */
  43108. for(i=0; i<k-1; i++){
  43109. int minV = apNew[i]->pgno;
  43110. int minI = i;
  43111. for(j=i+1; j<k; j++){
  43112. if( apNew[j]->pgno<(unsigned)minV ){
  43113. minI = j;
  43114. minV = apNew[j]->pgno;
  43115. }
  43116. }
  43117. if( minI>i ){
  43118. MemPage *pT;
  43119. pT = apNew[i];
  43120. apNew[i] = apNew[minI];
  43121. apNew[minI] = pT;
  43122. }
  43123. }
  43124. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  43125. apNew[0]->pgno, szNew[0],
  43126. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  43127. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  43128. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  43129. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  43130. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  43131. put4byte(pRight, apNew[nNew-1]->pgno);
  43132. /*
  43133. ** Evenly distribute the data in apCell[] across the new pages.
  43134. ** Insert divider cells into pParent as necessary.
  43135. */
  43136. j = 0;
  43137. for(i=0; i<nNew; i++){
  43138. /* Assemble the new sibling page. */
  43139. MemPage *pNew = apNew[i];
  43140. assert( j<nMaxCells );
  43141. zeroPage(pNew, pageFlags);
  43142. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  43143. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  43144. assert( pNew->nOverflow==0 );
  43145. j = cntNew[i];
  43146. /* If the sibling page assembled above was not the right-most sibling,
  43147. ** insert a divider cell into the parent page.
  43148. */
  43149. assert( i<nNew-1 || j==nCell );
  43150. if( j<nCell ){
  43151. u8 *pCell;
  43152. u8 *pTemp;
  43153. int sz;
  43154. assert( j<nMaxCells );
  43155. pCell = apCell[j];
  43156. sz = szCell[j] + leafCorrection;
  43157. pTemp = &aOvflSpace[iOvflSpace];
  43158. if( !pNew->leaf ){
  43159. memcpy(&pNew->aData[8], pCell, 4);
  43160. }else if( leafData ){
  43161. /* If the tree is a leaf-data tree, and the siblings are leaves,
  43162. ** then there is no divider cell in apCell[]. Instead, the divider
  43163. ** cell consists of the integer key for the right-most cell of
  43164. ** the sibling-page assembled above only.
  43165. */
  43166. CellInfo info;
  43167. j--;
  43168. btreeParseCellPtr(pNew, apCell[j], &info);
  43169. pCell = pTemp;
  43170. sz = 4 + putVarint(&pCell[4], info.nKey);
  43171. pTemp = 0;
  43172. }else{
  43173. pCell -= 4;
  43174. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  43175. ** previously stored on a leaf node, and its reported size was 4
  43176. ** bytes, then it may actually be smaller than this
  43177. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  43178. ** any cell). But it is important to pass the correct size to
  43179. ** insertCell(), so reparse the cell now.
  43180. **
  43181. ** Note that this can never happen in an SQLite data file, as all
  43182. ** cells are at least 4 bytes. It only happens in b-trees used
  43183. ** to evaluate "IN (SELECT ...)" and similar clauses.
  43184. */
  43185. if( szCell[j]==4 ){
  43186. assert(leafCorrection==4);
  43187. sz = cellSizePtr(pParent, pCell);
  43188. }
  43189. }
  43190. iOvflSpace += sz;
  43191. assert( sz<=pBt->maxLocal+23 );
  43192. assert( iOvflSpace <= (int)pBt->pageSize );
  43193. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  43194. if( rc!=SQLITE_OK ) goto balance_cleanup;
  43195. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  43196. j++;
  43197. nxDiv++;
  43198. }
  43199. }
  43200. assert( j==nCell );
  43201. assert( nOld>0 );
  43202. assert( nNew>0 );
  43203. if( (pageFlags & PTF_LEAF)==0 ){
  43204. u8 *zChild = &apCopy[nOld-1]->aData[8];
  43205. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  43206. }
  43207. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  43208. /* The root page of the b-tree now contains no cells. The only sibling
  43209. ** page is the right-child of the parent. Copy the contents of the
  43210. ** child page into the parent, decreasing the overall height of the
  43211. ** b-tree structure by one. This is described as the "balance-shallower"
  43212. ** sub-algorithm in some documentation.
  43213. **
  43214. ** If this is an auto-vacuum database, the call to copyNodeContent()
  43215. ** sets all pointer-map entries corresponding to database image pages
  43216. ** for which the pointer is stored within the content being copied.
  43217. **
  43218. ** The second assert below verifies that the child page is defragmented
  43219. ** (it must be, as it was just reconstructed using assemblePage()). This
  43220. ** is important if the parent page happens to be page 1 of the database
  43221. ** image. */
  43222. assert( nNew==1 );
  43223. assert( apNew[0]->nFree ==
  43224. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  43225. );
  43226. copyNodeContent(apNew[0], pParent, &rc);
  43227. freePage(apNew[0], &rc);
  43228. }else if( ISAUTOVACUUM ){
  43229. /* Fix the pointer-map entries for all the cells that were shifted around.
  43230. ** There are several different types of pointer-map entries that need to
  43231. ** be dealt with by this routine. Some of these have been set already, but
  43232. ** many have not. The following is a summary:
  43233. **
  43234. ** 1) The entries associated with new sibling pages that were not
  43235. ** siblings when this function was called. These have already
  43236. ** been set. We don't need to worry about old siblings that were
  43237. ** moved to the free-list - the freePage() code has taken care
  43238. ** of those.
  43239. **
  43240. ** 2) The pointer-map entries associated with the first overflow
  43241. ** page in any overflow chains used by new divider cells. These
  43242. ** have also already been taken care of by the insertCell() code.
  43243. **
  43244. ** 3) If the sibling pages are not leaves, then the child pages of
  43245. ** cells stored on the sibling pages may need to be updated.
  43246. **
  43247. ** 4) If the sibling pages are not internal intkey nodes, then any
  43248. ** overflow pages used by these cells may need to be updated
  43249. ** (internal intkey nodes never contain pointers to overflow pages).
  43250. **
  43251. ** 5) If the sibling pages are not leaves, then the pointer-map
  43252. ** entries for the right-child pages of each sibling may need
  43253. ** to be updated.
  43254. **
  43255. ** Cases 1 and 2 are dealt with above by other code. The next
  43256. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  43257. ** setting a pointer map entry is a relatively expensive operation, this
  43258. ** code only sets pointer map entries for child or overflow pages that have
  43259. ** actually moved between pages. */
  43260. MemPage *pNew = apNew[0];
  43261. MemPage *pOld = apCopy[0];
  43262. int nOverflow = pOld->nOverflow;
  43263. int iNextOld = pOld->nCell + nOverflow;
  43264. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  43265. j = 0; /* Current 'old' sibling page */
  43266. k = 0; /* Current 'new' sibling page */
  43267. for(i=0; i<nCell; i++){
  43268. int isDivider = 0;
  43269. while( i==iNextOld ){
  43270. /* Cell i is the cell immediately following the last cell on old
  43271. ** sibling page j. If the siblings are not leaf pages of an
  43272. ** intkey b-tree, then cell i was a divider cell. */
  43273. assert( j+1 < ArraySize(apCopy) );
  43274. assert( j+1 < nOld );
  43275. pOld = apCopy[++j];
  43276. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  43277. if( pOld->nOverflow ){
  43278. nOverflow = pOld->nOverflow;
  43279. iOverflow = i + !leafData + pOld->aiOvfl[0];
  43280. }
  43281. isDivider = !leafData;
  43282. }
  43283. assert(nOverflow>0 || iOverflow<i );
  43284. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  43285. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  43286. if( i==iOverflow ){
  43287. isDivider = 1;
  43288. if( (--nOverflow)>0 ){
  43289. iOverflow++;
  43290. }
  43291. }
  43292. if( i==cntNew[k] ){
  43293. /* Cell i is the cell immediately following the last cell on new
  43294. ** sibling page k. If the siblings are not leaf pages of an
  43295. ** intkey b-tree, then cell i is a divider cell. */
  43296. pNew = apNew[++k];
  43297. if( !leafData ) continue;
  43298. }
  43299. assert( j<nOld );
  43300. assert( k<nNew );
  43301. /* If the cell was originally divider cell (and is not now) or
  43302. ** an overflow cell, or if the cell was located on a different sibling
  43303. ** page before the balancing, then the pointer map entries associated
  43304. ** with any child or overflow pages need to be updated. */
  43305. if( isDivider || pOld->pgno!=pNew->pgno ){
  43306. if( !leafCorrection ){
  43307. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  43308. }
  43309. if( szCell[i]>pNew->minLocal ){
  43310. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  43311. }
  43312. }
  43313. }
  43314. if( !leafCorrection ){
  43315. for(i=0; i<nNew; i++){
  43316. u32 key = get4byte(&apNew[i]->aData[8]);
  43317. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  43318. }
  43319. }
  43320. #if 0
  43321. /* The ptrmapCheckPages() contains assert() statements that verify that
  43322. ** all pointer map pages are set correctly. This is helpful while
  43323. ** debugging. This is usually disabled because a corrupt database may
  43324. ** cause an assert() statement to fail. */
  43325. ptrmapCheckPages(apNew, nNew);
  43326. ptrmapCheckPages(&pParent, 1);
  43327. #endif
  43328. }
  43329. assert( pParent->isInit );
  43330. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  43331. nOld, nNew, nCell));
  43332. /*
  43333. ** Cleanup before returning.
  43334. */
  43335. balance_cleanup:
  43336. sqlite3ScratchFree(apCell);
  43337. for(i=0; i<nOld; i++){
  43338. releasePage(apOld[i]);
  43339. }
  43340. for(i=0; i<nNew; i++){
  43341. releasePage(apNew[i]);
  43342. }
  43343. return rc;
  43344. }
  43345. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  43346. #pragma optimize("", on)
  43347. #endif
  43348. /*
  43349. ** This function is called when the root page of a b-tree structure is
  43350. ** overfull (has one or more overflow pages).
  43351. **
  43352. ** A new child page is allocated and the contents of the current root
  43353. ** page, including overflow cells, are copied into the child. The root
  43354. ** page is then overwritten to make it an empty page with the right-child
  43355. ** pointer pointing to the new page.
  43356. **
  43357. ** Before returning, all pointer-map entries corresponding to pages
  43358. ** that the new child-page now contains pointers to are updated. The
  43359. ** entry corresponding to the new right-child pointer of the root
  43360. ** page is also updated.
  43361. **
  43362. ** If successful, *ppChild is set to contain a reference to the child
  43363. ** page and SQLITE_OK is returned. In this case the caller is required
  43364. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  43365. ** an error code is returned and *ppChild is set to 0.
  43366. */
  43367. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  43368. int rc; /* Return value from subprocedures */
  43369. MemPage *pChild = 0; /* Pointer to a new child page */
  43370. Pgno pgnoChild = 0; /* Page number of the new child page */
  43371. BtShared *pBt = pRoot->pBt; /* The BTree */
  43372. assert( pRoot->nOverflow>0 );
  43373. assert( sqlite3_mutex_held(pBt->mutex) );
  43374. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  43375. ** page that will become the new right-child of pPage. Copy the contents
  43376. ** of the node stored on pRoot into the new child page.
  43377. */
  43378. rc = sqlite3PagerWrite(pRoot->pDbPage);
  43379. if( rc==SQLITE_OK ){
  43380. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  43381. copyNodeContent(pRoot, pChild, &rc);
  43382. if( ISAUTOVACUUM ){
  43383. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  43384. }
  43385. }
  43386. if( rc ){
  43387. *ppChild = 0;
  43388. releasePage(pChild);
  43389. return rc;
  43390. }
  43391. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  43392. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  43393. assert( pChild->nCell==pRoot->nCell );
  43394. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  43395. /* Copy the overflow cells from pRoot to pChild */
  43396. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  43397. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  43398. memcpy(pChild->apOvfl, pRoot->apOvfl,
  43399. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  43400. pChild->nOverflow = pRoot->nOverflow;
  43401. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  43402. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  43403. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  43404. *ppChild = pChild;
  43405. return SQLITE_OK;
  43406. }
  43407. /*
  43408. ** The page that pCur currently points to has just been modified in
  43409. ** some way. This function figures out if this modification means the
  43410. ** tree needs to be balanced, and if so calls the appropriate balancing
  43411. ** routine. Balancing routines are:
  43412. **
  43413. ** balance_quick()
  43414. ** balance_deeper()
  43415. ** balance_nonroot()
  43416. */
  43417. static int balance(BtCursor *pCur){
  43418. int rc = SQLITE_OK;
  43419. const int nMin = pCur->pBt->usableSize * 2 / 3;
  43420. u8 aBalanceQuickSpace[13];
  43421. u8 *pFree = 0;
  43422. TESTONLY( int balance_quick_called = 0 );
  43423. TESTONLY( int balance_deeper_called = 0 );
  43424. do {
  43425. int iPage = pCur->iPage;
  43426. MemPage *pPage = pCur->apPage[iPage];
  43427. if( iPage==0 ){
  43428. if( pPage->nOverflow ){
  43429. /* The root page of the b-tree is overfull. In this case call the
  43430. ** balance_deeper() function to create a new child for the root-page
  43431. ** and copy the current contents of the root-page to it. The
  43432. ** next iteration of the do-loop will balance the child page.
  43433. */
  43434. assert( (balance_deeper_called++)==0 );
  43435. rc = balance_deeper(pPage, &pCur->apPage[1]);
  43436. if( rc==SQLITE_OK ){
  43437. pCur->iPage = 1;
  43438. pCur->aiIdx[0] = 0;
  43439. pCur->aiIdx[1] = 0;
  43440. assert( pCur->apPage[1]->nOverflow );
  43441. }
  43442. }else{
  43443. break;
  43444. }
  43445. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  43446. break;
  43447. }else{
  43448. MemPage * const pParent = pCur->apPage[iPage-1];
  43449. int const iIdx = pCur->aiIdx[iPage-1];
  43450. rc = sqlite3PagerWrite(pParent->pDbPage);
  43451. if( rc==SQLITE_OK ){
  43452. #ifndef SQLITE_OMIT_QUICKBALANCE
  43453. if( pPage->hasData
  43454. && pPage->nOverflow==1
  43455. && pPage->aiOvfl[0]==pPage->nCell
  43456. && pParent->pgno!=1
  43457. && pParent->nCell==iIdx
  43458. ){
  43459. /* Call balance_quick() to create a new sibling of pPage on which
  43460. ** to store the overflow cell. balance_quick() inserts a new cell
  43461. ** into pParent, which may cause pParent overflow. If this
  43462. ** happens, the next interation of the do-loop will balance pParent
  43463. ** use either balance_nonroot() or balance_deeper(). Until this
  43464. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  43465. ** buffer.
  43466. **
  43467. ** The purpose of the following assert() is to check that only a
  43468. ** single call to balance_quick() is made for each call to this
  43469. ** function. If this were not verified, a subtle bug involving reuse
  43470. ** of the aBalanceQuickSpace[] might sneak in.
  43471. */
  43472. assert( (balance_quick_called++)==0 );
  43473. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  43474. }else
  43475. #endif
  43476. {
  43477. /* In this case, call balance_nonroot() to redistribute cells
  43478. ** between pPage and up to 2 of its sibling pages. This involves
  43479. ** modifying the contents of pParent, which may cause pParent to
  43480. ** become overfull or underfull. The next iteration of the do-loop
  43481. ** will balance the parent page to correct this.
  43482. **
  43483. ** If the parent page becomes overfull, the overflow cell or cells
  43484. ** are stored in the pSpace buffer allocated immediately below.
  43485. ** A subsequent iteration of the do-loop will deal with this by
  43486. ** calling balance_nonroot() (balance_deeper() may be called first,
  43487. ** but it doesn't deal with overflow cells - just moves them to a
  43488. ** different page). Once this subsequent call to balance_nonroot()
  43489. ** has completed, it is safe to release the pSpace buffer used by
  43490. ** the previous call, as the overflow cell data will have been
  43491. ** copied either into the body of a database page or into the new
  43492. ** pSpace buffer passed to the latter call to balance_nonroot().
  43493. */
  43494. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  43495. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  43496. if( pFree ){
  43497. /* If pFree is not NULL, it points to the pSpace buffer used
  43498. ** by a previous call to balance_nonroot(). Its contents are
  43499. ** now stored either on real database pages or within the
  43500. ** new pSpace buffer, so it may be safely freed here. */
  43501. sqlite3PageFree(pFree);
  43502. }
  43503. /* The pSpace buffer will be freed after the next call to
  43504. ** balance_nonroot(), or just before this function returns, whichever
  43505. ** comes first. */
  43506. pFree = pSpace;
  43507. }
  43508. }
  43509. pPage->nOverflow = 0;
  43510. /* The next iteration of the do-loop balances the parent page. */
  43511. releasePage(pPage);
  43512. pCur->iPage--;
  43513. }
  43514. }while( rc==SQLITE_OK );
  43515. if( pFree ){
  43516. sqlite3PageFree(pFree);
  43517. }
  43518. return rc;
  43519. }
  43520. /*
  43521. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  43522. ** and the data is given by (pData,nData). The cursor is used only to
  43523. ** define what table the record should be inserted into. The cursor
  43524. ** is left pointing at a random location.
  43525. **
  43526. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  43527. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  43528. **
  43529. ** If the seekResult parameter is non-zero, then a successful call to
  43530. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  43531. ** been performed. seekResult is the search result returned (a negative
  43532. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  43533. ** a positive value if pCur points at an etry that is larger than
  43534. ** (pKey, nKey)).
  43535. **
  43536. ** If the seekResult parameter is non-zero, then the caller guarantees that
  43537. ** cursor pCur is pointing at the existing copy of a row that is to be
  43538. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  43539. ** point to any entry or to no entry at all and so this function has to seek
  43540. ** the cursor before the new key can be inserted.
  43541. */
  43542. SQLITE_PRIVATE int sqlite3BtreeInsert(
  43543. BtCursor *pCur, /* Insert data into the table of this cursor */
  43544. const void *pKey, i64 nKey, /* The key of the new record */
  43545. const void *pData, int nData, /* The data of the new record */
  43546. int nZero, /* Number of extra 0 bytes to append to data */
  43547. int appendBias, /* True if this is likely an append */
  43548. int seekResult /* Result of prior MovetoUnpacked() call */
  43549. ){
  43550. int rc;
  43551. int loc = seekResult; /* -1: before desired location +1: after */
  43552. int szNew = 0;
  43553. int idx;
  43554. MemPage *pPage;
  43555. Btree *p = pCur->pBtree;
  43556. BtShared *pBt = p->pBt;
  43557. unsigned char *oldCell;
  43558. unsigned char *newCell = 0;
  43559. if( pCur->eState==CURSOR_FAULT ){
  43560. assert( pCur->skipNext!=SQLITE_OK );
  43561. return pCur->skipNext;
  43562. }
  43563. assert( cursorHoldsMutex(pCur) );
  43564. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  43565. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43566. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  43567. /* Assert that the caller has been consistent. If this cursor was opened
  43568. ** expecting an index b-tree, then the caller should be inserting blob
  43569. ** keys with no associated data. If the cursor was opened expecting an
  43570. ** intkey table, the caller should be inserting integer keys with a
  43571. ** blob of associated data. */
  43572. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  43573. /* Save the positions of any other cursors open on this table.
  43574. **
  43575. ** In some cases, the call to btreeMoveto() below is a no-op. For
  43576. ** example, when inserting data into a table with auto-generated integer
  43577. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  43578. ** integer key to use. It then calls this function to actually insert the
  43579. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  43580. ** that the cursor is already where it needs to be and returns without
  43581. ** doing any work. To avoid thwarting these optimizations, it is important
  43582. ** not to clear the cursor here.
  43583. */
  43584. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  43585. if( rc ) return rc;
  43586. /* If this is an insert into a table b-tree, invalidate any incrblob
  43587. ** cursors open on the row being replaced (assuming this is a replace
  43588. ** operation - if it is not, the following is a no-op). */
  43589. if( pCur->pKeyInfo==0 ){
  43590. invalidateIncrblobCursors(p, nKey, 0);
  43591. }
  43592. if( !loc ){
  43593. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  43594. if( rc ) return rc;
  43595. }
  43596. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  43597. pPage = pCur->apPage[pCur->iPage];
  43598. assert( pPage->intKey || nKey>=0 );
  43599. assert( pPage->leaf || !pPage->intKey );
  43600. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  43601. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  43602. loc==0 ? "overwrite" : "new entry"));
  43603. assert( pPage->isInit );
  43604. allocateTempSpace(pBt);
  43605. newCell = pBt->pTmpSpace;
  43606. if( newCell==0 ) return SQLITE_NOMEM;
  43607. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  43608. if( rc ) goto end_insert;
  43609. assert( szNew==cellSizePtr(pPage, newCell) );
  43610. assert( szNew <= MX_CELL_SIZE(pBt) );
  43611. idx = pCur->aiIdx[pCur->iPage];
  43612. if( loc==0 ){
  43613. u16 szOld;
  43614. assert( idx<pPage->nCell );
  43615. rc = sqlite3PagerWrite(pPage->pDbPage);
  43616. if( rc ){
  43617. goto end_insert;
  43618. }
  43619. oldCell = findCell(pPage, idx);
  43620. if( !pPage->leaf ){
  43621. memcpy(newCell, oldCell, 4);
  43622. }
  43623. szOld = cellSizePtr(pPage, oldCell);
  43624. rc = clearCell(pPage, oldCell);
  43625. dropCell(pPage, idx, szOld, &rc);
  43626. if( rc ) goto end_insert;
  43627. }else if( loc<0 && pPage->nCell>0 ){
  43628. assert( pPage->leaf );
  43629. idx = ++pCur->aiIdx[pCur->iPage];
  43630. }else{
  43631. assert( pPage->leaf );
  43632. }
  43633. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  43634. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  43635. /* If no error has occurred and pPage has an overflow cell, call balance()
  43636. ** to redistribute the cells within the tree. Since balance() may move
  43637. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  43638. ** variables.
  43639. **
  43640. ** Previous versions of SQLite called moveToRoot() to move the cursor
  43641. ** back to the root page as balance() used to invalidate the contents
  43642. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  43643. ** set the cursor state to "invalid". This makes common insert operations
  43644. ** slightly faster.
  43645. **
  43646. ** There is a subtle but important optimization here too. When inserting
  43647. ** multiple records into an intkey b-tree using a single cursor (as can
  43648. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  43649. ** is advantageous to leave the cursor pointing to the last entry in
  43650. ** the b-tree if possible. If the cursor is left pointing to the last
  43651. ** entry in the table, and the next row inserted has an integer key
  43652. ** larger than the largest existing key, it is possible to insert the
  43653. ** row without seeking the cursor. This can be a big performance boost.
  43654. */
  43655. pCur->info.nSize = 0;
  43656. pCur->validNKey = 0;
  43657. if( rc==SQLITE_OK && pPage->nOverflow ){
  43658. rc = balance(pCur);
  43659. /* Must make sure nOverflow is reset to zero even if the balance()
  43660. ** fails. Internal data structure corruption will result otherwise.
  43661. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  43662. ** from trying to save the current position of the cursor. */
  43663. pCur->apPage[pCur->iPage]->nOverflow = 0;
  43664. pCur->eState = CURSOR_INVALID;
  43665. }
  43666. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  43667. end_insert:
  43668. return rc;
  43669. }
  43670. /*
  43671. ** Delete the entry that the cursor is pointing to. The cursor
  43672. ** is left pointing at a arbitrary location.
  43673. */
  43674. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  43675. Btree *p = pCur->pBtree;
  43676. BtShared *pBt = p->pBt;
  43677. int rc; /* Return code */
  43678. MemPage *pPage; /* Page to delete cell from */
  43679. unsigned char *pCell; /* Pointer to cell to delete */
  43680. int iCellIdx; /* Index of cell to delete */
  43681. int iCellDepth; /* Depth of node containing pCell */
  43682. assert( cursorHoldsMutex(pCur) );
  43683. assert( pBt->inTransaction==TRANS_WRITE );
  43684. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43685. assert( pCur->wrFlag );
  43686. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  43687. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  43688. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  43689. || NEVER(pCur->eState!=CURSOR_VALID)
  43690. ){
  43691. return SQLITE_ERROR; /* Something has gone awry. */
  43692. }
  43693. iCellDepth = pCur->iPage;
  43694. iCellIdx = pCur->aiIdx[iCellDepth];
  43695. pPage = pCur->apPage[iCellDepth];
  43696. pCell = findCell(pPage, iCellIdx);
  43697. /* If the page containing the entry to delete is not a leaf page, move
  43698. ** the cursor to the largest entry in the tree that is smaller than
  43699. ** the entry being deleted. This cell will replace the cell being deleted
  43700. ** from the internal node. The 'previous' entry is used for this instead
  43701. ** of the 'next' entry, as the previous entry is always a part of the
  43702. ** sub-tree headed by the child page of the cell being deleted. This makes
  43703. ** balancing the tree following the delete operation easier. */
  43704. if( !pPage->leaf ){
  43705. int notUsed;
  43706. rc = sqlite3BtreePrevious(pCur, &notUsed);
  43707. if( rc ) return rc;
  43708. }
  43709. /* Save the positions of any other cursors open on this table before
  43710. ** making any modifications. Make the page containing the entry to be
  43711. ** deleted writable. Then free any overflow pages associated with the
  43712. ** entry and finally remove the cell itself from within the page.
  43713. */
  43714. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  43715. if( rc ) return rc;
  43716. /* If this is a delete operation to remove a row from a table b-tree,
  43717. ** invalidate any incrblob cursors open on the row being deleted. */
  43718. if( pCur->pKeyInfo==0 ){
  43719. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  43720. }
  43721. rc = sqlite3PagerWrite(pPage->pDbPage);
  43722. if( rc ) return rc;
  43723. rc = clearCell(pPage, pCell);
  43724. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  43725. if( rc ) return rc;
  43726. /* If the cell deleted was not located on a leaf page, then the cursor
  43727. ** is currently pointing to the largest entry in the sub-tree headed
  43728. ** by the child-page of the cell that was just deleted from an internal
  43729. ** node. The cell from the leaf node needs to be moved to the internal
  43730. ** node to replace the deleted cell. */
  43731. if( !pPage->leaf ){
  43732. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  43733. int nCell;
  43734. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  43735. unsigned char *pTmp;
  43736. pCell = findCell(pLeaf, pLeaf->nCell-1);
  43737. nCell = cellSizePtr(pLeaf, pCell);
  43738. assert( MX_CELL_SIZE(pBt) >= nCell );
  43739. allocateTempSpace(pBt);
  43740. pTmp = pBt->pTmpSpace;
  43741. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  43742. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  43743. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  43744. if( rc ) return rc;
  43745. }
  43746. /* Balance the tree. If the entry deleted was located on a leaf page,
  43747. ** then the cursor still points to that page. In this case the first
  43748. ** call to balance() repairs the tree, and the if(...) condition is
  43749. ** never true.
  43750. **
  43751. ** Otherwise, if the entry deleted was on an internal node page, then
  43752. ** pCur is pointing to the leaf page from which a cell was removed to
  43753. ** replace the cell deleted from the internal node. This is slightly
  43754. ** tricky as the leaf node may be underfull, and the internal node may
  43755. ** be either under or overfull. In this case run the balancing algorithm
  43756. ** on the leaf node first. If the balance proceeds far enough up the
  43757. ** tree that we can be sure that any problem in the internal node has
  43758. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  43759. ** walk the cursor up the tree to the internal node and balance it as
  43760. ** well. */
  43761. rc = balance(pCur);
  43762. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  43763. while( pCur->iPage>iCellDepth ){
  43764. releasePage(pCur->apPage[pCur->iPage--]);
  43765. }
  43766. rc = balance(pCur);
  43767. }
  43768. if( rc==SQLITE_OK ){
  43769. moveToRoot(pCur);
  43770. }
  43771. return rc;
  43772. }
  43773. /*
  43774. ** Create a new BTree table. Write into *piTable the page
  43775. ** number for the root page of the new table.
  43776. **
  43777. ** The type of type is determined by the flags parameter. Only the
  43778. ** following values of flags are currently in use. Other values for
  43779. ** flags might not work:
  43780. **
  43781. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  43782. ** BTREE_ZERODATA Used for SQL indices
  43783. */
  43784. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  43785. BtShared *pBt = p->pBt;
  43786. MemPage *pRoot;
  43787. Pgno pgnoRoot;
  43788. int rc;
  43789. int ptfFlags; /* Page-type flage for the root page of new table */
  43790. assert( sqlite3BtreeHoldsMutex(p) );
  43791. assert( pBt->inTransaction==TRANS_WRITE );
  43792. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43793. #ifdef SQLITE_OMIT_AUTOVACUUM
  43794. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  43795. if( rc ){
  43796. return rc;
  43797. }
  43798. #else
  43799. if( pBt->autoVacuum ){
  43800. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  43801. MemPage *pPageMove; /* The page to move to. */
  43802. /* Creating a new table may probably require moving an existing database
  43803. ** to make room for the new tables root page. In case this page turns
  43804. ** out to be an overflow page, delete all overflow page-map caches
  43805. ** held by open cursors.
  43806. */
  43807. invalidateAllOverflowCache(pBt);
  43808. /* Read the value of meta[3] from the database to determine where the
  43809. ** root page of the new table should go. meta[3] is the largest root-page
  43810. ** created so far, so the new root-page is (meta[3]+1).
  43811. */
  43812. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  43813. pgnoRoot++;
  43814. /* The new root-page may not be allocated on a pointer-map page, or the
  43815. ** PENDING_BYTE page.
  43816. */
  43817. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  43818. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  43819. pgnoRoot++;
  43820. }
  43821. assert( pgnoRoot>=3 );
  43822. /* Allocate a page. The page that currently resides at pgnoRoot will
  43823. ** be moved to the allocated page (unless the allocated page happens
  43824. ** to reside at pgnoRoot).
  43825. */
  43826. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  43827. if( rc!=SQLITE_OK ){
  43828. return rc;
  43829. }
  43830. if( pgnoMove!=pgnoRoot ){
  43831. /* pgnoRoot is the page that will be used for the root-page of
  43832. ** the new table (assuming an error did not occur). But we were
  43833. ** allocated pgnoMove. If required (i.e. if it was not allocated
  43834. ** by extending the file), the current page at position pgnoMove
  43835. ** is already journaled.
  43836. */
  43837. u8 eType = 0;
  43838. Pgno iPtrPage = 0;
  43839. /* Save the positions of any open cursors. This is required in
  43840. ** case they are holding a reference to an xFetch reference
  43841. ** corresponding to page pgnoRoot. */
  43842. rc = saveAllCursors(pBt, 0, 0);
  43843. releasePage(pPageMove);
  43844. if( rc!=SQLITE_OK ){
  43845. return rc;
  43846. }
  43847. /* Move the page currently at pgnoRoot to pgnoMove. */
  43848. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  43849. if( rc!=SQLITE_OK ){
  43850. return rc;
  43851. }
  43852. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  43853. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  43854. rc = SQLITE_CORRUPT_BKPT;
  43855. }
  43856. if( rc!=SQLITE_OK ){
  43857. releasePage(pRoot);
  43858. return rc;
  43859. }
  43860. assert( eType!=PTRMAP_ROOTPAGE );
  43861. assert( eType!=PTRMAP_FREEPAGE );
  43862. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  43863. releasePage(pRoot);
  43864. /* Obtain the page at pgnoRoot */
  43865. if( rc!=SQLITE_OK ){
  43866. return rc;
  43867. }
  43868. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  43869. if( rc!=SQLITE_OK ){
  43870. return rc;
  43871. }
  43872. rc = sqlite3PagerWrite(pRoot->pDbPage);
  43873. if( rc!=SQLITE_OK ){
  43874. releasePage(pRoot);
  43875. return rc;
  43876. }
  43877. }else{
  43878. pRoot = pPageMove;
  43879. }
  43880. /* Update the pointer-map and meta-data with the new root-page number. */
  43881. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  43882. if( rc ){
  43883. releasePage(pRoot);
  43884. return rc;
  43885. }
  43886. /* When the new root page was allocated, page 1 was made writable in
  43887. ** order either to increase the database filesize, or to decrement the
  43888. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  43889. */
  43890. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  43891. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  43892. if( NEVER(rc) ){
  43893. releasePage(pRoot);
  43894. return rc;
  43895. }
  43896. }else{
  43897. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  43898. if( rc ) return rc;
  43899. }
  43900. #endif
  43901. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  43902. if( createTabFlags & BTREE_INTKEY ){
  43903. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  43904. }else{
  43905. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  43906. }
  43907. zeroPage(pRoot, ptfFlags);
  43908. sqlite3PagerUnref(pRoot->pDbPage);
  43909. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  43910. *piTable = (int)pgnoRoot;
  43911. return SQLITE_OK;
  43912. }
  43913. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  43914. int rc;
  43915. sqlite3BtreeEnter(p);
  43916. rc = btreeCreateTable(p, piTable, flags);
  43917. sqlite3BtreeLeave(p);
  43918. return rc;
  43919. }
  43920. /*
  43921. ** Erase the given database page and all its children. Return
  43922. ** the page to the freelist.
  43923. */
  43924. static int clearDatabasePage(
  43925. BtShared *pBt, /* The BTree that contains the table */
  43926. Pgno pgno, /* Page number to clear */
  43927. int freePageFlag, /* Deallocate page if true */
  43928. int *pnChange /* Add number of Cells freed to this counter */
  43929. ){
  43930. MemPage *pPage;
  43931. int rc;
  43932. unsigned char *pCell;
  43933. int i;
  43934. assert( sqlite3_mutex_held(pBt->mutex) );
  43935. if( pgno>btreePagecount(pBt) ){
  43936. return SQLITE_CORRUPT_BKPT;
  43937. }
  43938. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  43939. if( rc ) return rc;
  43940. for(i=0; i<pPage->nCell; i++){
  43941. pCell = findCell(pPage, i);
  43942. if( !pPage->leaf ){
  43943. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  43944. if( rc ) goto cleardatabasepage_out;
  43945. }
  43946. rc = clearCell(pPage, pCell);
  43947. if( rc ) goto cleardatabasepage_out;
  43948. }
  43949. if( !pPage->leaf ){
  43950. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  43951. if( rc ) goto cleardatabasepage_out;
  43952. }else if( pnChange ){
  43953. assert( pPage->intKey );
  43954. *pnChange += pPage->nCell;
  43955. }
  43956. if( freePageFlag ){
  43957. freePage(pPage, &rc);
  43958. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  43959. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  43960. }
  43961. cleardatabasepage_out:
  43962. releasePage(pPage);
  43963. return rc;
  43964. }
  43965. /*
  43966. ** Delete all information from a single table in the database. iTable is
  43967. ** the page number of the root of the table. After this routine returns,
  43968. ** the root page is empty, but still exists.
  43969. **
  43970. ** This routine will fail with SQLITE_LOCKED if there are any open
  43971. ** read cursors on the table. Open write cursors are moved to the
  43972. ** root of the table.
  43973. **
  43974. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  43975. ** integer value pointed to by pnChange is incremented by the number of
  43976. ** entries in the table.
  43977. */
  43978. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  43979. int rc;
  43980. BtShared *pBt = p->pBt;
  43981. sqlite3BtreeEnter(p);
  43982. assert( p->inTrans==TRANS_WRITE );
  43983. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  43984. if( SQLITE_OK==rc ){
  43985. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  43986. ** is the root of a table b-tree - if it is not, the following call is
  43987. ** a no-op). */
  43988. invalidateIncrblobCursors(p, 0, 1);
  43989. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  43990. }
  43991. sqlite3BtreeLeave(p);
  43992. return rc;
  43993. }
  43994. /*
  43995. ** Erase all information in a table and add the root of the table to
  43996. ** the freelist. Except, the root of the principle table (the one on
  43997. ** page 1) is never added to the freelist.
  43998. **
  43999. ** This routine will fail with SQLITE_LOCKED if there are any open
  44000. ** cursors on the table.
  44001. **
  44002. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  44003. ** root page in the database file, then the last root page
  44004. ** in the database file is moved into the slot formerly occupied by
  44005. ** iTable and that last slot formerly occupied by the last root page
  44006. ** is added to the freelist instead of iTable. In this say, all
  44007. ** root pages are kept at the beginning of the database file, which
  44008. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  44009. ** page number that used to be the last root page in the file before
  44010. ** the move. If no page gets moved, *piMoved is set to 0.
  44011. ** The last root page is recorded in meta[3] and the value of
  44012. ** meta[3] is updated by this procedure.
  44013. */
  44014. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  44015. int rc;
  44016. MemPage *pPage = 0;
  44017. BtShared *pBt = p->pBt;
  44018. assert( sqlite3BtreeHoldsMutex(p) );
  44019. assert( p->inTrans==TRANS_WRITE );
  44020. /* It is illegal to drop a table if any cursors are open on the
  44021. ** database. This is because in auto-vacuum mode the backend may
  44022. ** need to move another root-page to fill a gap left by the deleted
  44023. ** root page. If an open cursor was using this page a problem would
  44024. ** occur.
  44025. **
  44026. ** This error is caught long before control reaches this point.
  44027. */
  44028. if( NEVER(pBt->pCursor) ){
  44029. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  44030. return SQLITE_LOCKED_SHAREDCACHE;
  44031. }
  44032. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  44033. if( rc ) return rc;
  44034. rc = sqlite3BtreeClearTable(p, iTable, 0);
  44035. if( rc ){
  44036. releasePage(pPage);
  44037. return rc;
  44038. }
  44039. *piMoved = 0;
  44040. if( iTable>1 ){
  44041. #ifdef SQLITE_OMIT_AUTOVACUUM
  44042. freePage(pPage, &rc);
  44043. releasePage(pPage);
  44044. #else
  44045. if( pBt->autoVacuum ){
  44046. Pgno maxRootPgno;
  44047. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  44048. if( iTable==maxRootPgno ){
  44049. /* If the table being dropped is the table with the largest root-page
  44050. ** number in the database, put the root page on the free list.
  44051. */
  44052. freePage(pPage, &rc);
  44053. releasePage(pPage);
  44054. if( rc!=SQLITE_OK ){
  44055. return rc;
  44056. }
  44057. }else{
  44058. /* The table being dropped does not have the largest root-page
  44059. ** number in the database. So move the page that does into the
  44060. ** gap left by the deleted root-page.
  44061. */
  44062. MemPage *pMove;
  44063. releasePage(pPage);
  44064. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  44065. if( rc!=SQLITE_OK ){
  44066. return rc;
  44067. }
  44068. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  44069. releasePage(pMove);
  44070. if( rc!=SQLITE_OK ){
  44071. return rc;
  44072. }
  44073. pMove = 0;
  44074. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  44075. freePage(pMove, &rc);
  44076. releasePage(pMove);
  44077. if( rc!=SQLITE_OK ){
  44078. return rc;
  44079. }
  44080. *piMoved = maxRootPgno;
  44081. }
  44082. /* Set the new 'max-root-page' value in the database header. This
  44083. ** is the old value less one, less one more if that happens to
  44084. ** be a root-page number, less one again if that is the
  44085. ** PENDING_BYTE_PAGE.
  44086. */
  44087. maxRootPgno--;
  44088. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  44089. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  44090. maxRootPgno--;
  44091. }
  44092. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  44093. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  44094. }else{
  44095. freePage(pPage, &rc);
  44096. releasePage(pPage);
  44097. }
  44098. #endif
  44099. }else{
  44100. /* If sqlite3BtreeDropTable was called on page 1.
  44101. ** This really never should happen except in a corrupt
  44102. ** database.
  44103. */
  44104. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  44105. releasePage(pPage);
  44106. }
  44107. return rc;
  44108. }
  44109. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  44110. int rc;
  44111. sqlite3BtreeEnter(p);
  44112. rc = btreeDropTable(p, iTable, piMoved);
  44113. sqlite3BtreeLeave(p);
  44114. return rc;
  44115. }
  44116. /*
  44117. ** This function may only be called if the b-tree connection already
  44118. ** has a read or write transaction open on the database.
  44119. **
  44120. ** Read the meta-information out of a database file. Meta[0]
  44121. ** is the number of free pages currently in the database. Meta[1]
  44122. ** through meta[15] are available for use by higher layers. Meta[0]
  44123. ** is read-only, the others are read/write.
  44124. **
  44125. ** The schema layer numbers meta values differently. At the schema
  44126. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  44127. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  44128. */
  44129. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  44130. BtShared *pBt = p->pBt;
  44131. sqlite3BtreeEnter(p);
  44132. assert( p->inTrans>TRANS_NONE );
  44133. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  44134. assert( pBt->pPage1 );
  44135. assert( idx>=0 && idx<=15 );
  44136. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  44137. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  44138. ** database, mark the database as read-only. */
  44139. #ifdef SQLITE_OMIT_AUTOVACUUM
  44140. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  44141. pBt->btsFlags |= BTS_READ_ONLY;
  44142. }
  44143. #endif
  44144. sqlite3BtreeLeave(p);
  44145. }
  44146. /*
  44147. ** Write meta-information back into the database. Meta[0] is
  44148. ** read-only and may not be written.
  44149. */
  44150. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  44151. BtShared *pBt = p->pBt;
  44152. unsigned char *pP1;
  44153. int rc;
  44154. assert( idx>=1 && idx<=15 );
  44155. sqlite3BtreeEnter(p);
  44156. assert( p->inTrans==TRANS_WRITE );
  44157. assert( pBt->pPage1!=0 );
  44158. pP1 = pBt->pPage1->aData;
  44159. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  44160. if( rc==SQLITE_OK ){
  44161. put4byte(&pP1[36 + idx*4], iMeta);
  44162. #ifndef SQLITE_OMIT_AUTOVACUUM
  44163. if( idx==BTREE_INCR_VACUUM ){
  44164. assert( pBt->autoVacuum || iMeta==0 );
  44165. assert( iMeta==0 || iMeta==1 );
  44166. pBt->incrVacuum = (u8)iMeta;
  44167. }
  44168. #endif
  44169. }
  44170. sqlite3BtreeLeave(p);
  44171. return rc;
  44172. }
  44173. #ifndef SQLITE_OMIT_BTREECOUNT
  44174. /*
  44175. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  44176. ** number of entries in the b-tree and write the result to *pnEntry.
  44177. **
  44178. ** SQLITE_OK is returned if the operation is successfully executed.
  44179. ** Otherwise, if an error is encountered (i.e. an IO error or database
  44180. ** corruption) an SQLite error code is returned.
  44181. */
  44182. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  44183. i64 nEntry = 0; /* Value to return in *pnEntry */
  44184. int rc; /* Return code */
  44185. if( pCur->pgnoRoot==0 ){
  44186. *pnEntry = 0;
  44187. return SQLITE_OK;
  44188. }
  44189. rc = moveToRoot(pCur);
  44190. /* Unless an error occurs, the following loop runs one iteration for each
  44191. ** page in the B-Tree structure (not including overflow pages).
  44192. */
  44193. while( rc==SQLITE_OK ){
  44194. int iIdx; /* Index of child node in parent */
  44195. MemPage *pPage; /* Current page of the b-tree */
  44196. /* If this is a leaf page or the tree is not an int-key tree, then
  44197. ** this page contains countable entries. Increment the entry counter
  44198. ** accordingly.
  44199. */
  44200. pPage = pCur->apPage[pCur->iPage];
  44201. if( pPage->leaf || !pPage->intKey ){
  44202. nEntry += pPage->nCell;
  44203. }
  44204. /* pPage is a leaf node. This loop navigates the cursor so that it
  44205. ** points to the first interior cell that it points to the parent of
  44206. ** the next page in the tree that has not yet been visited. The
  44207. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  44208. ** of the page, or to the number of cells in the page if the next page
  44209. ** to visit is the right-child of its parent.
  44210. **
  44211. ** If all pages in the tree have been visited, return SQLITE_OK to the
  44212. ** caller.
  44213. */
  44214. if( pPage->leaf ){
  44215. do {
  44216. if( pCur->iPage==0 ){
  44217. /* All pages of the b-tree have been visited. Return successfully. */
  44218. *pnEntry = nEntry;
  44219. return SQLITE_OK;
  44220. }
  44221. moveToParent(pCur);
  44222. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  44223. pCur->aiIdx[pCur->iPage]++;
  44224. pPage = pCur->apPage[pCur->iPage];
  44225. }
  44226. /* Descend to the child node of the cell that the cursor currently
  44227. ** points at. This is the right-child if (iIdx==pPage->nCell).
  44228. */
  44229. iIdx = pCur->aiIdx[pCur->iPage];
  44230. if( iIdx==pPage->nCell ){
  44231. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  44232. }else{
  44233. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  44234. }
  44235. }
  44236. /* An error has occurred. Return an error code. */
  44237. return rc;
  44238. }
  44239. #endif
  44240. /*
  44241. ** Return the pager associated with a BTree. This routine is used for
  44242. ** testing and debugging only.
  44243. */
  44244. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  44245. return p->pBt->pPager;
  44246. }
  44247. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44248. /*
  44249. ** Append a message to the error message string.
  44250. */
  44251. static void checkAppendMsg(
  44252. IntegrityCk *pCheck,
  44253. char *zMsg1,
  44254. const char *zFormat,
  44255. ...
  44256. ){
  44257. va_list ap;
  44258. if( !pCheck->mxErr ) return;
  44259. pCheck->mxErr--;
  44260. pCheck->nErr++;
  44261. va_start(ap, zFormat);
  44262. if( pCheck->errMsg.nChar ){
  44263. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  44264. }
  44265. if( zMsg1 ){
  44266. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  44267. }
  44268. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  44269. va_end(ap);
  44270. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  44271. pCheck->mallocFailed = 1;
  44272. }
  44273. }
  44274. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44275. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44276. /*
  44277. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  44278. ** corresponds to page iPg is already set.
  44279. */
  44280. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  44281. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  44282. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  44283. }
  44284. /*
  44285. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  44286. */
  44287. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  44288. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  44289. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  44290. }
  44291. /*
  44292. ** Add 1 to the reference count for page iPage. If this is the second
  44293. ** reference to the page, add an error message to pCheck->zErrMsg.
  44294. ** Return 1 if there are 2 ore more references to the page and 0 if
  44295. ** if this is the first reference to the page.
  44296. **
  44297. ** Also check that the page number is in bounds.
  44298. */
  44299. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  44300. if( iPage==0 ) return 1;
  44301. if( iPage>pCheck->nPage ){
  44302. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  44303. return 1;
  44304. }
  44305. if( getPageReferenced(pCheck, iPage) ){
  44306. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  44307. return 1;
  44308. }
  44309. setPageReferenced(pCheck, iPage);
  44310. return 0;
  44311. }
  44312. #ifndef SQLITE_OMIT_AUTOVACUUM
  44313. /*
  44314. ** Check that the entry in the pointer-map for page iChild maps to
  44315. ** page iParent, pointer type ptrType. If not, append an error message
  44316. ** to pCheck.
  44317. */
  44318. static void checkPtrmap(
  44319. IntegrityCk *pCheck, /* Integrity check context */
  44320. Pgno iChild, /* Child page number */
  44321. u8 eType, /* Expected pointer map type */
  44322. Pgno iParent, /* Expected pointer map parent page number */
  44323. char *zContext /* Context description (used for error msg) */
  44324. ){
  44325. int rc;
  44326. u8 ePtrmapType;
  44327. Pgno iPtrmapParent;
  44328. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  44329. if( rc!=SQLITE_OK ){
  44330. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  44331. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  44332. return;
  44333. }
  44334. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  44335. checkAppendMsg(pCheck, zContext,
  44336. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  44337. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  44338. }
  44339. }
  44340. #endif
  44341. /*
  44342. ** Check the integrity of the freelist or of an overflow page list.
  44343. ** Verify that the number of pages on the list is N.
  44344. */
  44345. static void checkList(
  44346. IntegrityCk *pCheck, /* Integrity checking context */
  44347. int isFreeList, /* True for a freelist. False for overflow page list */
  44348. int iPage, /* Page number for first page in the list */
  44349. int N, /* Expected number of pages in the list */
  44350. char *zContext /* Context for error messages */
  44351. ){
  44352. int i;
  44353. int expected = N;
  44354. int iFirst = iPage;
  44355. while( N-- > 0 && pCheck->mxErr ){
  44356. DbPage *pOvflPage;
  44357. unsigned char *pOvflData;
  44358. if( iPage<1 ){
  44359. checkAppendMsg(pCheck, zContext,
  44360. "%d of %d pages missing from overflow list starting at %d",
  44361. N+1, expected, iFirst);
  44362. break;
  44363. }
  44364. if( checkRef(pCheck, iPage, zContext) ) break;
  44365. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  44366. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  44367. break;
  44368. }
  44369. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  44370. if( isFreeList ){
  44371. int n = get4byte(&pOvflData[4]);
  44372. #ifndef SQLITE_OMIT_AUTOVACUUM
  44373. if( pCheck->pBt->autoVacuum ){
  44374. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  44375. }
  44376. #endif
  44377. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  44378. checkAppendMsg(pCheck, zContext,
  44379. "freelist leaf count too big on page %d", iPage);
  44380. N--;
  44381. }else{
  44382. for(i=0; i<n; i++){
  44383. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  44384. #ifndef SQLITE_OMIT_AUTOVACUUM
  44385. if( pCheck->pBt->autoVacuum ){
  44386. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  44387. }
  44388. #endif
  44389. checkRef(pCheck, iFreePage, zContext);
  44390. }
  44391. N -= n;
  44392. }
  44393. }
  44394. #ifndef SQLITE_OMIT_AUTOVACUUM
  44395. else{
  44396. /* If this database supports auto-vacuum and iPage is not the last
  44397. ** page in this overflow list, check that the pointer-map entry for
  44398. ** the following page matches iPage.
  44399. */
  44400. if( pCheck->pBt->autoVacuum && N>0 ){
  44401. i = get4byte(pOvflData);
  44402. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  44403. }
  44404. }
  44405. #endif
  44406. iPage = get4byte(pOvflData);
  44407. sqlite3PagerUnref(pOvflPage);
  44408. }
  44409. }
  44410. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44411. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44412. /*
  44413. ** Do various sanity checks on a single page of a tree. Return
  44414. ** the tree depth. Root pages return 0. Parents of root pages
  44415. ** return 1, and so forth.
  44416. **
  44417. ** These checks are done:
  44418. **
  44419. ** 1. Make sure that cells and freeblocks do not overlap
  44420. ** but combine to completely cover the page.
  44421. ** NO 2. Make sure cell keys are in order.
  44422. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  44423. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  44424. ** 5. Check the integrity of overflow pages.
  44425. ** 6. Recursively call checkTreePage on all children.
  44426. ** 7. Verify that the depth of all children is the same.
  44427. ** 8. Make sure this page is at least 33% full or else it is
  44428. ** the root of the tree.
  44429. */
  44430. static int checkTreePage(
  44431. IntegrityCk *pCheck, /* Context for the sanity check */
  44432. int iPage, /* Page number of the page to check */
  44433. char *zParentContext, /* Parent context */
  44434. i64 *pnParentMinKey,
  44435. i64 *pnParentMaxKey
  44436. ){
  44437. MemPage *pPage;
  44438. int i, rc, depth, d2, pgno, cnt;
  44439. int hdr, cellStart;
  44440. int nCell;
  44441. u8 *data;
  44442. BtShared *pBt;
  44443. int usableSize;
  44444. char zContext[100];
  44445. char *hit = 0;
  44446. i64 nMinKey = 0;
  44447. i64 nMaxKey = 0;
  44448. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  44449. /* Check that the page exists
  44450. */
  44451. pBt = pCheck->pBt;
  44452. usableSize = pBt->usableSize;
  44453. if( iPage==0 ) return 0;
  44454. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  44455. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  44456. checkAppendMsg(pCheck, zContext,
  44457. "unable to get the page. error code=%d", rc);
  44458. return 0;
  44459. }
  44460. /* Clear MemPage.isInit to make sure the corruption detection code in
  44461. ** btreeInitPage() is executed. */
  44462. pPage->isInit = 0;
  44463. if( (rc = btreeInitPage(pPage))!=0 ){
  44464. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  44465. checkAppendMsg(pCheck, zContext,
  44466. "btreeInitPage() returns error code %d", rc);
  44467. releasePage(pPage);
  44468. return 0;
  44469. }
  44470. /* Check out all the cells.
  44471. */
  44472. depth = 0;
  44473. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  44474. u8 *pCell;
  44475. u32 sz;
  44476. CellInfo info;
  44477. /* Check payload overflow pages
  44478. */
  44479. sqlite3_snprintf(sizeof(zContext), zContext,
  44480. "On tree page %d cell %d: ", iPage, i);
  44481. pCell = findCell(pPage,i);
  44482. btreeParseCellPtr(pPage, pCell, &info);
  44483. sz = info.nData;
  44484. if( !pPage->intKey ) sz += (int)info.nKey;
  44485. /* For intKey pages, check that the keys are in order.
  44486. */
  44487. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  44488. else{
  44489. if( info.nKey <= nMaxKey ){
  44490. checkAppendMsg(pCheck, zContext,
  44491. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  44492. }
  44493. nMaxKey = info.nKey;
  44494. }
  44495. assert( sz==info.nPayload );
  44496. if( (sz>info.nLocal)
  44497. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  44498. ){
  44499. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  44500. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  44501. #ifndef SQLITE_OMIT_AUTOVACUUM
  44502. if( pBt->autoVacuum ){
  44503. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  44504. }
  44505. #endif
  44506. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  44507. }
  44508. /* Check sanity of left child page.
  44509. */
  44510. if( !pPage->leaf ){
  44511. pgno = get4byte(pCell);
  44512. #ifndef SQLITE_OMIT_AUTOVACUUM
  44513. if( pBt->autoVacuum ){
  44514. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  44515. }
  44516. #endif
  44517. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  44518. if( i>0 && d2!=depth ){
  44519. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  44520. }
  44521. depth = d2;
  44522. }
  44523. }
  44524. if( !pPage->leaf ){
  44525. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  44526. sqlite3_snprintf(sizeof(zContext), zContext,
  44527. "On page %d at right child: ", iPage);
  44528. #ifndef SQLITE_OMIT_AUTOVACUUM
  44529. if( pBt->autoVacuum ){
  44530. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  44531. }
  44532. #endif
  44533. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  44534. }
  44535. /* For intKey leaf pages, check that the min/max keys are in order
  44536. ** with any left/parent/right pages.
  44537. */
  44538. if( pPage->leaf && pPage->intKey ){
  44539. /* if we are a left child page */
  44540. if( pnParentMinKey ){
  44541. /* if we are the left most child page */
  44542. if( !pnParentMaxKey ){
  44543. if( nMaxKey > *pnParentMinKey ){
  44544. checkAppendMsg(pCheck, zContext,
  44545. "Rowid %lld out of order (max larger than parent min of %lld)",
  44546. nMaxKey, *pnParentMinKey);
  44547. }
  44548. }else{
  44549. if( nMinKey <= *pnParentMinKey ){
  44550. checkAppendMsg(pCheck, zContext,
  44551. "Rowid %lld out of order (min less than parent min of %lld)",
  44552. nMinKey, *pnParentMinKey);
  44553. }
  44554. if( nMaxKey > *pnParentMaxKey ){
  44555. checkAppendMsg(pCheck, zContext,
  44556. "Rowid %lld out of order (max larger than parent max of %lld)",
  44557. nMaxKey, *pnParentMaxKey);
  44558. }
  44559. *pnParentMinKey = nMaxKey;
  44560. }
  44561. /* else if we're a right child page */
  44562. } else if( pnParentMaxKey ){
  44563. if( nMinKey <= *pnParentMaxKey ){
  44564. checkAppendMsg(pCheck, zContext,
  44565. "Rowid %lld out of order (min less than parent max of %lld)",
  44566. nMinKey, *pnParentMaxKey);
  44567. }
  44568. }
  44569. }
  44570. /* Check for complete coverage of the page
  44571. */
  44572. data = pPage->aData;
  44573. hdr = pPage->hdrOffset;
  44574. hit = sqlite3PageMalloc( pBt->pageSize );
  44575. if( hit==0 ){
  44576. pCheck->mallocFailed = 1;
  44577. }else{
  44578. int contentOffset = get2byteNotZero(&data[hdr+5]);
  44579. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  44580. memset(hit+contentOffset, 0, usableSize-contentOffset);
  44581. memset(hit, 1, contentOffset);
  44582. nCell = get2byte(&data[hdr+3]);
  44583. cellStart = hdr + 12 - 4*pPage->leaf;
  44584. for(i=0; i<nCell; i++){
  44585. int pc = get2byte(&data[cellStart+i*2]);
  44586. u32 size = 65536;
  44587. int j;
  44588. if( pc<=usableSize-4 ){
  44589. size = cellSizePtr(pPage, &data[pc]);
  44590. }
  44591. if( (int)(pc+size-1)>=usableSize ){
  44592. checkAppendMsg(pCheck, 0,
  44593. "Corruption detected in cell %d on page %d",i,iPage);
  44594. }else{
  44595. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  44596. }
  44597. }
  44598. i = get2byte(&data[hdr+1]);
  44599. while( i>0 ){
  44600. int size, j;
  44601. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  44602. size = get2byte(&data[i+2]);
  44603. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  44604. for(j=i+size-1; j>=i; j--) hit[j]++;
  44605. j = get2byte(&data[i]);
  44606. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  44607. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  44608. i = j;
  44609. }
  44610. for(i=cnt=0; i<usableSize; i++){
  44611. if( hit[i]==0 ){
  44612. cnt++;
  44613. }else if( hit[i]>1 ){
  44614. checkAppendMsg(pCheck, 0,
  44615. "Multiple uses for byte %d of page %d", i, iPage);
  44616. break;
  44617. }
  44618. }
  44619. if( cnt!=data[hdr+7] ){
  44620. checkAppendMsg(pCheck, 0,
  44621. "Fragmentation of %d bytes reported as %d on page %d",
  44622. cnt, data[hdr+7], iPage);
  44623. }
  44624. }
  44625. sqlite3PageFree(hit);
  44626. releasePage(pPage);
  44627. return depth+1;
  44628. }
  44629. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44630. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44631. /*
  44632. ** This routine does a complete check of the given BTree file. aRoot[] is
  44633. ** an array of pages numbers were each page number is the root page of
  44634. ** a table. nRoot is the number of entries in aRoot.
  44635. **
  44636. ** A read-only or read-write transaction must be opened before calling
  44637. ** this function.
  44638. **
  44639. ** Write the number of error seen in *pnErr. Except for some memory
  44640. ** allocation errors, an error message held in memory obtained from
  44641. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  44642. ** returned. If a memory allocation error occurs, NULL is returned.
  44643. */
  44644. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  44645. Btree *p, /* The btree to be checked */
  44646. int *aRoot, /* An array of root pages numbers for individual trees */
  44647. int nRoot, /* Number of entries in aRoot[] */
  44648. int mxErr, /* Stop reporting errors after this many */
  44649. int *pnErr /* Write number of errors seen to this variable */
  44650. ){
  44651. Pgno i;
  44652. int nRef;
  44653. IntegrityCk sCheck;
  44654. BtShared *pBt = p->pBt;
  44655. char zErr[100];
  44656. sqlite3BtreeEnter(p);
  44657. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  44658. nRef = sqlite3PagerRefcount(pBt->pPager);
  44659. sCheck.pBt = pBt;
  44660. sCheck.pPager = pBt->pPager;
  44661. sCheck.nPage = btreePagecount(sCheck.pBt);
  44662. sCheck.mxErr = mxErr;
  44663. sCheck.nErr = 0;
  44664. sCheck.mallocFailed = 0;
  44665. *pnErr = 0;
  44666. if( sCheck.nPage==0 ){
  44667. sqlite3BtreeLeave(p);
  44668. return 0;
  44669. }
  44670. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  44671. if( !sCheck.aPgRef ){
  44672. *pnErr = 1;
  44673. sqlite3BtreeLeave(p);
  44674. return 0;
  44675. }
  44676. i = PENDING_BYTE_PAGE(pBt);
  44677. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  44678. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  44679. sCheck.errMsg.useMalloc = 2;
  44680. /* Check the integrity of the freelist
  44681. */
  44682. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  44683. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  44684. /* Check all the tables.
  44685. */
  44686. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  44687. if( aRoot[i]==0 ) continue;
  44688. #ifndef SQLITE_OMIT_AUTOVACUUM
  44689. if( pBt->autoVacuum && aRoot[i]>1 ){
  44690. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  44691. }
  44692. #endif
  44693. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  44694. }
  44695. /* Make sure every page in the file is referenced
  44696. */
  44697. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  44698. #ifdef SQLITE_OMIT_AUTOVACUUM
  44699. if( getPageReferenced(&sCheck, i)==0 ){
  44700. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  44701. }
  44702. #else
  44703. /* If the database supports auto-vacuum, make sure no tables contain
  44704. ** references to pointer-map pages.
  44705. */
  44706. if( getPageReferenced(&sCheck, i)==0 &&
  44707. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  44708. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  44709. }
  44710. if( getPageReferenced(&sCheck, i)!=0 &&
  44711. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  44712. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  44713. }
  44714. #endif
  44715. }
  44716. /* Make sure this analysis did not leave any unref() pages.
  44717. ** This is an internal consistency check; an integrity check
  44718. ** of the integrity check.
  44719. */
  44720. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  44721. checkAppendMsg(&sCheck, 0,
  44722. "Outstanding page count goes from %d to %d during this analysis",
  44723. nRef, sqlite3PagerRefcount(pBt->pPager)
  44724. );
  44725. }
  44726. /* Clean up and report errors.
  44727. */
  44728. sqlite3BtreeLeave(p);
  44729. sqlite3_free(sCheck.aPgRef);
  44730. if( sCheck.mallocFailed ){
  44731. sqlite3StrAccumReset(&sCheck.errMsg);
  44732. *pnErr = sCheck.nErr+1;
  44733. return 0;
  44734. }
  44735. *pnErr = sCheck.nErr;
  44736. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  44737. return sqlite3StrAccumFinish(&sCheck.errMsg);
  44738. }
  44739. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44740. /*
  44741. ** Return the full pathname of the underlying database file. Return
  44742. ** an empty string if the database is in-memory or a TEMP database.
  44743. **
  44744. ** The pager filename is invariant as long as the pager is
  44745. ** open so it is safe to access without the BtShared mutex.
  44746. */
  44747. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  44748. assert( p->pBt->pPager!=0 );
  44749. return sqlite3PagerFilename(p->pBt->pPager, 1);
  44750. }
  44751. /*
  44752. ** Return the pathname of the journal file for this database. The return
  44753. ** value of this routine is the same regardless of whether the journal file
  44754. ** has been created or not.
  44755. **
  44756. ** The pager journal filename is invariant as long as the pager is
  44757. ** open so it is safe to access without the BtShared mutex.
  44758. */
  44759. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  44760. assert( p->pBt->pPager!=0 );
  44761. return sqlite3PagerJournalname(p->pBt->pPager);
  44762. }
  44763. /*
  44764. ** Return non-zero if a transaction is active.
  44765. */
  44766. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  44767. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  44768. return (p && (p->inTrans==TRANS_WRITE));
  44769. }
  44770. #ifndef SQLITE_OMIT_WAL
  44771. /*
  44772. ** Run a checkpoint on the Btree passed as the first argument.
  44773. **
  44774. ** Return SQLITE_LOCKED if this or any other connection has an open
  44775. ** transaction on the shared-cache the argument Btree is connected to.
  44776. **
  44777. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  44778. */
  44779. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  44780. int rc = SQLITE_OK;
  44781. if( p ){
  44782. BtShared *pBt = p->pBt;
  44783. sqlite3BtreeEnter(p);
  44784. if( pBt->inTransaction!=TRANS_NONE ){
  44785. rc = SQLITE_LOCKED;
  44786. }else{
  44787. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  44788. }
  44789. sqlite3BtreeLeave(p);
  44790. }
  44791. return rc;
  44792. }
  44793. #endif
  44794. /*
  44795. ** Return non-zero if a read (or write) transaction is active.
  44796. */
  44797. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  44798. assert( p );
  44799. assert( sqlite3_mutex_held(p->db->mutex) );
  44800. return p->inTrans!=TRANS_NONE;
  44801. }
  44802. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  44803. assert( p );
  44804. assert( sqlite3_mutex_held(p->db->mutex) );
  44805. return p->nBackup!=0;
  44806. }
  44807. /*
  44808. ** This function returns a pointer to a blob of memory associated with
  44809. ** a single shared-btree. The memory is used by client code for its own
  44810. ** purposes (for example, to store a high-level schema associated with
  44811. ** the shared-btree). The btree layer manages reference counting issues.
  44812. **
  44813. ** The first time this is called on a shared-btree, nBytes bytes of memory
  44814. ** are allocated, zeroed, and returned to the caller. For each subsequent
  44815. ** call the nBytes parameter is ignored and a pointer to the same blob
  44816. ** of memory returned.
  44817. **
  44818. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  44819. ** allocated, a null pointer is returned. If the blob has already been
  44820. ** allocated, it is returned as normal.
  44821. **
  44822. ** Just before the shared-btree is closed, the function passed as the
  44823. ** xFree argument when the memory allocation was made is invoked on the
  44824. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  44825. ** on the memory, the btree layer does that.
  44826. */
  44827. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  44828. BtShared *pBt = p->pBt;
  44829. sqlite3BtreeEnter(p);
  44830. if( !pBt->pSchema && nBytes ){
  44831. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  44832. pBt->xFreeSchema = xFree;
  44833. }
  44834. sqlite3BtreeLeave(p);
  44835. return pBt->pSchema;
  44836. }
  44837. /*
  44838. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  44839. ** btree as the argument handle holds an exclusive lock on the
  44840. ** sqlite_master table. Otherwise SQLITE_OK.
  44841. */
  44842. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  44843. int rc;
  44844. assert( sqlite3_mutex_held(p->db->mutex) );
  44845. sqlite3BtreeEnter(p);
  44846. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  44847. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  44848. sqlite3BtreeLeave(p);
  44849. return rc;
  44850. }
  44851. #ifndef SQLITE_OMIT_SHARED_CACHE
  44852. /*
  44853. ** Obtain a lock on the table whose root page is iTab. The
  44854. ** lock is a write lock if isWritelock is true or a read lock
  44855. ** if it is false.
  44856. */
  44857. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  44858. int rc = SQLITE_OK;
  44859. assert( p->inTrans!=TRANS_NONE );
  44860. if( p->sharable ){
  44861. u8 lockType = READ_LOCK + isWriteLock;
  44862. assert( READ_LOCK+1==WRITE_LOCK );
  44863. assert( isWriteLock==0 || isWriteLock==1 );
  44864. sqlite3BtreeEnter(p);
  44865. rc = querySharedCacheTableLock(p, iTab, lockType);
  44866. if( rc==SQLITE_OK ){
  44867. rc = setSharedCacheTableLock(p, iTab, lockType);
  44868. }
  44869. sqlite3BtreeLeave(p);
  44870. }
  44871. return rc;
  44872. }
  44873. #endif
  44874. #ifndef SQLITE_OMIT_INCRBLOB
  44875. /*
  44876. ** Argument pCsr must be a cursor opened for writing on an
  44877. ** INTKEY table currently pointing at a valid table entry.
  44878. ** This function modifies the data stored as part of that entry.
  44879. **
  44880. ** Only the data content may only be modified, it is not possible to
  44881. ** change the length of the data stored. If this function is called with
  44882. ** parameters that attempt to write past the end of the existing data,
  44883. ** no modifications are made and SQLITE_CORRUPT is returned.
  44884. */
  44885. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  44886. int rc;
  44887. assert( cursorHoldsMutex(pCsr) );
  44888. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  44889. assert( pCsr->isIncrblobHandle );
  44890. rc = restoreCursorPosition(pCsr);
  44891. if( rc!=SQLITE_OK ){
  44892. return rc;
  44893. }
  44894. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  44895. if( pCsr->eState!=CURSOR_VALID ){
  44896. return SQLITE_ABORT;
  44897. }
  44898. /* Save the positions of all other cursors open on this table. This is
  44899. ** required in case any of them are holding references to an xFetch
  44900. ** version of the b-tree page modified by the accessPayload call below.
  44901. **
  44902. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  44903. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  44904. ** saveAllCursors can only return SQLITE_OK.
  44905. */
  44906. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  44907. assert( rc==SQLITE_OK );
  44908. /* Check some assumptions:
  44909. ** (a) the cursor is open for writing,
  44910. ** (b) there is a read/write transaction open,
  44911. ** (c) the connection holds a write-lock on the table (if required),
  44912. ** (d) there are no conflicting read-locks, and
  44913. ** (e) the cursor points at a valid row of an intKey table.
  44914. */
  44915. if( !pCsr->wrFlag ){
  44916. return SQLITE_READONLY;
  44917. }
  44918. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  44919. && pCsr->pBt->inTransaction==TRANS_WRITE );
  44920. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  44921. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  44922. assert( pCsr->apPage[pCsr->iPage]->intKey );
  44923. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  44924. }
  44925. /*
  44926. ** Set a flag on this cursor to cache the locations of pages from the
  44927. ** overflow list for the current row. This is used by cursors opened
  44928. ** for incremental blob IO only.
  44929. **
  44930. ** This function sets a flag only. The actual page location cache
  44931. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  44932. ** accessPayload() (the worker function for sqlite3BtreeData() and
  44933. ** sqlite3BtreePutData()).
  44934. */
  44935. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  44936. assert( cursorHoldsMutex(pCur) );
  44937. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  44938. invalidateOverflowCache(pCur);
  44939. pCur->isIncrblobHandle = 1;
  44940. }
  44941. #endif
  44942. /*
  44943. ** Set both the "read version" (single byte at byte offset 18) and
  44944. ** "write version" (single byte at byte offset 19) fields in the database
  44945. ** header to iVersion.
  44946. */
  44947. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  44948. BtShared *pBt = pBtree->pBt;
  44949. int rc; /* Return code */
  44950. assert( iVersion==1 || iVersion==2 );
  44951. /* If setting the version fields to 1, do not automatically open the
  44952. ** WAL connection, even if the version fields are currently set to 2.
  44953. */
  44954. pBt->btsFlags &= ~BTS_NO_WAL;
  44955. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  44956. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  44957. if( rc==SQLITE_OK ){
  44958. u8 *aData = pBt->pPage1->aData;
  44959. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  44960. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  44961. if( rc==SQLITE_OK ){
  44962. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  44963. if( rc==SQLITE_OK ){
  44964. aData[18] = (u8)iVersion;
  44965. aData[19] = (u8)iVersion;
  44966. }
  44967. }
  44968. }
  44969. }
  44970. pBt->btsFlags &= ~BTS_NO_WAL;
  44971. return rc;
  44972. }
  44973. /*
  44974. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  44975. ** values are 0 and BTREE_BULKLOAD.
  44976. */
  44977. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  44978. assert( mask==BTREE_BULKLOAD || mask==0 );
  44979. pCsr->hints = mask;
  44980. }
  44981. /************** End of btree.c ***********************************************/
  44982. /************** Begin file backup.c ******************************************/
  44983. /*
  44984. ** 2009 January 28
  44985. **
  44986. ** The author disclaims copyright to this source code. In place of
  44987. ** a legal notice, here is a blessing:
  44988. **
  44989. ** May you do good and not evil.
  44990. ** May you find forgiveness for yourself and forgive others.
  44991. ** May you share freely, never taking more than you give.
  44992. **
  44993. *************************************************************************
  44994. ** This file contains the implementation of the sqlite3_backup_XXX()
  44995. ** API functions and the related features.
  44996. */
  44997. /*
  44998. ** Structure allocated for each backup operation.
  44999. */
  45000. struct sqlite3_backup {
  45001. sqlite3* pDestDb; /* Destination database handle */
  45002. Btree *pDest; /* Destination b-tree file */
  45003. u32 iDestSchema; /* Original schema cookie in destination */
  45004. int bDestLocked; /* True once a write-transaction is open on pDest */
  45005. Pgno iNext; /* Page number of the next source page to copy */
  45006. sqlite3* pSrcDb; /* Source database handle */
  45007. Btree *pSrc; /* Source b-tree file */
  45008. int rc; /* Backup process error code */
  45009. /* These two variables are set by every call to backup_step(). They are
  45010. ** read by calls to backup_remaining() and backup_pagecount().
  45011. */
  45012. Pgno nRemaining; /* Number of pages left to copy */
  45013. Pgno nPagecount; /* Total number of pages to copy */
  45014. int isAttached; /* True once backup has been registered with pager */
  45015. sqlite3_backup *pNext; /* Next backup associated with source pager */
  45016. };
  45017. /*
  45018. ** THREAD SAFETY NOTES:
  45019. **
  45020. ** Once it has been created using backup_init(), a single sqlite3_backup
  45021. ** structure may be accessed via two groups of thread-safe entry points:
  45022. **
  45023. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  45024. ** backup_finish(). Both these functions obtain the source database
  45025. ** handle mutex and the mutex associated with the source BtShared
  45026. ** structure, in that order.
  45027. **
  45028. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  45029. ** invoked by the pager layer to report various state changes in
  45030. ** the page cache associated with the source database. The mutex
  45031. ** associated with the source database BtShared structure will always
  45032. ** be held when either of these functions are invoked.
  45033. **
  45034. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  45035. ** backup_pagecount() are not thread-safe functions. If they are called
  45036. ** while some other thread is calling backup_step() or backup_finish(),
  45037. ** the values returned may be invalid. There is no way for a call to
  45038. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  45039. ** or backup_pagecount().
  45040. **
  45041. ** Depending on the SQLite configuration, the database handles and/or
  45042. ** the Btree objects may have their own mutexes that require locking.
  45043. ** Non-sharable Btrees (in-memory databases for example), do not have
  45044. ** associated mutexes.
  45045. */
  45046. /*
  45047. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  45048. ** in connection handle pDb. If such a database cannot be found, return
  45049. ** a NULL pointer and write an error message to pErrorDb.
  45050. **
  45051. ** If the "temp" database is requested, it may need to be opened by this
  45052. ** function. If an error occurs while doing so, return 0 and write an
  45053. ** error message to pErrorDb.
  45054. */
  45055. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  45056. int i = sqlite3FindDbName(pDb, zDb);
  45057. if( i==1 ){
  45058. Parse *pParse;
  45059. int rc = 0;
  45060. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  45061. if( pParse==0 ){
  45062. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  45063. rc = SQLITE_NOMEM;
  45064. }else{
  45065. pParse->db = pDb;
  45066. if( sqlite3OpenTempDatabase(pParse) ){
  45067. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  45068. rc = SQLITE_ERROR;
  45069. }
  45070. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  45071. sqlite3StackFree(pErrorDb, pParse);
  45072. }
  45073. if( rc ){
  45074. return 0;
  45075. }
  45076. }
  45077. if( i<0 ){
  45078. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  45079. return 0;
  45080. }
  45081. return pDb->aDb[i].pBt;
  45082. }
  45083. /*
  45084. ** Attempt to set the page size of the destination to match the page size
  45085. ** of the source.
  45086. */
  45087. static int setDestPgsz(sqlite3_backup *p){
  45088. int rc;
  45089. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  45090. return rc;
  45091. }
  45092. /*
  45093. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  45094. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  45095. ** a pointer to the new sqlite3_backup object.
  45096. **
  45097. ** If an error occurs, NULL is returned and an error code and error message
  45098. ** stored in database handle pDestDb.
  45099. */
  45100. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  45101. sqlite3* pDestDb, /* Database to write to */
  45102. const char *zDestDb, /* Name of database within pDestDb */
  45103. sqlite3* pSrcDb, /* Database connection to read from */
  45104. const char *zSrcDb /* Name of database within pSrcDb */
  45105. ){
  45106. sqlite3_backup *p; /* Value to return */
  45107. /* Lock the source database handle. The destination database
  45108. ** handle is not locked in this routine, but it is locked in
  45109. ** sqlite3_backup_step(). The user is required to ensure that no
  45110. ** other thread accesses the destination handle for the duration
  45111. ** of the backup operation. Any attempt to use the destination
  45112. ** database connection while a backup is in progress may cause
  45113. ** a malfunction or a deadlock.
  45114. */
  45115. sqlite3_mutex_enter(pSrcDb->mutex);
  45116. sqlite3_mutex_enter(pDestDb->mutex);
  45117. if( pSrcDb==pDestDb ){
  45118. sqlite3Error(
  45119. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  45120. );
  45121. p = 0;
  45122. }else {
  45123. /* Allocate space for a new sqlite3_backup object...
  45124. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  45125. ** call to sqlite3_backup_init() and is destroyed by a call to
  45126. ** sqlite3_backup_finish(). */
  45127. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  45128. if( !p ){
  45129. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  45130. }
  45131. }
  45132. /* If the allocation succeeded, populate the new object. */
  45133. if( p ){
  45134. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  45135. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  45136. p->pDestDb = pDestDb;
  45137. p->pSrcDb = pSrcDb;
  45138. p->iNext = 1;
  45139. p->isAttached = 0;
  45140. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  45141. /* One (or both) of the named databases did not exist or an OOM
  45142. ** error was hit. The error has already been written into the
  45143. ** pDestDb handle. All that is left to do here is free the
  45144. ** sqlite3_backup structure.
  45145. */
  45146. sqlite3_free(p);
  45147. p = 0;
  45148. }
  45149. }
  45150. if( p ){
  45151. p->pSrc->nBackup++;
  45152. }
  45153. sqlite3_mutex_leave(pDestDb->mutex);
  45154. sqlite3_mutex_leave(pSrcDb->mutex);
  45155. return p;
  45156. }
  45157. /*
  45158. ** Argument rc is an SQLite error code. Return true if this error is
  45159. ** considered fatal if encountered during a backup operation. All errors
  45160. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  45161. */
  45162. static int isFatalError(int rc){
  45163. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  45164. }
  45165. /*
  45166. ** Parameter zSrcData points to a buffer containing the data for
  45167. ** page iSrcPg from the source database. Copy this data into the
  45168. ** destination database.
  45169. */
  45170. static int backupOnePage(
  45171. sqlite3_backup *p, /* Backup handle */
  45172. Pgno iSrcPg, /* Source database page to backup */
  45173. const u8 *zSrcData, /* Source database page data */
  45174. int bUpdate /* True for an update, false otherwise */
  45175. ){
  45176. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  45177. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  45178. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  45179. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  45180. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  45181. #ifdef SQLITE_HAS_CODEC
  45182. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  45183. ** guaranteed that the shared-mutex is held by this thread, handle
  45184. ** p->pSrc may not actually be the owner. */
  45185. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  45186. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  45187. #endif
  45188. int rc = SQLITE_OK;
  45189. i64 iOff;
  45190. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  45191. assert( p->bDestLocked );
  45192. assert( !isFatalError(p->rc) );
  45193. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  45194. assert( zSrcData );
  45195. /* Catch the case where the destination is an in-memory database and the
  45196. ** page sizes of the source and destination differ.
  45197. */
  45198. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  45199. rc = SQLITE_READONLY;
  45200. }
  45201. #ifdef SQLITE_HAS_CODEC
  45202. /* Backup is not possible if the page size of the destination is changing
  45203. ** and a codec is in use.
  45204. */
  45205. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  45206. rc = SQLITE_READONLY;
  45207. }
  45208. /* Backup is not possible if the number of bytes of reserve space differ
  45209. ** between source and destination. If there is a difference, try to
  45210. ** fix the destination to agree with the source. If that is not possible,
  45211. ** then the backup cannot proceed.
  45212. */
  45213. if( nSrcReserve!=nDestReserve ){
  45214. u32 newPgsz = nSrcPgsz;
  45215. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  45216. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  45217. }
  45218. #endif
  45219. /* This loop runs once for each destination page spanned by the source
  45220. ** page. For each iteration, variable iOff is set to the byte offset
  45221. ** of the destination page.
  45222. */
  45223. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  45224. DbPage *pDestPg = 0;
  45225. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  45226. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  45227. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  45228. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  45229. ){
  45230. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  45231. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  45232. u8 *zOut = &zDestData[iOff%nDestPgsz];
  45233. /* Copy the data from the source page into the destination page.
  45234. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  45235. ** and the pager code use this trick (clearing the first byte
  45236. ** of the page 'extra' space to invalidate the Btree layers
  45237. ** cached parse of the page). MemPage.isInit is marked
  45238. ** "MUST BE FIRST" for this purpose.
  45239. */
  45240. memcpy(zOut, zIn, nCopy);
  45241. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  45242. if( iOff==0 && bUpdate==0 ){
  45243. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  45244. }
  45245. }
  45246. sqlite3PagerUnref(pDestPg);
  45247. }
  45248. return rc;
  45249. }
  45250. /*
  45251. ** If pFile is currently larger than iSize bytes, then truncate it to
  45252. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  45253. ** this function is a no-op.
  45254. **
  45255. ** Return SQLITE_OK if everything is successful, or an SQLite error
  45256. ** code if an error occurs.
  45257. */
  45258. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  45259. i64 iCurrent;
  45260. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  45261. if( rc==SQLITE_OK && iCurrent>iSize ){
  45262. rc = sqlite3OsTruncate(pFile, iSize);
  45263. }
  45264. return rc;
  45265. }
  45266. /*
  45267. ** Register this backup object with the associated source pager for
  45268. ** callbacks when pages are changed or the cache invalidated.
  45269. */
  45270. static void attachBackupObject(sqlite3_backup *p){
  45271. sqlite3_backup **pp;
  45272. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  45273. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  45274. p->pNext = *pp;
  45275. *pp = p;
  45276. p->isAttached = 1;
  45277. }
  45278. /*
  45279. ** Copy nPage pages from the source b-tree to the destination.
  45280. */
  45281. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  45282. int rc;
  45283. int destMode; /* Destination journal mode */
  45284. int pgszSrc = 0; /* Source page size */
  45285. int pgszDest = 0; /* Destination page size */
  45286. sqlite3_mutex_enter(p->pSrcDb->mutex);
  45287. sqlite3BtreeEnter(p->pSrc);
  45288. if( p->pDestDb ){
  45289. sqlite3_mutex_enter(p->pDestDb->mutex);
  45290. }
  45291. rc = p->rc;
  45292. if( !isFatalError(rc) ){
  45293. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  45294. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  45295. int ii; /* Iterator variable */
  45296. int nSrcPage = -1; /* Size of source db in pages */
  45297. int bCloseTrans = 0; /* True if src db requires unlocking */
  45298. /* If the source pager is currently in a write-transaction, return
  45299. ** SQLITE_BUSY immediately.
  45300. */
  45301. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  45302. rc = SQLITE_BUSY;
  45303. }else{
  45304. rc = SQLITE_OK;
  45305. }
  45306. /* Lock the destination database, if it is not locked already. */
  45307. if( SQLITE_OK==rc && p->bDestLocked==0
  45308. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  45309. ){
  45310. p->bDestLocked = 1;
  45311. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  45312. }
  45313. /* If there is no open read-transaction on the source database, open
  45314. ** one now. If a transaction is opened here, then it will be closed
  45315. ** before this function exits.
  45316. */
  45317. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  45318. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  45319. bCloseTrans = 1;
  45320. }
  45321. /* Do not allow backup if the destination database is in WAL mode
  45322. ** and the page sizes are different between source and destination */
  45323. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  45324. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  45325. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  45326. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  45327. rc = SQLITE_READONLY;
  45328. }
  45329. /* Now that there is a read-lock on the source database, query the
  45330. ** source pager for the number of pages in the database.
  45331. */
  45332. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  45333. assert( nSrcPage>=0 );
  45334. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  45335. const Pgno iSrcPg = p->iNext; /* Source page number */
  45336. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  45337. DbPage *pSrcPg; /* Source page object */
  45338. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  45339. PAGER_GET_READONLY);
  45340. if( rc==SQLITE_OK ){
  45341. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  45342. sqlite3PagerUnref(pSrcPg);
  45343. }
  45344. }
  45345. p->iNext++;
  45346. }
  45347. if( rc==SQLITE_OK ){
  45348. p->nPagecount = nSrcPage;
  45349. p->nRemaining = nSrcPage+1-p->iNext;
  45350. if( p->iNext>(Pgno)nSrcPage ){
  45351. rc = SQLITE_DONE;
  45352. }else if( !p->isAttached ){
  45353. attachBackupObject(p);
  45354. }
  45355. }
  45356. /* Update the schema version field in the destination database. This
  45357. ** is to make sure that the schema-version really does change in
  45358. ** the case where the source and destination databases have the
  45359. ** same schema version.
  45360. */
  45361. if( rc==SQLITE_DONE ){
  45362. if( nSrcPage==0 ){
  45363. rc = sqlite3BtreeNewDb(p->pDest);
  45364. nSrcPage = 1;
  45365. }
  45366. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  45367. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  45368. }
  45369. if( rc==SQLITE_OK ){
  45370. if( p->pDestDb ){
  45371. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  45372. }
  45373. if( destMode==PAGER_JOURNALMODE_WAL ){
  45374. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  45375. }
  45376. }
  45377. if( rc==SQLITE_OK ){
  45378. int nDestTruncate;
  45379. /* Set nDestTruncate to the final number of pages in the destination
  45380. ** database. The complication here is that the destination page
  45381. ** size may be different to the source page size.
  45382. **
  45383. ** If the source page size is smaller than the destination page size,
  45384. ** round up. In this case the call to sqlite3OsTruncate() below will
  45385. ** fix the size of the file. However it is important to call
  45386. ** sqlite3PagerTruncateImage() here so that any pages in the
  45387. ** destination file that lie beyond the nDestTruncate page mark are
  45388. ** journalled by PagerCommitPhaseOne() before they are destroyed
  45389. ** by the file truncation.
  45390. */
  45391. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  45392. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  45393. if( pgszSrc<pgszDest ){
  45394. int ratio = pgszDest/pgszSrc;
  45395. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  45396. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  45397. nDestTruncate--;
  45398. }
  45399. }else{
  45400. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  45401. }
  45402. assert( nDestTruncate>0 );
  45403. if( pgszSrc<pgszDest ){
  45404. /* If the source page-size is smaller than the destination page-size,
  45405. ** two extra things may need to happen:
  45406. **
  45407. ** * The destination may need to be truncated, and
  45408. **
  45409. ** * Data stored on the pages immediately following the
  45410. ** pending-byte page in the source database may need to be
  45411. ** copied into the destination database.
  45412. */
  45413. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  45414. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  45415. Pgno iPg;
  45416. int nDstPage;
  45417. i64 iOff;
  45418. i64 iEnd;
  45419. assert( pFile );
  45420. assert( nDestTruncate==0
  45421. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  45422. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  45423. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  45424. ));
  45425. /* This block ensures that all data required to recreate the original
  45426. ** database has been stored in the journal for pDestPager and the
  45427. ** journal synced to disk. So at this point we may safely modify
  45428. ** the database file in any way, knowing that if a power failure
  45429. ** occurs, the original database will be reconstructed from the
  45430. ** journal file. */
  45431. sqlite3PagerPagecount(pDestPager, &nDstPage);
  45432. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  45433. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  45434. DbPage *pPg;
  45435. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  45436. if( rc==SQLITE_OK ){
  45437. rc = sqlite3PagerWrite(pPg);
  45438. sqlite3PagerUnref(pPg);
  45439. }
  45440. }
  45441. }
  45442. if( rc==SQLITE_OK ){
  45443. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  45444. }
  45445. /* Write the extra pages and truncate the database file as required */
  45446. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  45447. for(
  45448. iOff=PENDING_BYTE+pgszSrc;
  45449. rc==SQLITE_OK && iOff<iEnd;
  45450. iOff+=pgszSrc
  45451. ){
  45452. PgHdr *pSrcPg = 0;
  45453. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  45454. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  45455. if( rc==SQLITE_OK ){
  45456. u8 *zData = sqlite3PagerGetData(pSrcPg);
  45457. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  45458. }
  45459. sqlite3PagerUnref(pSrcPg);
  45460. }
  45461. if( rc==SQLITE_OK ){
  45462. rc = backupTruncateFile(pFile, iSize);
  45463. }
  45464. /* Sync the database file to disk. */
  45465. if( rc==SQLITE_OK ){
  45466. rc = sqlite3PagerSync(pDestPager);
  45467. }
  45468. }else{
  45469. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  45470. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  45471. }
  45472. /* Finish committing the transaction to the destination database. */
  45473. if( SQLITE_OK==rc
  45474. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  45475. ){
  45476. rc = SQLITE_DONE;
  45477. }
  45478. }
  45479. }
  45480. /* If bCloseTrans is true, then this function opened a read transaction
  45481. ** on the source database. Close the read transaction here. There is
  45482. ** no need to check the return values of the btree methods here, as
  45483. ** "committing" a read-only transaction cannot fail.
  45484. */
  45485. if( bCloseTrans ){
  45486. TESTONLY( int rc2 );
  45487. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  45488. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  45489. assert( rc2==SQLITE_OK );
  45490. }
  45491. if( rc==SQLITE_IOERR_NOMEM ){
  45492. rc = SQLITE_NOMEM;
  45493. }
  45494. p->rc = rc;
  45495. }
  45496. if( p->pDestDb ){
  45497. sqlite3_mutex_leave(p->pDestDb->mutex);
  45498. }
  45499. sqlite3BtreeLeave(p->pSrc);
  45500. sqlite3_mutex_leave(p->pSrcDb->mutex);
  45501. return rc;
  45502. }
  45503. /*
  45504. ** Release all resources associated with an sqlite3_backup* handle.
  45505. */
  45506. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  45507. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  45508. sqlite3 *pSrcDb; /* Source database connection */
  45509. int rc; /* Value to return */
  45510. /* Enter the mutexes */
  45511. if( p==0 ) return SQLITE_OK;
  45512. pSrcDb = p->pSrcDb;
  45513. sqlite3_mutex_enter(pSrcDb->mutex);
  45514. sqlite3BtreeEnter(p->pSrc);
  45515. if( p->pDestDb ){
  45516. sqlite3_mutex_enter(p->pDestDb->mutex);
  45517. }
  45518. /* Detach this backup from the source pager. */
  45519. if( p->pDestDb ){
  45520. p->pSrc->nBackup--;
  45521. }
  45522. if( p->isAttached ){
  45523. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  45524. while( *pp!=p ){
  45525. pp = &(*pp)->pNext;
  45526. }
  45527. *pp = p->pNext;
  45528. }
  45529. /* If a transaction is still open on the Btree, roll it back. */
  45530. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  45531. /* Set the error code of the destination database handle. */
  45532. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  45533. sqlite3Error(p->pDestDb, rc, 0);
  45534. /* Exit the mutexes and free the backup context structure. */
  45535. if( p->pDestDb ){
  45536. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  45537. }
  45538. sqlite3BtreeLeave(p->pSrc);
  45539. if( p->pDestDb ){
  45540. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  45541. ** call to sqlite3_backup_init() and is destroyed by a call to
  45542. ** sqlite3_backup_finish(). */
  45543. sqlite3_free(p);
  45544. }
  45545. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  45546. return rc;
  45547. }
  45548. /*
  45549. ** Return the number of pages still to be backed up as of the most recent
  45550. ** call to sqlite3_backup_step().
  45551. */
  45552. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  45553. return p->nRemaining;
  45554. }
  45555. /*
  45556. ** Return the total number of pages in the source database as of the most
  45557. ** recent call to sqlite3_backup_step().
  45558. */
  45559. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  45560. return p->nPagecount;
  45561. }
  45562. /*
  45563. ** This function is called after the contents of page iPage of the
  45564. ** source database have been modified. If page iPage has already been
  45565. ** copied into the destination database, then the data written to the
  45566. ** destination is now invalidated. The destination copy of iPage needs
  45567. ** to be updated with the new data before the backup operation is
  45568. ** complete.
  45569. **
  45570. ** It is assumed that the mutex associated with the BtShared object
  45571. ** corresponding to the source database is held when this function is
  45572. ** called.
  45573. */
  45574. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  45575. sqlite3_backup *p; /* Iterator variable */
  45576. for(p=pBackup; p; p=p->pNext){
  45577. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  45578. if( !isFatalError(p->rc) && iPage<p->iNext ){
  45579. /* The backup process p has already copied page iPage. But now it
  45580. ** has been modified by a transaction on the source pager. Copy
  45581. ** the new data into the backup.
  45582. */
  45583. int rc;
  45584. assert( p->pDestDb );
  45585. sqlite3_mutex_enter(p->pDestDb->mutex);
  45586. rc = backupOnePage(p, iPage, aData, 1);
  45587. sqlite3_mutex_leave(p->pDestDb->mutex);
  45588. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  45589. if( rc!=SQLITE_OK ){
  45590. p->rc = rc;
  45591. }
  45592. }
  45593. }
  45594. }
  45595. /*
  45596. ** Restart the backup process. This is called when the pager layer
  45597. ** detects that the database has been modified by an external database
  45598. ** connection. In this case there is no way of knowing which of the
  45599. ** pages that have been copied into the destination database are still
  45600. ** valid and which are not, so the entire process needs to be restarted.
  45601. **
  45602. ** It is assumed that the mutex associated with the BtShared object
  45603. ** corresponding to the source database is held when this function is
  45604. ** called.
  45605. */
  45606. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  45607. sqlite3_backup *p; /* Iterator variable */
  45608. for(p=pBackup; p; p=p->pNext){
  45609. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  45610. p->iNext = 1;
  45611. }
  45612. }
  45613. #ifndef SQLITE_OMIT_VACUUM
  45614. /*
  45615. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  45616. ** must be active for both files.
  45617. **
  45618. ** The size of file pTo may be reduced by this operation. If anything
  45619. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  45620. ** transaction is committed before returning.
  45621. */
  45622. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  45623. int rc;
  45624. sqlite3_file *pFd; /* File descriptor for database pTo */
  45625. sqlite3_backup b;
  45626. sqlite3BtreeEnter(pTo);
  45627. sqlite3BtreeEnter(pFrom);
  45628. assert( sqlite3BtreeIsInTrans(pTo) );
  45629. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  45630. if( pFd->pMethods ){
  45631. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  45632. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  45633. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45634. if( rc ) goto copy_finished;
  45635. }
  45636. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  45637. ** to 0. This is used by the implementations of sqlite3_backup_step()
  45638. ** and sqlite3_backup_finish() to detect that they are being called
  45639. ** from this function, not directly by the user.
  45640. */
  45641. memset(&b, 0, sizeof(b));
  45642. b.pSrcDb = pFrom->db;
  45643. b.pSrc = pFrom;
  45644. b.pDest = pTo;
  45645. b.iNext = 1;
  45646. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  45647. ** file. By passing this as the number of pages to copy to
  45648. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  45649. ** within a single call (unless an error occurs). The assert() statement
  45650. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  45651. ** or an error code.
  45652. */
  45653. sqlite3_backup_step(&b, 0x7FFFFFFF);
  45654. assert( b.rc!=SQLITE_OK );
  45655. rc = sqlite3_backup_finish(&b);
  45656. if( rc==SQLITE_OK ){
  45657. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  45658. }else{
  45659. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  45660. }
  45661. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  45662. copy_finished:
  45663. sqlite3BtreeLeave(pFrom);
  45664. sqlite3BtreeLeave(pTo);
  45665. return rc;
  45666. }
  45667. #endif /* SQLITE_OMIT_VACUUM */
  45668. /************** End of backup.c **********************************************/
  45669. /************** Begin file vdbemem.c *****************************************/
  45670. /*
  45671. ** 2004 May 26
  45672. **
  45673. ** The author disclaims copyright to this source code. In place of
  45674. ** a legal notice, here is a blessing:
  45675. **
  45676. ** May you do good and not evil.
  45677. ** May you find forgiveness for yourself and forgive others.
  45678. ** May you share freely, never taking more than you give.
  45679. **
  45680. *************************************************************************
  45681. **
  45682. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  45683. ** stores a single value in the VDBE. Mem is an opaque structure visible
  45684. ** only within the VDBE. Interface routines refer to a Mem using the
  45685. ** name sqlite_value
  45686. */
  45687. /*
  45688. ** If pMem is an object with a valid string representation, this routine
  45689. ** ensures the internal encoding for the string representation is
  45690. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  45691. **
  45692. ** If pMem is not a string object, or the encoding of the string
  45693. ** representation is already stored using the requested encoding, then this
  45694. ** routine is a no-op.
  45695. **
  45696. ** SQLITE_OK is returned if the conversion is successful (or not required).
  45697. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  45698. ** between formats.
  45699. */
  45700. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  45701. #ifndef SQLITE_OMIT_UTF16
  45702. int rc;
  45703. #endif
  45704. assert( (pMem->flags&MEM_RowSet)==0 );
  45705. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  45706. || desiredEnc==SQLITE_UTF16BE );
  45707. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  45708. return SQLITE_OK;
  45709. }
  45710. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45711. #ifdef SQLITE_OMIT_UTF16
  45712. return SQLITE_ERROR;
  45713. #else
  45714. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  45715. ** then the encoding of the value may not have changed.
  45716. */
  45717. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  45718. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  45719. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  45720. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  45721. return rc;
  45722. #endif
  45723. }
  45724. /*
  45725. ** Make sure pMem->z points to a writable allocation of at least
  45726. ** n bytes.
  45727. **
  45728. ** If the third argument passed to this function is true, then memory
  45729. ** cell pMem must contain a string or blob. In this case the content is
  45730. ** preserved. Otherwise, if the third parameter to this function is false,
  45731. ** any current string or blob value may be discarded.
  45732. **
  45733. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  45734. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  45735. ** not set, Mem.n is zeroed.
  45736. */
  45737. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  45738. assert( 1 >=
  45739. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  45740. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  45741. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  45742. ((pMem->flags&MEM_Static) ? 1 : 0)
  45743. );
  45744. assert( (pMem->flags&MEM_RowSet)==0 );
  45745. /* If the preserve flag is set to true, then the memory cell must already
  45746. ** contain a valid string or blob value. */
  45747. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  45748. if( n<32 ) n = 32;
  45749. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  45750. if( preserve && pMem->z==pMem->zMalloc ){
  45751. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  45752. preserve = 0;
  45753. }else{
  45754. sqlite3DbFree(pMem->db, pMem->zMalloc);
  45755. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  45756. }
  45757. }
  45758. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  45759. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  45760. }
  45761. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  45762. assert( pMem->xDel!=SQLITE_DYNAMIC );
  45763. pMem->xDel((void *)(pMem->z));
  45764. }
  45765. pMem->z = pMem->zMalloc;
  45766. if( pMem->z==0 ){
  45767. pMem->flags = MEM_Null;
  45768. }else{
  45769. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  45770. }
  45771. pMem->xDel = 0;
  45772. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  45773. }
  45774. /*
  45775. ** Make the given Mem object MEM_Dyn. In other words, make it so
  45776. ** that any TEXT or BLOB content is stored in memory obtained from
  45777. ** malloc(). In this way, we know that the memory is safe to be
  45778. ** overwritten or altered.
  45779. **
  45780. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  45781. */
  45782. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  45783. int f;
  45784. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45785. assert( (pMem->flags&MEM_RowSet)==0 );
  45786. ExpandBlob(pMem);
  45787. f = pMem->flags;
  45788. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  45789. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  45790. return SQLITE_NOMEM;
  45791. }
  45792. pMem->z[pMem->n] = 0;
  45793. pMem->z[pMem->n+1] = 0;
  45794. pMem->flags |= MEM_Term;
  45795. #ifdef SQLITE_DEBUG
  45796. pMem->pScopyFrom = 0;
  45797. #endif
  45798. }
  45799. return SQLITE_OK;
  45800. }
  45801. /*
  45802. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  45803. ** blob stored in dynamically allocated space.
  45804. */
  45805. #ifndef SQLITE_OMIT_INCRBLOB
  45806. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  45807. if( pMem->flags & MEM_Zero ){
  45808. int nByte;
  45809. assert( pMem->flags&MEM_Blob );
  45810. assert( (pMem->flags&MEM_RowSet)==0 );
  45811. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45812. /* Set nByte to the number of bytes required to store the expanded blob. */
  45813. nByte = pMem->n + pMem->u.nZero;
  45814. if( nByte<=0 ){
  45815. nByte = 1;
  45816. }
  45817. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  45818. return SQLITE_NOMEM;
  45819. }
  45820. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  45821. pMem->n += pMem->u.nZero;
  45822. pMem->flags &= ~(MEM_Zero|MEM_Term);
  45823. }
  45824. return SQLITE_OK;
  45825. }
  45826. #endif
  45827. /*
  45828. ** Make sure the given Mem is \u0000 terminated.
  45829. */
  45830. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  45831. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45832. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  45833. return SQLITE_OK; /* Nothing to do */
  45834. }
  45835. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  45836. return SQLITE_NOMEM;
  45837. }
  45838. pMem->z[pMem->n] = 0;
  45839. pMem->z[pMem->n+1] = 0;
  45840. pMem->flags |= MEM_Term;
  45841. return SQLITE_OK;
  45842. }
  45843. /*
  45844. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  45845. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  45846. ** is a no-op.
  45847. **
  45848. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  45849. **
  45850. ** A MEM_Null value will never be passed to this function. This function is
  45851. ** used for converting values to text for returning to the user (i.e. via
  45852. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  45853. ** keys are strings. In the former case a NULL pointer is returned the
  45854. ** user and the later is an internal programming error.
  45855. */
  45856. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  45857. int rc = SQLITE_OK;
  45858. int fg = pMem->flags;
  45859. const int nByte = 32;
  45860. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45861. assert( !(fg&MEM_Zero) );
  45862. assert( !(fg&(MEM_Str|MEM_Blob)) );
  45863. assert( fg&(MEM_Int|MEM_Real) );
  45864. assert( (pMem->flags&MEM_RowSet)==0 );
  45865. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  45866. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  45867. return SQLITE_NOMEM;
  45868. }
  45869. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  45870. ** string representation of the value. Then, if the required encoding
  45871. ** is UTF-16le or UTF-16be do a translation.
  45872. **
  45873. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  45874. */
  45875. if( fg & MEM_Int ){
  45876. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  45877. }else{
  45878. assert( fg & MEM_Real );
  45879. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  45880. }
  45881. pMem->n = sqlite3Strlen30(pMem->z);
  45882. pMem->enc = SQLITE_UTF8;
  45883. pMem->flags |= MEM_Str|MEM_Term;
  45884. sqlite3VdbeChangeEncoding(pMem, enc);
  45885. return rc;
  45886. }
  45887. /*
  45888. ** Memory cell pMem contains the context of an aggregate function.
  45889. ** This routine calls the finalize method for that function. The
  45890. ** result of the aggregate is stored back into pMem.
  45891. **
  45892. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  45893. ** otherwise.
  45894. */
  45895. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  45896. int rc = SQLITE_OK;
  45897. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  45898. sqlite3_context ctx;
  45899. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  45900. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45901. memset(&ctx, 0, sizeof(ctx));
  45902. ctx.s.flags = MEM_Null;
  45903. ctx.s.db = pMem->db;
  45904. ctx.pMem = pMem;
  45905. ctx.pFunc = pFunc;
  45906. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  45907. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  45908. sqlite3DbFree(pMem->db, pMem->zMalloc);
  45909. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  45910. rc = ctx.isError;
  45911. }
  45912. return rc;
  45913. }
  45914. /*
  45915. ** If the memory cell contains a string value that must be freed by
  45916. ** invoking an external callback, free it now. Calling this function
  45917. ** does not free any Mem.zMalloc buffer.
  45918. */
  45919. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  45920. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  45921. if( p->flags&MEM_Agg ){
  45922. sqlite3VdbeMemFinalize(p, p->u.pDef);
  45923. assert( (p->flags & MEM_Agg)==0 );
  45924. sqlite3VdbeMemRelease(p);
  45925. }else if( p->flags&MEM_Dyn && p->xDel ){
  45926. assert( (p->flags&MEM_RowSet)==0 );
  45927. assert( p->xDel!=SQLITE_DYNAMIC );
  45928. p->xDel((void *)p->z);
  45929. p->xDel = 0;
  45930. }else if( p->flags&MEM_RowSet ){
  45931. sqlite3RowSetClear(p->u.pRowSet);
  45932. }else if( p->flags&MEM_Frame ){
  45933. sqlite3VdbeMemSetNull(p);
  45934. }
  45935. }
  45936. /*
  45937. ** Release any memory held by the Mem. This may leave the Mem in an
  45938. ** inconsistent state, for example with (Mem.z==0) and
  45939. ** (Mem.type==SQLITE_TEXT).
  45940. */
  45941. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  45942. VdbeMemRelease(p);
  45943. sqlite3DbFree(p->db, p->zMalloc);
  45944. p->z = 0;
  45945. p->zMalloc = 0;
  45946. p->xDel = 0;
  45947. }
  45948. /*
  45949. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  45950. ** If the double is too large, return 0x8000000000000000.
  45951. **
  45952. ** Most systems appear to do this simply by assigning
  45953. ** variables and without the extra range tests. But
  45954. ** there are reports that windows throws an expection
  45955. ** if the floating point value is out of range. (See ticket #2880.)
  45956. ** Because we do not completely understand the problem, we will
  45957. ** take the conservative approach and always do range tests
  45958. ** before attempting the conversion.
  45959. */
  45960. static i64 doubleToInt64(double r){
  45961. #ifdef SQLITE_OMIT_FLOATING_POINT
  45962. /* When floating-point is omitted, double and int64 are the same thing */
  45963. return r;
  45964. #else
  45965. /*
  45966. ** Many compilers we encounter do not define constants for the
  45967. ** minimum and maximum 64-bit integers, or they define them
  45968. ** inconsistently. And many do not understand the "LL" notation.
  45969. ** So we define our own static constants here using nothing
  45970. ** larger than a 32-bit integer constant.
  45971. */
  45972. static const i64 maxInt = LARGEST_INT64;
  45973. static const i64 minInt = SMALLEST_INT64;
  45974. if( r<(double)minInt ){
  45975. return minInt;
  45976. }else if( r>(double)maxInt ){
  45977. /* minInt is correct here - not maxInt. It turns out that assigning
  45978. ** a very large positive number to an integer results in a very large
  45979. ** negative integer. This makes no sense, but it is what x86 hardware
  45980. ** does so for compatibility we will do the same in software. */
  45981. return minInt;
  45982. }else{
  45983. return (i64)r;
  45984. }
  45985. #endif
  45986. }
  45987. /*
  45988. ** Return some kind of integer value which is the best we can do
  45989. ** at representing the value that *pMem describes as an integer.
  45990. ** If pMem is an integer, then the value is exact. If pMem is
  45991. ** a floating-point then the value returned is the integer part.
  45992. ** If pMem is a string or blob, then we make an attempt to convert
  45993. ** it into a integer and return that. If pMem represents an
  45994. ** an SQL-NULL value, return 0.
  45995. **
  45996. ** If pMem represents a string value, its encoding might be changed.
  45997. */
  45998. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  45999. int flags;
  46000. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46001. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46002. flags = pMem->flags;
  46003. if( flags & MEM_Int ){
  46004. return pMem->u.i;
  46005. }else if( flags & MEM_Real ){
  46006. return doubleToInt64(pMem->r);
  46007. }else if( flags & (MEM_Str|MEM_Blob) ){
  46008. i64 value = 0;
  46009. assert( pMem->z || pMem->n==0 );
  46010. testcase( pMem->z==0 );
  46011. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  46012. return value;
  46013. }else{
  46014. return 0;
  46015. }
  46016. }
  46017. /*
  46018. ** Return the best representation of pMem that we can get into a
  46019. ** double. If pMem is already a double or an integer, return its
  46020. ** value. If it is a string or blob, try to convert it to a double.
  46021. ** If it is a NULL, return 0.0.
  46022. */
  46023. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  46024. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46025. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46026. if( pMem->flags & MEM_Real ){
  46027. return pMem->r;
  46028. }else if( pMem->flags & MEM_Int ){
  46029. return (double)pMem->u.i;
  46030. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  46031. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  46032. double val = (double)0;
  46033. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  46034. return val;
  46035. }else{
  46036. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  46037. return (double)0;
  46038. }
  46039. }
  46040. /*
  46041. ** The MEM structure is already a MEM_Real. Try to also make it a
  46042. ** MEM_Int if we can.
  46043. */
  46044. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  46045. assert( pMem->flags & MEM_Real );
  46046. assert( (pMem->flags & MEM_RowSet)==0 );
  46047. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46048. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46049. pMem->u.i = doubleToInt64(pMem->r);
  46050. /* Only mark the value as an integer if
  46051. **
  46052. ** (1) the round-trip conversion real->int->real is a no-op, and
  46053. ** (2) The integer is neither the largest nor the smallest
  46054. ** possible integer (ticket #3922)
  46055. **
  46056. ** The second and third terms in the following conditional enforces
  46057. ** the second condition under the assumption that addition overflow causes
  46058. ** values to wrap around. On x86 hardware, the third term is always
  46059. ** true and could be omitted. But we leave it in because other
  46060. ** architectures might behave differently.
  46061. */
  46062. if( pMem->r==(double)pMem->u.i
  46063. && pMem->u.i>SMALLEST_INT64
  46064. #if defined(__i486__) || defined(__x86_64__)
  46065. && ALWAYS(pMem->u.i<LARGEST_INT64)
  46066. #else
  46067. && pMem->u.i<LARGEST_INT64
  46068. #endif
  46069. ){
  46070. pMem->flags |= MEM_Int;
  46071. }
  46072. }
  46073. /*
  46074. ** Convert pMem to type integer. Invalidate any prior representations.
  46075. */
  46076. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  46077. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46078. assert( (pMem->flags & MEM_RowSet)==0 );
  46079. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46080. pMem->u.i = sqlite3VdbeIntValue(pMem);
  46081. MemSetTypeFlag(pMem, MEM_Int);
  46082. return SQLITE_OK;
  46083. }
  46084. /*
  46085. ** Convert pMem so that it is of type MEM_Real.
  46086. ** Invalidate any prior representations.
  46087. */
  46088. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  46089. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46090. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46091. pMem->r = sqlite3VdbeRealValue(pMem);
  46092. MemSetTypeFlag(pMem, MEM_Real);
  46093. return SQLITE_OK;
  46094. }
  46095. /*
  46096. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  46097. ** Invalidate any prior representations.
  46098. **
  46099. ** Every effort is made to force the conversion, even if the input
  46100. ** is a string that does not look completely like a number. Convert
  46101. ** as much of the string as we can and ignore the rest.
  46102. */
  46103. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  46104. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  46105. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  46106. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46107. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  46108. MemSetTypeFlag(pMem, MEM_Int);
  46109. }else{
  46110. pMem->r = sqlite3VdbeRealValue(pMem);
  46111. MemSetTypeFlag(pMem, MEM_Real);
  46112. sqlite3VdbeIntegerAffinity(pMem);
  46113. }
  46114. }
  46115. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  46116. pMem->flags &= ~(MEM_Str|MEM_Blob);
  46117. return SQLITE_OK;
  46118. }
  46119. /*
  46120. ** Delete any previous value and set the value stored in *pMem to NULL.
  46121. */
  46122. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  46123. if( pMem->flags & MEM_Frame ){
  46124. VdbeFrame *pFrame = pMem->u.pFrame;
  46125. pFrame->pParent = pFrame->v->pDelFrame;
  46126. pFrame->v->pDelFrame = pFrame;
  46127. }
  46128. if( pMem->flags & MEM_RowSet ){
  46129. sqlite3RowSetClear(pMem->u.pRowSet);
  46130. }
  46131. MemSetTypeFlag(pMem, MEM_Null);
  46132. pMem->type = SQLITE_NULL;
  46133. }
  46134. /*
  46135. ** Delete any previous value and set the value to be a BLOB of length
  46136. ** n containing all zeros.
  46137. */
  46138. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  46139. sqlite3VdbeMemRelease(pMem);
  46140. pMem->flags = MEM_Blob|MEM_Zero;
  46141. pMem->type = SQLITE_BLOB;
  46142. pMem->n = 0;
  46143. if( n<0 ) n = 0;
  46144. pMem->u.nZero = n;
  46145. pMem->enc = SQLITE_UTF8;
  46146. #ifdef SQLITE_OMIT_INCRBLOB
  46147. sqlite3VdbeMemGrow(pMem, n, 0);
  46148. if( pMem->z ){
  46149. pMem->n = n;
  46150. memset(pMem->z, 0, n);
  46151. }
  46152. #endif
  46153. }
  46154. /*
  46155. ** Delete any previous value and set the value stored in *pMem to val,
  46156. ** manifest type INTEGER.
  46157. */
  46158. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  46159. sqlite3VdbeMemRelease(pMem);
  46160. pMem->u.i = val;
  46161. pMem->flags = MEM_Int;
  46162. pMem->type = SQLITE_INTEGER;
  46163. }
  46164. #ifndef SQLITE_OMIT_FLOATING_POINT
  46165. /*
  46166. ** Delete any previous value and set the value stored in *pMem to val,
  46167. ** manifest type REAL.
  46168. */
  46169. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  46170. if( sqlite3IsNaN(val) ){
  46171. sqlite3VdbeMemSetNull(pMem);
  46172. }else{
  46173. sqlite3VdbeMemRelease(pMem);
  46174. pMem->r = val;
  46175. pMem->flags = MEM_Real;
  46176. pMem->type = SQLITE_FLOAT;
  46177. }
  46178. }
  46179. #endif
  46180. /*
  46181. ** Delete any previous value and set the value of pMem to be an
  46182. ** empty boolean index.
  46183. */
  46184. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  46185. sqlite3 *db = pMem->db;
  46186. assert( db!=0 );
  46187. assert( (pMem->flags & MEM_RowSet)==0 );
  46188. sqlite3VdbeMemRelease(pMem);
  46189. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  46190. if( db->mallocFailed ){
  46191. pMem->flags = MEM_Null;
  46192. }else{
  46193. assert( pMem->zMalloc );
  46194. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  46195. sqlite3DbMallocSize(db, pMem->zMalloc));
  46196. assert( pMem->u.pRowSet!=0 );
  46197. pMem->flags = MEM_RowSet;
  46198. }
  46199. }
  46200. /*
  46201. ** Return true if the Mem object contains a TEXT or BLOB that is
  46202. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  46203. */
  46204. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  46205. assert( p->db!=0 );
  46206. if( p->flags & (MEM_Str|MEM_Blob) ){
  46207. int n = p->n;
  46208. if( p->flags & MEM_Zero ){
  46209. n += p->u.nZero;
  46210. }
  46211. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  46212. }
  46213. return 0;
  46214. }
  46215. #ifdef SQLITE_DEBUG
  46216. /*
  46217. ** This routine prepares a memory cell for modication by breaking
  46218. ** its link to a shallow copy and by marking any current shallow
  46219. ** copies of this cell as invalid.
  46220. **
  46221. ** This is used for testing and debugging only - to make sure shallow
  46222. ** copies are not misused.
  46223. */
  46224. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  46225. int i;
  46226. Mem *pX;
  46227. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  46228. if( pX->pScopyFrom==pMem ){
  46229. pX->flags |= MEM_Invalid;
  46230. pX->pScopyFrom = 0;
  46231. }
  46232. }
  46233. pMem->pScopyFrom = 0;
  46234. }
  46235. #endif /* SQLITE_DEBUG */
  46236. /*
  46237. ** Size of struct Mem not including the Mem.zMalloc member.
  46238. */
  46239. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  46240. /*
  46241. ** Make an shallow copy of pFrom into pTo. Prior contents of
  46242. ** pTo are freed. The pFrom->z field is not duplicated. If
  46243. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  46244. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  46245. */
  46246. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  46247. assert( (pFrom->flags & MEM_RowSet)==0 );
  46248. VdbeMemRelease(pTo);
  46249. memcpy(pTo, pFrom, MEMCELLSIZE);
  46250. pTo->xDel = 0;
  46251. if( (pFrom->flags&MEM_Static)==0 ){
  46252. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  46253. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  46254. pTo->flags |= srcType;
  46255. }
  46256. }
  46257. /*
  46258. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  46259. ** freed before the copy is made.
  46260. */
  46261. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  46262. int rc = SQLITE_OK;
  46263. assert( (pFrom->flags & MEM_RowSet)==0 );
  46264. VdbeMemRelease(pTo);
  46265. memcpy(pTo, pFrom, MEMCELLSIZE);
  46266. pTo->flags &= ~MEM_Dyn;
  46267. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  46268. if( 0==(pFrom->flags&MEM_Static) ){
  46269. pTo->flags |= MEM_Ephem;
  46270. rc = sqlite3VdbeMemMakeWriteable(pTo);
  46271. }
  46272. }
  46273. return rc;
  46274. }
  46275. /*
  46276. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  46277. ** freed. If pFrom contains ephemeral data, a copy is made.
  46278. **
  46279. ** pFrom contains an SQL NULL when this routine returns.
  46280. */
  46281. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  46282. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  46283. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  46284. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  46285. sqlite3VdbeMemRelease(pTo);
  46286. memcpy(pTo, pFrom, sizeof(Mem));
  46287. pFrom->flags = MEM_Null;
  46288. pFrom->xDel = 0;
  46289. pFrom->zMalloc = 0;
  46290. }
  46291. /*
  46292. ** Change the value of a Mem to be a string or a BLOB.
  46293. **
  46294. ** The memory management strategy depends on the value of the xDel
  46295. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  46296. ** string is copied into a (possibly existing) buffer managed by the
  46297. ** Mem structure. Otherwise, any existing buffer is freed and the
  46298. ** pointer copied.
  46299. **
  46300. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  46301. ** size limit) then no memory allocation occurs. If the string can be
  46302. ** stored without allocating memory, then it is. If a memory allocation
  46303. ** is required to store the string, then value of pMem is unchanged. In
  46304. ** either case, SQLITE_TOOBIG is returned.
  46305. */
  46306. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  46307. Mem *pMem, /* Memory cell to set to string value */
  46308. const char *z, /* String pointer */
  46309. int n, /* Bytes in string, or negative */
  46310. u8 enc, /* Encoding of z. 0 for BLOBs */
  46311. void (*xDel)(void*) /* Destructor function */
  46312. ){
  46313. int nByte = n; /* New value for pMem->n */
  46314. int iLimit; /* Maximum allowed string or blob size */
  46315. u16 flags = 0; /* New value for pMem->flags */
  46316. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46317. assert( (pMem->flags & MEM_RowSet)==0 );
  46318. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  46319. if( !z ){
  46320. sqlite3VdbeMemSetNull(pMem);
  46321. return SQLITE_OK;
  46322. }
  46323. if( pMem->db ){
  46324. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  46325. }else{
  46326. iLimit = SQLITE_MAX_LENGTH;
  46327. }
  46328. flags = (enc==0?MEM_Blob:MEM_Str);
  46329. if( nByte<0 ){
  46330. assert( enc!=0 );
  46331. if( enc==SQLITE_UTF8 ){
  46332. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  46333. }else{
  46334. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  46335. }
  46336. flags |= MEM_Term;
  46337. }
  46338. /* The following block sets the new values of Mem.z and Mem.xDel. It
  46339. ** also sets a flag in local variable "flags" to indicate the memory
  46340. ** management (one of MEM_Dyn or MEM_Static).
  46341. */
  46342. if( xDel==SQLITE_TRANSIENT ){
  46343. int nAlloc = nByte;
  46344. if( flags&MEM_Term ){
  46345. nAlloc += (enc==SQLITE_UTF8?1:2);
  46346. }
  46347. if( nByte>iLimit ){
  46348. return SQLITE_TOOBIG;
  46349. }
  46350. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  46351. return SQLITE_NOMEM;
  46352. }
  46353. memcpy(pMem->z, z, nAlloc);
  46354. }else if( xDel==SQLITE_DYNAMIC ){
  46355. sqlite3VdbeMemRelease(pMem);
  46356. pMem->zMalloc = pMem->z = (char *)z;
  46357. pMem->xDel = 0;
  46358. }else{
  46359. sqlite3VdbeMemRelease(pMem);
  46360. pMem->z = (char *)z;
  46361. pMem->xDel = xDel;
  46362. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  46363. }
  46364. pMem->n = nByte;
  46365. pMem->flags = flags;
  46366. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  46367. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  46368. #ifndef SQLITE_OMIT_UTF16
  46369. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  46370. return SQLITE_NOMEM;
  46371. }
  46372. #endif
  46373. if( nByte>iLimit ){
  46374. return SQLITE_TOOBIG;
  46375. }
  46376. return SQLITE_OK;
  46377. }
  46378. /*
  46379. ** Compare the values contained by the two memory cells, returning
  46380. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  46381. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  46382. ** and reals) sorted numerically, followed by text ordered by the collating
  46383. ** sequence pColl and finally blob's ordered by memcmp().
  46384. **
  46385. ** Two NULL values are considered equal by this function.
  46386. */
  46387. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  46388. int rc;
  46389. int f1, f2;
  46390. int combined_flags;
  46391. f1 = pMem1->flags;
  46392. f2 = pMem2->flags;
  46393. combined_flags = f1|f2;
  46394. assert( (combined_flags & MEM_RowSet)==0 );
  46395. /* If one value is NULL, it is less than the other. If both values
  46396. ** are NULL, return 0.
  46397. */
  46398. if( combined_flags&MEM_Null ){
  46399. return (f2&MEM_Null) - (f1&MEM_Null);
  46400. }
  46401. /* If one value is a number and the other is not, the number is less.
  46402. ** If both are numbers, compare as reals if one is a real, or as integers
  46403. ** if both values are integers.
  46404. */
  46405. if( combined_flags&(MEM_Int|MEM_Real) ){
  46406. double r1, r2;
  46407. if( (f1 & f2 & MEM_Int)!=0 ){
  46408. if( pMem1->u.i < pMem2->u.i ) return -1;
  46409. if( pMem1->u.i > pMem2->u.i ) return 1;
  46410. return 0;
  46411. }
  46412. if( (f1&MEM_Real)!=0 ){
  46413. r1 = pMem1->r;
  46414. }else if( (f1&MEM_Int)!=0 ){
  46415. r1 = (double)pMem1->u.i;
  46416. }else{
  46417. return 1;
  46418. }
  46419. if( (f2&MEM_Real)!=0 ){
  46420. r2 = pMem2->r;
  46421. }else if( (f2&MEM_Int)!=0 ){
  46422. r2 = (double)pMem2->u.i;
  46423. }else{
  46424. return -1;
  46425. }
  46426. if( r1<r2 ) return -1;
  46427. if( r1>r2 ) return 1;
  46428. return 0;
  46429. }
  46430. /* If one value is a string and the other is a blob, the string is less.
  46431. ** If both are strings, compare using the collating functions.
  46432. */
  46433. if( combined_flags&MEM_Str ){
  46434. if( (f1 & MEM_Str)==0 ){
  46435. return 1;
  46436. }
  46437. if( (f2 & MEM_Str)==0 ){
  46438. return -1;
  46439. }
  46440. assert( pMem1->enc==pMem2->enc );
  46441. assert( pMem1->enc==SQLITE_UTF8 ||
  46442. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  46443. /* The collation sequence must be defined at this point, even if
  46444. ** the user deletes the collation sequence after the vdbe program is
  46445. ** compiled (this was not always the case).
  46446. */
  46447. assert( !pColl || pColl->xCmp );
  46448. if( pColl ){
  46449. if( pMem1->enc==pColl->enc ){
  46450. /* The strings are already in the correct encoding. Call the
  46451. ** comparison function directly */
  46452. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  46453. }else{
  46454. const void *v1, *v2;
  46455. int n1, n2;
  46456. Mem c1;
  46457. Mem c2;
  46458. memset(&c1, 0, sizeof(c1));
  46459. memset(&c2, 0, sizeof(c2));
  46460. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  46461. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  46462. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  46463. n1 = v1==0 ? 0 : c1.n;
  46464. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  46465. n2 = v2==0 ? 0 : c2.n;
  46466. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  46467. sqlite3VdbeMemRelease(&c1);
  46468. sqlite3VdbeMemRelease(&c2);
  46469. return rc;
  46470. }
  46471. }
  46472. /* If a NULL pointer was passed as the collate function, fall through
  46473. ** to the blob case and use memcmp(). */
  46474. }
  46475. /* Both values must be blobs. Compare using memcmp(). */
  46476. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  46477. if( rc==0 ){
  46478. rc = pMem1->n - pMem2->n;
  46479. }
  46480. return rc;
  46481. }
  46482. /*
  46483. ** Move data out of a btree key or data field and into a Mem structure.
  46484. ** The data or key is taken from the entry that pCur is currently pointing
  46485. ** to. offset and amt determine what portion of the data or key to retrieve.
  46486. ** key is true to get the key or false to get data. The result is written
  46487. ** into the pMem element.
  46488. **
  46489. ** The pMem structure is assumed to be uninitialized. Any prior content
  46490. ** is overwritten without being freed.
  46491. **
  46492. ** If this routine fails for any reason (malloc returns NULL or unable
  46493. ** to read from the disk) then the pMem is left in an inconsistent state.
  46494. */
  46495. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  46496. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  46497. int offset, /* Offset from the start of data to return bytes from. */
  46498. int amt, /* Number of bytes to return. */
  46499. int key, /* If true, retrieve from the btree key, not data. */
  46500. Mem *pMem /* OUT: Return data in this Mem structure. */
  46501. ){
  46502. char *zData; /* Data from the btree layer */
  46503. int available = 0; /* Number of bytes available on the local btree page */
  46504. int rc = SQLITE_OK; /* Return code */
  46505. assert( sqlite3BtreeCursorIsValid(pCur) );
  46506. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  46507. ** that both the BtShared and database handle mutexes are held. */
  46508. assert( (pMem->flags & MEM_RowSet)==0 );
  46509. if( key ){
  46510. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  46511. }else{
  46512. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  46513. }
  46514. assert( zData!=0 );
  46515. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  46516. sqlite3VdbeMemRelease(pMem);
  46517. pMem->z = &zData[offset];
  46518. pMem->flags = MEM_Blob|MEM_Ephem;
  46519. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  46520. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  46521. pMem->enc = 0;
  46522. pMem->type = SQLITE_BLOB;
  46523. if( key ){
  46524. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  46525. }else{
  46526. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  46527. }
  46528. pMem->z[amt] = 0;
  46529. pMem->z[amt+1] = 0;
  46530. if( rc!=SQLITE_OK ){
  46531. sqlite3VdbeMemRelease(pMem);
  46532. }
  46533. }
  46534. pMem->n = amt;
  46535. return rc;
  46536. }
  46537. /* This function is only available internally, it is not part of the
  46538. ** external API. It works in a similar way to sqlite3_value_text(),
  46539. ** except the data returned is in the encoding specified by the second
  46540. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  46541. ** SQLITE_UTF8.
  46542. **
  46543. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  46544. ** If that is the case, then the result must be aligned on an even byte
  46545. ** boundary.
  46546. */
  46547. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  46548. if( !pVal ) return 0;
  46549. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  46550. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  46551. assert( (pVal->flags & MEM_RowSet)==0 );
  46552. if( pVal->flags&MEM_Null ){
  46553. return 0;
  46554. }
  46555. assert( (MEM_Blob>>3) == MEM_Str );
  46556. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  46557. ExpandBlob(pVal);
  46558. if( pVal->flags&MEM_Str ){
  46559. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  46560. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  46561. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  46562. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  46563. return 0;
  46564. }
  46565. }
  46566. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  46567. }else{
  46568. assert( (pVal->flags&MEM_Blob)==0 );
  46569. sqlite3VdbeMemStringify(pVal, enc);
  46570. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  46571. }
  46572. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  46573. || pVal->db->mallocFailed );
  46574. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  46575. return pVal->z;
  46576. }else{
  46577. return 0;
  46578. }
  46579. }
  46580. /*
  46581. ** Create a new sqlite3_value object.
  46582. */
  46583. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  46584. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  46585. if( p ){
  46586. p->flags = MEM_Null;
  46587. p->type = SQLITE_NULL;
  46588. p->db = db;
  46589. }
  46590. return p;
  46591. }
  46592. /*
  46593. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  46594. ** valueNew(). See comments above valueNew() for details.
  46595. */
  46596. struct ValueNewStat4Ctx {
  46597. Parse *pParse;
  46598. Index *pIdx;
  46599. UnpackedRecord **ppRec;
  46600. int iVal;
  46601. };
  46602. /*
  46603. ** Allocate and return a pointer to a new sqlite3_value object. If
  46604. ** the second argument to this function is NULL, the object is allocated
  46605. ** by calling sqlite3ValueNew().
  46606. **
  46607. ** Otherwise, if the second argument is non-zero, then this function is
  46608. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  46609. ** already been allocated, allocate the UnpackedRecord structure that
  46610. ** that function will return to its caller here. Then return a pointer
  46611. ** an sqlite3_value within the UnpackedRecord.a[] array.
  46612. */
  46613. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  46614. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46615. if( p ){
  46616. UnpackedRecord *pRec = p->ppRec[0];
  46617. if( pRec==0 ){
  46618. Index *pIdx = p->pIdx; /* Index being probed */
  46619. int nByte; /* Bytes of space to allocate */
  46620. int i; /* Counter variable */
  46621. int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */
  46622. nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord);
  46623. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  46624. if( pRec ){
  46625. pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx);
  46626. if( pRec->pKeyInfo ){
  46627. assert( pRec->pKeyInfo->nField+1==nCol );
  46628. pRec->pKeyInfo->enc = ENC(db);
  46629. pRec->flags = UNPACKED_PREFIX_MATCH;
  46630. pRec->aMem = (Mem *)&pRec[1];
  46631. for(i=0; i<nCol; i++){
  46632. pRec->aMem[i].flags = MEM_Null;
  46633. pRec->aMem[i].type = SQLITE_NULL;
  46634. pRec->aMem[i].db = db;
  46635. }
  46636. }else{
  46637. sqlite3DbFree(db, pRec);
  46638. pRec = 0;
  46639. }
  46640. }
  46641. if( pRec==0 ) return 0;
  46642. p->ppRec[0] = pRec;
  46643. }
  46644. pRec->nField = p->iVal+1;
  46645. return &pRec->aMem[p->iVal];
  46646. }
  46647. #else
  46648. UNUSED_PARAMETER(p);
  46649. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  46650. return sqlite3ValueNew(db);
  46651. }
  46652. /*
  46653. ** Extract a value from the supplied expression in the manner described
  46654. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  46655. ** using valueNew().
  46656. **
  46657. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  46658. ** has been allocated, it is freed before returning. Or, if pCtx is not
  46659. ** NULL, it is assumed that the caller will free any allocated object
  46660. ** in all cases.
  46661. */
  46662. static int valueFromExpr(
  46663. sqlite3 *db, /* The database connection */
  46664. Expr *pExpr, /* The expression to evaluate */
  46665. u8 enc, /* Encoding to use */
  46666. u8 affinity, /* Affinity to use */
  46667. sqlite3_value **ppVal, /* Write the new value here */
  46668. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  46669. ){
  46670. int op;
  46671. char *zVal = 0;
  46672. sqlite3_value *pVal = 0;
  46673. int negInt = 1;
  46674. const char *zNeg = "";
  46675. int rc = SQLITE_OK;
  46676. if( !pExpr ){
  46677. *ppVal = 0;
  46678. return SQLITE_OK;
  46679. }
  46680. op = pExpr->op;
  46681. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4.
  46682. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  46683. ** when SQLITE_ENABLE_STAT4 is omitted.
  46684. */
  46685. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46686. if( op==TK_REGISTER ) op = pExpr->op2;
  46687. #else
  46688. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  46689. #endif
  46690. /* Handle negative integers in a single step. This is needed in the
  46691. ** case when the value is -9223372036854775808.
  46692. */
  46693. if( op==TK_UMINUS
  46694. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  46695. pExpr = pExpr->pLeft;
  46696. op = pExpr->op;
  46697. negInt = -1;
  46698. zNeg = "-";
  46699. }
  46700. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  46701. pVal = valueNew(db, pCtx);
  46702. if( pVal==0 ) goto no_mem;
  46703. if( ExprHasProperty(pExpr, EP_IntValue) ){
  46704. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  46705. }else{
  46706. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  46707. if( zVal==0 ) goto no_mem;
  46708. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  46709. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  46710. }
  46711. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  46712. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  46713. }else{
  46714. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  46715. }
  46716. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  46717. if( enc!=SQLITE_UTF8 ){
  46718. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  46719. }
  46720. }else if( op==TK_UMINUS ) {
  46721. /* This branch happens for multiple negative signs. Ex: -(-5) */
  46722. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  46723. && pVal!=0
  46724. ){
  46725. sqlite3VdbeMemNumerify(pVal);
  46726. if( pVal->u.i==SMALLEST_INT64 ){
  46727. pVal->flags &= MEM_Int;
  46728. pVal->flags |= MEM_Real;
  46729. pVal->r = (double)LARGEST_INT64;
  46730. }else{
  46731. pVal->u.i = -pVal->u.i;
  46732. }
  46733. pVal->r = -pVal->r;
  46734. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  46735. }
  46736. }else if( op==TK_NULL ){
  46737. pVal = valueNew(db, pCtx);
  46738. if( pVal==0 ) goto no_mem;
  46739. }
  46740. #ifndef SQLITE_OMIT_BLOB_LITERAL
  46741. else if( op==TK_BLOB ){
  46742. int nVal;
  46743. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  46744. assert( pExpr->u.zToken[1]=='\'' );
  46745. pVal = valueNew(db, pCtx);
  46746. if( !pVal ) goto no_mem;
  46747. zVal = &pExpr->u.zToken[2];
  46748. nVal = sqlite3Strlen30(zVal)-1;
  46749. assert( zVal[nVal]=='\'' );
  46750. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  46751. 0, SQLITE_DYNAMIC);
  46752. }
  46753. #endif
  46754. if( pVal ){
  46755. sqlite3VdbeMemStoreType(pVal);
  46756. }
  46757. *ppVal = pVal;
  46758. return rc;
  46759. no_mem:
  46760. db->mallocFailed = 1;
  46761. sqlite3DbFree(db, zVal);
  46762. assert( *ppVal==0 );
  46763. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46764. if( pCtx==0 ) sqlite3ValueFree(pVal);
  46765. #else
  46766. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  46767. #endif
  46768. return SQLITE_NOMEM;
  46769. }
  46770. /*
  46771. ** Create a new sqlite3_value object, containing the value of pExpr.
  46772. **
  46773. ** This only works for very simple expressions that consist of one constant
  46774. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  46775. ** be converted directly into a value, then the value is allocated and
  46776. ** a pointer written to *ppVal. The caller is responsible for deallocating
  46777. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  46778. ** cannot be converted to a value, then *ppVal is set to NULL.
  46779. */
  46780. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  46781. sqlite3 *db, /* The database connection */
  46782. Expr *pExpr, /* The expression to evaluate */
  46783. u8 enc, /* Encoding to use */
  46784. u8 affinity, /* Affinity to use */
  46785. sqlite3_value **ppVal /* Write the new value here */
  46786. ){
  46787. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  46788. }
  46789. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46790. /*
  46791. ** The implementation of the sqlite_record() function. This function accepts
  46792. ** a single argument of any type. The return value is a formatted database
  46793. ** record (a blob) containing the argument value.
  46794. **
  46795. ** This is used to convert the value stored in the 'sample' column of the
  46796. ** sqlite_stat3 table to the record format SQLite uses internally.
  46797. */
  46798. static void recordFunc(
  46799. sqlite3_context *context,
  46800. int argc,
  46801. sqlite3_value **argv
  46802. ){
  46803. const int file_format = 1;
  46804. int iSerial; /* Serial type */
  46805. int nSerial; /* Bytes of space for iSerial as varint */
  46806. int nVal; /* Bytes of space required for argv[0] */
  46807. int nRet;
  46808. sqlite3 *db;
  46809. u8 *aRet;
  46810. UNUSED_PARAMETER( argc );
  46811. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  46812. nSerial = sqlite3VarintLen(iSerial);
  46813. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  46814. db = sqlite3_context_db_handle(context);
  46815. nRet = 1 + nSerial + nVal;
  46816. aRet = sqlite3DbMallocRaw(db, nRet);
  46817. if( aRet==0 ){
  46818. sqlite3_result_error_nomem(context);
  46819. }else{
  46820. aRet[0] = nSerial+1;
  46821. sqlite3PutVarint(&aRet[1], iSerial);
  46822. sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
  46823. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  46824. sqlite3DbFree(db, aRet);
  46825. }
  46826. }
  46827. /*
  46828. ** Register built-in functions used to help read ANALYZE data.
  46829. */
  46830. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  46831. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  46832. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  46833. };
  46834. int i;
  46835. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  46836. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  46837. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  46838. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  46839. }
  46840. }
  46841. /*
  46842. ** This function is used to allocate and populate UnpackedRecord
  46843. ** structures intended to be compared against sample index keys stored
  46844. ** in the sqlite_stat4 table.
  46845. **
  46846. ** A single call to this function attempts to populates field iVal (leftmost
  46847. ** is 0 etc.) of the unpacked record with a value extracted from expression
  46848. ** pExpr. Extraction of values is possible if:
  46849. **
  46850. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  46851. **
  46852. ** * The expression is a bound variable, and this is a reprepare, or
  46853. **
  46854. ** * The sqlite3ValueFromExpr() function is able to extract a value
  46855. ** from the expression (i.e. the expression is a literal value).
  46856. **
  46857. ** If a value can be extracted, the affinity passed as the 5th argument
  46858. ** is applied to it before it is copied into the UnpackedRecord. Output
  46859. ** parameter *pbOk is set to true if a value is extracted, or false
  46860. ** otherwise.
  46861. **
  46862. ** When this function is called, *ppRec must either point to an object
  46863. ** allocated by an earlier call to this function, or must be NULL. If it
  46864. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  46865. ** is allocated (and *ppRec set to point to it) before returning.
  46866. **
  46867. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  46868. ** error if a value cannot be extracted from pExpr. If an error does
  46869. ** occur, an SQLite error code is returned.
  46870. */
  46871. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  46872. Parse *pParse, /* Parse context */
  46873. Index *pIdx, /* Index being probed */
  46874. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  46875. Expr *pExpr, /* The expression to extract a value from */
  46876. u8 affinity, /* Affinity to use */
  46877. int iVal, /* Array element to populate */
  46878. int *pbOk /* OUT: True if value was extracted */
  46879. ){
  46880. int rc = SQLITE_OK;
  46881. sqlite3_value *pVal = 0;
  46882. sqlite3 *db = pParse->db;
  46883. struct ValueNewStat4Ctx alloc;
  46884. alloc.pParse = pParse;
  46885. alloc.pIdx = pIdx;
  46886. alloc.ppRec = ppRec;
  46887. alloc.iVal = iVal;
  46888. /* Skip over any TK_COLLATE nodes */
  46889. pExpr = sqlite3ExprSkipCollate(pExpr);
  46890. if( !pExpr ){
  46891. pVal = valueNew(db, &alloc);
  46892. if( pVal ){
  46893. sqlite3VdbeMemSetNull((Mem*)pVal);
  46894. *pbOk = 1;
  46895. }
  46896. }else if( pExpr->op==TK_VARIABLE
  46897. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  46898. ){
  46899. Vdbe *v;
  46900. int iBindVar = pExpr->iColumn;
  46901. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  46902. if( (v = pParse->pReprepare)!=0 ){
  46903. pVal = valueNew(db, &alloc);
  46904. if( pVal ){
  46905. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  46906. if( rc==SQLITE_OK ){
  46907. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  46908. }
  46909. pVal->db = pParse->db;
  46910. *pbOk = 1;
  46911. sqlite3VdbeMemStoreType((Mem*)pVal);
  46912. }
  46913. }else{
  46914. *pbOk = 0;
  46915. }
  46916. }else{
  46917. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
  46918. *pbOk = (pVal!=0);
  46919. }
  46920. assert( pVal==0 || pVal->db==db );
  46921. return rc;
  46922. }
  46923. /*
  46924. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  46925. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  46926. ** the object.
  46927. */
  46928. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  46929. if( pRec ){
  46930. int i;
  46931. int nCol = pRec->pKeyInfo->nField+1;
  46932. Mem *aMem = pRec->aMem;
  46933. sqlite3 *db = aMem[0].db;
  46934. for(i=0; i<nCol; i++){
  46935. sqlite3DbFree(db, aMem[i].zMalloc);
  46936. }
  46937. sqlite3DbFree(db, pRec->pKeyInfo);
  46938. sqlite3DbFree(db, pRec);
  46939. }
  46940. }
  46941. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  46942. /*
  46943. ** Change the string value of an sqlite3_value object
  46944. */
  46945. SQLITE_PRIVATE void sqlite3ValueSetStr(
  46946. sqlite3_value *v, /* Value to be set */
  46947. int n, /* Length of string z */
  46948. const void *z, /* Text of the new string */
  46949. u8 enc, /* Encoding to use */
  46950. void (*xDel)(void*) /* Destructor for the string */
  46951. ){
  46952. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  46953. }
  46954. /*
  46955. ** Free an sqlite3_value object
  46956. */
  46957. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  46958. if( !v ) return;
  46959. sqlite3VdbeMemRelease((Mem *)v);
  46960. sqlite3DbFree(((Mem*)v)->db, v);
  46961. }
  46962. /*
  46963. ** Return the number of bytes in the sqlite3_value object assuming
  46964. ** that it uses the encoding "enc"
  46965. */
  46966. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  46967. Mem *p = (Mem*)pVal;
  46968. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  46969. if( p->flags & MEM_Zero ){
  46970. return p->n + p->u.nZero;
  46971. }else{
  46972. return p->n;
  46973. }
  46974. }
  46975. return 0;
  46976. }
  46977. /************** End of vdbemem.c *********************************************/
  46978. /************** Begin file vdbeaux.c *****************************************/
  46979. /*
  46980. ** 2003 September 6
  46981. **
  46982. ** The author disclaims copyright to this source code. In place of
  46983. ** a legal notice, here is a blessing:
  46984. **
  46985. ** May you do good and not evil.
  46986. ** May you find forgiveness for yourself and forgive others.
  46987. ** May you share freely, never taking more than you give.
  46988. **
  46989. *************************************************************************
  46990. ** This file contains code used for creating, destroying, and populating
  46991. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  46992. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  46993. ** But that file was getting too big so this subroutines were split out.
  46994. */
  46995. /*
  46996. ** Create a new virtual database engine.
  46997. */
  46998. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  46999. Vdbe *p;
  47000. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  47001. if( p==0 ) return 0;
  47002. p->db = db;
  47003. if( db->pVdbe ){
  47004. db->pVdbe->pPrev = p;
  47005. }
  47006. p->pNext = db->pVdbe;
  47007. p->pPrev = 0;
  47008. db->pVdbe = p;
  47009. p->magic = VDBE_MAGIC_INIT;
  47010. return p;
  47011. }
  47012. /*
  47013. ** Remember the SQL string for a prepared statement.
  47014. */
  47015. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  47016. assert( isPrepareV2==1 || isPrepareV2==0 );
  47017. if( p==0 ) return;
  47018. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  47019. if( !isPrepareV2 ) return;
  47020. #endif
  47021. assert( p->zSql==0 );
  47022. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  47023. p->isPrepareV2 = (u8)isPrepareV2;
  47024. }
  47025. /*
  47026. ** Return the SQL associated with a prepared statement
  47027. */
  47028. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  47029. Vdbe *p = (Vdbe *)pStmt;
  47030. return (p && p->isPrepareV2) ? p->zSql : 0;
  47031. }
  47032. /*
  47033. ** Swap all content between two VDBE structures.
  47034. */
  47035. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  47036. Vdbe tmp, *pTmp;
  47037. char *zTmp;
  47038. tmp = *pA;
  47039. *pA = *pB;
  47040. *pB = tmp;
  47041. pTmp = pA->pNext;
  47042. pA->pNext = pB->pNext;
  47043. pB->pNext = pTmp;
  47044. pTmp = pA->pPrev;
  47045. pA->pPrev = pB->pPrev;
  47046. pB->pPrev = pTmp;
  47047. zTmp = pA->zSql;
  47048. pA->zSql = pB->zSql;
  47049. pB->zSql = zTmp;
  47050. pB->isPrepareV2 = pA->isPrepareV2;
  47051. }
  47052. #ifdef SQLITE_DEBUG
  47053. /*
  47054. ** Turn tracing on or off
  47055. */
  47056. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  47057. p->trace = trace;
  47058. }
  47059. #endif
  47060. /*
  47061. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  47062. ** it was.
  47063. **
  47064. ** If an out-of-memory error occurs while resizing the array, return
  47065. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  47066. ** unchanged (this is so that any opcodes already allocated can be
  47067. ** correctly deallocated along with the rest of the Vdbe).
  47068. */
  47069. static int growOpArray(Vdbe *p){
  47070. VdbeOp *pNew;
  47071. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  47072. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  47073. if( pNew ){
  47074. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  47075. p->aOp = pNew;
  47076. }
  47077. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  47078. }
  47079. /*
  47080. ** Add a new instruction to the list of instructions current in the
  47081. ** VDBE. Return the address of the new instruction.
  47082. **
  47083. ** Parameters:
  47084. **
  47085. ** p Pointer to the VDBE
  47086. **
  47087. ** op The opcode for this instruction
  47088. **
  47089. ** p1, p2, p3 Operands
  47090. **
  47091. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  47092. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  47093. ** operand.
  47094. */
  47095. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  47096. int i;
  47097. VdbeOp *pOp;
  47098. i = p->nOp;
  47099. assert( p->magic==VDBE_MAGIC_INIT );
  47100. assert( op>0 && op<0xff );
  47101. if( p->nOpAlloc<=i ){
  47102. if( growOpArray(p) ){
  47103. return 1;
  47104. }
  47105. }
  47106. p->nOp++;
  47107. pOp = &p->aOp[i];
  47108. pOp->opcode = (u8)op;
  47109. pOp->p5 = 0;
  47110. pOp->p1 = p1;
  47111. pOp->p2 = p2;
  47112. pOp->p3 = p3;
  47113. pOp->p4.p = 0;
  47114. pOp->p4type = P4_NOTUSED;
  47115. #ifdef SQLITE_DEBUG
  47116. pOp->zComment = 0;
  47117. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  47118. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  47119. }
  47120. #endif
  47121. #ifdef VDBE_PROFILE
  47122. pOp->cycles = 0;
  47123. pOp->cnt = 0;
  47124. #endif
  47125. return i;
  47126. }
  47127. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  47128. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  47129. }
  47130. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  47131. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  47132. }
  47133. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  47134. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  47135. }
  47136. /*
  47137. ** Add an opcode that includes the p4 value as a pointer.
  47138. */
  47139. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  47140. Vdbe *p, /* Add the opcode to this VM */
  47141. int op, /* The new opcode */
  47142. int p1, /* The P1 operand */
  47143. int p2, /* The P2 operand */
  47144. int p3, /* The P3 operand */
  47145. const char *zP4, /* The P4 operand */
  47146. int p4type /* P4 operand type */
  47147. ){
  47148. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  47149. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  47150. return addr;
  47151. }
  47152. /*
  47153. ** Add an OP_ParseSchema opcode. This routine is broken out from
  47154. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  47155. ** as having been used.
  47156. **
  47157. ** The zWhere string must have been obtained from sqlite3_malloc().
  47158. ** This routine will take ownership of the allocated memory.
  47159. */
  47160. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  47161. int j;
  47162. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  47163. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  47164. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  47165. }
  47166. /*
  47167. ** Add an opcode that includes the p4 value as an integer.
  47168. */
  47169. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  47170. Vdbe *p, /* Add the opcode to this VM */
  47171. int op, /* The new opcode */
  47172. int p1, /* The P1 operand */
  47173. int p2, /* The P2 operand */
  47174. int p3, /* The P3 operand */
  47175. int p4 /* The P4 operand as an integer */
  47176. ){
  47177. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  47178. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  47179. return addr;
  47180. }
  47181. /*
  47182. ** Create a new symbolic label for an instruction that has yet to be
  47183. ** coded. The symbolic label is really just a negative number. The
  47184. ** label can be used as the P2 value of an operation. Later, when
  47185. ** the label is resolved to a specific address, the VDBE will scan
  47186. ** through its operation list and change all values of P2 which match
  47187. ** the label into the resolved address.
  47188. **
  47189. ** The VDBE knows that a P2 value is a label because labels are
  47190. ** always negative and P2 values are suppose to be non-negative.
  47191. ** Hence, a negative P2 value is a label that has yet to be resolved.
  47192. **
  47193. ** Zero is returned if a malloc() fails.
  47194. */
  47195. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  47196. int i = p->nLabel++;
  47197. assert( p->magic==VDBE_MAGIC_INIT );
  47198. if( (i & (i-1))==0 ){
  47199. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  47200. (i*2+1)*sizeof(p->aLabel[0]));
  47201. }
  47202. if( p->aLabel ){
  47203. p->aLabel[i] = -1;
  47204. }
  47205. return -1-i;
  47206. }
  47207. /*
  47208. ** Resolve label "x" to be the address of the next instruction to
  47209. ** be inserted. The parameter "x" must have been obtained from
  47210. ** a prior call to sqlite3VdbeMakeLabel().
  47211. */
  47212. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  47213. int j = -1-x;
  47214. assert( p->magic==VDBE_MAGIC_INIT );
  47215. assert( j<p->nLabel );
  47216. if( j>=0 && p->aLabel ){
  47217. p->aLabel[j] = p->nOp;
  47218. }
  47219. }
  47220. /*
  47221. ** Mark the VDBE as one that can only be run one time.
  47222. */
  47223. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  47224. p->runOnlyOnce = 1;
  47225. }
  47226. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  47227. /*
  47228. ** The following type and function are used to iterate through all opcodes
  47229. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  47230. ** invoke directly or indirectly. It should be used as follows:
  47231. **
  47232. ** Op *pOp;
  47233. ** VdbeOpIter sIter;
  47234. **
  47235. ** memset(&sIter, 0, sizeof(sIter));
  47236. ** sIter.v = v; // v is of type Vdbe*
  47237. ** while( (pOp = opIterNext(&sIter)) ){
  47238. ** // Do something with pOp
  47239. ** }
  47240. ** sqlite3DbFree(v->db, sIter.apSub);
  47241. **
  47242. */
  47243. typedef struct VdbeOpIter VdbeOpIter;
  47244. struct VdbeOpIter {
  47245. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  47246. SubProgram **apSub; /* Array of subprograms */
  47247. int nSub; /* Number of entries in apSub */
  47248. int iAddr; /* Address of next instruction to return */
  47249. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  47250. };
  47251. static Op *opIterNext(VdbeOpIter *p){
  47252. Vdbe *v = p->v;
  47253. Op *pRet = 0;
  47254. Op *aOp;
  47255. int nOp;
  47256. if( p->iSub<=p->nSub ){
  47257. if( p->iSub==0 ){
  47258. aOp = v->aOp;
  47259. nOp = v->nOp;
  47260. }else{
  47261. aOp = p->apSub[p->iSub-1]->aOp;
  47262. nOp = p->apSub[p->iSub-1]->nOp;
  47263. }
  47264. assert( p->iAddr<nOp );
  47265. pRet = &aOp[p->iAddr];
  47266. p->iAddr++;
  47267. if( p->iAddr==nOp ){
  47268. p->iSub++;
  47269. p->iAddr = 0;
  47270. }
  47271. if( pRet->p4type==P4_SUBPROGRAM ){
  47272. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  47273. int j;
  47274. for(j=0; j<p->nSub; j++){
  47275. if( p->apSub[j]==pRet->p4.pProgram ) break;
  47276. }
  47277. if( j==p->nSub ){
  47278. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  47279. if( !p->apSub ){
  47280. pRet = 0;
  47281. }else{
  47282. p->apSub[p->nSub++] = pRet->p4.pProgram;
  47283. }
  47284. }
  47285. }
  47286. }
  47287. return pRet;
  47288. }
  47289. /*
  47290. ** Check if the program stored in the VM associated with pParse may
  47291. ** throw an ABORT exception (causing the statement, but not entire transaction
  47292. ** to be rolled back). This condition is true if the main program or any
  47293. ** sub-programs contains any of the following:
  47294. **
  47295. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  47296. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  47297. ** * OP_Destroy
  47298. ** * OP_VUpdate
  47299. ** * OP_VRename
  47300. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  47301. **
  47302. ** Then check that the value of Parse.mayAbort is true if an
  47303. ** ABORT may be thrown, or false otherwise. Return true if it does
  47304. ** match, or false otherwise. This function is intended to be used as
  47305. ** part of an assert statement in the compiler. Similar to:
  47306. **
  47307. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  47308. */
  47309. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  47310. int hasAbort = 0;
  47311. Op *pOp;
  47312. VdbeOpIter sIter;
  47313. memset(&sIter, 0, sizeof(sIter));
  47314. sIter.v = v;
  47315. while( (pOp = opIterNext(&sIter))!=0 ){
  47316. int opcode = pOp->opcode;
  47317. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  47318. #ifndef SQLITE_OMIT_FOREIGN_KEY
  47319. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  47320. #endif
  47321. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  47322. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  47323. ){
  47324. hasAbort = 1;
  47325. break;
  47326. }
  47327. }
  47328. sqlite3DbFree(v->db, sIter.apSub);
  47329. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  47330. ** If malloc failed, then the while() loop above may not have iterated
  47331. ** through all opcodes and hasAbort may be set incorrectly. Return
  47332. ** true for this case to prevent the assert() in the callers frame
  47333. ** from failing. */
  47334. return ( v->db->mallocFailed || hasAbort==mayAbort );
  47335. }
  47336. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  47337. /*
  47338. ** Loop through the program looking for P2 values that are negative
  47339. ** on jump instructions. Each such value is a label. Resolve the
  47340. ** label by setting the P2 value to its correct non-zero value.
  47341. **
  47342. ** This routine is called once after all opcodes have been inserted.
  47343. **
  47344. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  47345. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  47346. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  47347. **
  47348. ** The Op.opflags field is set on all opcodes.
  47349. */
  47350. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  47351. int i;
  47352. int nMaxArgs = *pMaxFuncArgs;
  47353. Op *pOp;
  47354. int *aLabel = p->aLabel;
  47355. p->readOnly = 1;
  47356. p->bIsReader = 0;
  47357. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  47358. u8 opcode = pOp->opcode;
  47359. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  47360. ** cases from this switch! */
  47361. switch( opcode ){
  47362. case OP_Function:
  47363. case OP_AggStep: {
  47364. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  47365. break;
  47366. }
  47367. case OP_Transaction: {
  47368. if( pOp->p2!=0 ) p->readOnly = 0;
  47369. /* fall thru */
  47370. }
  47371. case OP_AutoCommit:
  47372. case OP_Savepoint: {
  47373. p->bIsReader = 1;
  47374. break;
  47375. }
  47376. #ifndef SQLITE_OMIT_WAL
  47377. case OP_Checkpoint:
  47378. #endif
  47379. case OP_Vacuum:
  47380. case OP_JournalMode: {
  47381. p->readOnly = 0;
  47382. p->bIsReader = 1;
  47383. break;
  47384. }
  47385. #ifndef SQLITE_OMIT_VIRTUALTABLE
  47386. case OP_VUpdate: {
  47387. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  47388. break;
  47389. }
  47390. case OP_VFilter: {
  47391. int n;
  47392. assert( p->nOp - i >= 3 );
  47393. assert( pOp[-1].opcode==OP_Integer );
  47394. n = pOp[-1].p1;
  47395. if( n>nMaxArgs ) nMaxArgs = n;
  47396. break;
  47397. }
  47398. #endif
  47399. case OP_Next:
  47400. case OP_SorterNext: {
  47401. pOp->p4.xAdvance = sqlite3BtreeNext;
  47402. pOp->p4type = P4_ADVANCE;
  47403. break;
  47404. }
  47405. case OP_Prev: {
  47406. pOp->p4.xAdvance = sqlite3BtreePrevious;
  47407. pOp->p4type = P4_ADVANCE;
  47408. break;
  47409. }
  47410. }
  47411. pOp->opflags = sqlite3OpcodeProperty[opcode];
  47412. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  47413. assert( -1-pOp->p2<p->nLabel );
  47414. pOp->p2 = aLabel[-1-pOp->p2];
  47415. }
  47416. }
  47417. sqlite3DbFree(p->db, p->aLabel);
  47418. p->aLabel = 0;
  47419. *pMaxFuncArgs = nMaxArgs;
  47420. assert( p->bIsReader!=0 || p->btreeMask==0 );
  47421. }
  47422. /*
  47423. ** Return the address of the next instruction to be inserted.
  47424. */
  47425. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  47426. assert( p->magic==VDBE_MAGIC_INIT );
  47427. return p->nOp;
  47428. }
  47429. /*
  47430. ** This function returns a pointer to the array of opcodes associated with
  47431. ** the Vdbe passed as the first argument. It is the callers responsibility
  47432. ** to arrange for the returned array to be eventually freed using the
  47433. ** vdbeFreeOpArray() function.
  47434. **
  47435. ** Before returning, *pnOp is set to the number of entries in the returned
  47436. ** array. Also, *pnMaxArg is set to the larger of its current value and
  47437. ** the number of entries in the Vdbe.apArg[] array required to execute the
  47438. ** returned program.
  47439. */
  47440. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  47441. VdbeOp *aOp = p->aOp;
  47442. assert( aOp && !p->db->mallocFailed );
  47443. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  47444. assert( p->btreeMask==0 );
  47445. resolveP2Values(p, pnMaxArg);
  47446. *pnOp = p->nOp;
  47447. p->aOp = 0;
  47448. return aOp;
  47449. }
  47450. /*
  47451. ** Add a whole list of operations to the operation stack. Return the
  47452. ** address of the first operation added.
  47453. */
  47454. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  47455. int addr;
  47456. assert( p->magic==VDBE_MAGIC_INIT );
  47457. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  47458. return 0;
  47459. }
  47460. addr = p->nOp;
  47461. if( ALWAYS(nOp>0) ){
  47462. int i;
  47463. VdbeOpList const *pIn = aOp;
  47464. for(i=0; i<nOp; i++, pIn++){
  47465. int p2 = pIn->p2;
  47466. VdbeOp *pOut = &p->aOp[i+addr];
  47467. pOut->opcode = pIn->opcode;
  47468. pOut->p1 = pIn->p1;
  47469. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  47470. pOut->p2 = addr + ADDR(p2);
  47471. }else{
  47472. pOut->p2 = p2;
  47473. }
  47474. pOut->p3 = pIn->p3;
  47475. pOut->p4type = P4_NOTUSED;
  47476. pOut->p4.p = 0;
  47477. pOut->p5 = 0;
  47478. #ifdef SQLITE_DEBUG
  47479. pOut->zComment = 0;
  47480. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  47481. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  47482. }
  47483. #endif
  47484. }
  47485. p->nOp += nOp;
  47486. }
  47487. return addr;
  47488. }
  47489. /*
  47490. ** Change the value of the P1 operand for a specific instruction.
  47491. ** This routine is useful when a large program is loaded from a
  47492. ** static array using sqlite3VdbeAddOpList but we want to make a
  47493. ** few minor changes to the program.
  47494. */
  47495. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  47496. assert( p!=0 );
  47497. if( ((u32)p->nOp)>addr ){
  47498. p->aOp[addr].p1 = val;
  47499. }
  47500. }
  47501. /*
  47502. ** Change the value of the P2 operand for a specific instruction.
  47503. ** This routine is useful for setting a jump destination.
  47504. */
  47505. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  47506. assert( p!=0 );
  47507. if( ((u32)p->nOp)>addr ){
  47508. p->aOp[addr].p2 = val;
  47509. }
  47510. }
  47511. /*
  47512. ** Change the value of the P3 operand for a specific instruction.
  47513. */
  47514. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  47515. assert( p!=0 );
  47516. if( ((u32)p->nOp)>addr ){
  47517. p->aOp[addr].p3 = val;
  47518. }
  47519. }
  47520. /*
  47521. ** Change the value of the P5 operand for the most recently
  47522. ** added operation.
  47523. */
  47524. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  47525. assert( p!=0 );
  47526. if( p->aOp ){
  47527. assert( p->nOp>0 );
  47528. p->aOp[p->nOp-1].p5 = val;
  47529. }
  47530. }
  47531. /*
  47532. ** Change the P2 operand of instruction addr so that it points to
  47533. ** the address of the next instruction to be coded.
  47534. */
  47535. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  47536. if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  47537. }
  47538. /*
  47539. ** If the input FuncDef structure is ephemeral, then free it. If
  47540. ** the FuncDef is not ephermal, then do nothing.
  47541. */
  47542. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  47543. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  47544. sqlite3DbFree(db, pDef);
  47545. }
  47546. }
  47547. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  47548. /*
  47549. ** Delete a P4 value if necessary.
  47550. */
  47551. static void freeP4(sqlite3 *db, int p4type, void *p4){
  47552. if( p4 ){
  47553. assert( db );
  47554. switch( p4type ){
  47555. case P4_REAL:
  47556. case P4_INT64:
  47557. case P4_DYNAMIC:
  47558. case P4_KEYINFO:
  47559. case P4_INTARRAY:
  47560. case P4_KEYINFO_HANDOFF: {
  47561. sqlite3DbFree(db, p4);
  47562. break;
  47563. }
  47564. case P4_MPRINTF: {
  47565. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  47566. break;
  47567. }
  47568. case P4_FUNCDEF: {
  47569. freeEphemeralFunction(db, (FuncDef*)p4);
  47570. break;
  47571. }
  47572. case P4_MEM: {
  47573. if( db->pnBytesFreed==0 ){
  47574. sqlite3ValueFree((sqlite3_value*)p4);
  47575. }else{
  47576. Mem *p = (Mem*)p4;
  47577. sqlite3DbFree(db, p->zMalloc);
  47578. sqlite3DbFree(db, p);
  47579. }
  47580. break;
  47581. }
  47582. case P4_VTAB : {
  47583. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  47584. break;
  47585. }
  47586. }
  47587. }
  47588. }
  47589. /*
  47590. ** Free the space allocated for aOp and any p4 values allocated for the
  47591. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  47592. ** nOp entries.
  47593. */
  47594. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  47595. if( aOp ){
  47596. Op *pOp;
  47597. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  47598. freeP4(db, pOp->p4type, pOp->p4.p);
  47599. #ifdef SQLITE_DEBUG
  47600. sqlite3DbFree(db, pOp->zComment);
  47601. #endif
  47602. }
  47603. }
  47604. sqlite3DbFree(db, aOp);
  47605. }
  47606. /*
  47607. ** Link the SubProgram object passed as the second argument into the linked
  47608. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  47609. ** objects when the VM is no longer required.
  47610. */
  47611. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  47612. p->pNext = pVdbe->pProgram;
  47613. pVdbe->pProgram = p;
  47614. }
  47615. /*
  47616. ** Change the opcode at addr into OP_Noop
  47617. */
  47618. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  47619. if( p->aOp ){
  47620. VdbeOp *pOp = &p->aOp[addr];
  47621. sqlite3 *db = p->db;
  47622. freeP4(db, pOp->p4type, pOp->p4.p);
  47623. memset(pOp, 0, sizeof(pOp[0]));
  47624. pOp->opcode = OP_Noop;
  47625. }
  47626. }
  47627. /*
  47628. ** Change the value of the P4 operand for a specific instruction.
  47629. ** This routine is useful when a large program is loaded from a
  47630. ** static array using sqlite3VdbeAddOpList but we want to make a
  47631. ** few minor changes to the program.
  47632. **
  47633. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  47634. ** the string is made into memory obtained from sqlite3_malloc().
  47635. ** A value of n==0 means copy bytes of zP4 up to and including the
  47636. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  47637. **
  47638. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  47639. ** A copy is made of the KeyInfo structure into memory obtained from
  47640. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  47641. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  47642. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  47643. ** caller should not free the allocation, it will be freed when the Vdbe is
  47644. ** finalized.
  47645. **
  47646. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  47647. ** to a string or structure that is guaranteed to exist for the lifetime of
  47648. ** the Vdbe. In these cases we can just copy the pointer.
  47649. **
  47650. ** If addr<0 then change P4 on the most recently inserted instruction.
  47651. */
  47652. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  47653. Op *pOp;
  47654. sqlite3 *db;
  47655. assert( p!=0 );
  47656. db = p->db;
  47657. assert( p->magic==VDBE_MAGIC_INIT );
  47658. if( p->aOp==0 || db->mallocFailed ){
  47659. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  47660. freeP4(db, n, (void*)*(char**)&zP4);
  47661. }
  47662. return;
  47663. }
  47664. assert( p->nOp>0 );
  47665. assert( addr<p->nOp );
  47666. if( addr<0 ){
  47667. addr = p->nOp - 1;
  47668. }
  47669. pOp = &p->aOp[addr];
  47670. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  47671. freeP4(db, pOp->p4type, pOp->p4.p);
  47672. pOp->p4.p = 0;
  47673. if( n==P4_INT32 ){
  47674. /* Note: this cast is safe, because the origin data point was an int
  47675. ** that was cast to a (const char *). */
  47676. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  47677. pOp->p4type = P4_INT32;
  47678. }else if( zP4==0 ){
  47679. pOp->p4.p = 0;
  47680. pOp->p4type = P4_NOTUSED;
  47681. }else if( n==P4_KEYINFO ){
  47682. KeyInfo *pOrig, *pNew;
  47683. pOrig = (KeyInfo*)zP4;
  47684. pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
  47685. if( pNew ){
  47686. memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
  47687. memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
  47688. pOp->p4type = P4_KEYINFO;
  47689. }else{
  47690. p->db->mallocFailed = 1;
  47691. pOp->p4type = P4_NOTUSED;
  47692. }
  47693. }else if( n==P4_KEYINFO_HANDOFF ){
  47694. pOp->p4.p = (void*)zP4;
  47695. pOp->p4type = P4_KEYINFO;
  47696. }else if( n==P4_VTAB ){
  47697. pOp->p4.p = (void*)zP4;
  47698. pOp->p4type = P4_VTAB;
  47699. sqlite3VtabLock((VTable *)zP4);
  47700. assert( ((VTable *)zP4)->db==p->db );
  47701. }else if( n<0 ){
  47702. pOp->p4.p = (void*)zP4;
  47703. pOp->p4type = (signed char)n;
  47704. }else{
  47705. if( n==0 ) n = sqlite3Strlen30(zP4);
  47706. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  47707. pOp->p4type = P4_DYNAMIC;
  47708. }
  47709. }
  47710. #ifndef NDEBUG
  47711. /*
  47712. ** Change the comment on the most recently coded instruction. Or
  47713. ** insert a No-op and add the comment to that new instruction. This
  47714. ** makes the code easier to read during debugging. None of this happens
  47715. ** in a production build.
  47716. */
  47717. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  47718. assert( p->nOp>0 || p->aOp==0 );
  47719. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  47720. if( p->nOp ){
  47721. assert( p->aOp );
  47722. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  47723. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  47724. }
  47725. }
  47726. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  47727. va_list ap;
  47728. if( p ){
  47729. va_start(ap, zFormat);
  47730. vdbeVComment(p, zFormat, ap);
  47731. va_end(ap);
  47732. }
  47733. }
  47734. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  47735. va_list ap;
  47736. if( p ){
  47737. sqlite3VdbeAddOp0(p, OP_Noop);
  47738. va_start(ap, zFormat);
  47739. vdbeVComment(p, zFormat, ap);
  47740. va_end(ap);
  47741. }
  47742. }
  47743. #endif /* NDEBUG */
  47744. /*
  47745. ** Return the opcode for a given address. If the address is -1, then
  47746. ** return the most recently inserted opcode.
  47747. **
  47748. ** If a memory allocation error has occurred prior to the calling of this
  47749. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  47750. ** is readable but not writable, though it is cast to a writable value.
  47751. ** The return of a dummy opcode allows the call to continue functioning
  47752. ** after a OOM fault without having to check to see if the return from
  47753. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  47754. ** dummy will never be written to. This is verified by code inspection and
  47755. ** by running with Valgrind.
  47756. **
  47757. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  47758. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  47759. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  47760. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  47761. ** having to double-check to make sure that the result is non-negative. But
  47762. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  47763. ** check the value of p->nOp-1 before continuing.
  47764. */
  47765. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  47766. /* C89 specifies that the constant "dummy" will be initialized to all
  47767. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  47768. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  47769. assert( p->magic==VDBE_MAGIC_INIT );
  47770. if( addr<0 ){
  47771. #ifdef SQLITE_OMIT_TRACE
  47772. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  47773. #endif
  47774. addr = p->nOp - 1;
  47775. }
  47776. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  47777. if( p->db->mallocFailed ){
  47778. return (VdbeOp*)&dummy;
  47779. }else{
  47780. return &p->aOp[addr];
  47781. }
  47782. }
  47783. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  47784. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  47785. /*
  47786. ** Compute a string that describes the P4 parameter for an opcode.
  47787. ** Use zTemp for any required temporary buffer space.
  47788. */
  47789. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  47790. char *zP4 = zTemp;
  47791. assert( nTemp>=20 );
  47792. switch( pOp->p4type ){
  47793. case P4_KEYINFO_STATIC:
  47794. case P4_KEYINFO: {
  47795. int i, j;
  47796. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  47797. assert( pKeyInfo->aSortOrder!=0 );
  47798. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  47799. i = sqlite3Strlen30(zTemp);
  47800. for(j=0; j<pKeyInfo->nField; j++){
  47801. CollSeq *pColl = pKeyInfo->aColl[j];
  47802. const char *zColl = pColl ? pColl->zName : "nil";
  47803. int n = sqlite3Strlen30(zColl);
  47804. if( i+n>nTemp-6 ){
  47805. memcpy(&zTemp[i],",...",4);
  47806. break;
  47807. }
  47808. zTemp[i++] = ',';
  47809. if( pKeyInfo->aSortOrder[j] ){
  47810. zTemp[i++] = '-';
  47811. }
  47812. memcpy(&zTemp[i], zColl, n+1);
  47813. i += n;
  47814. }
  47815. zTemp[i++] = ')';
  47816. zTemp[i] = 0;
  47817. assert( i<nTemp );
  47818. break;
  47819. }
  47820. case P4_COLLSEQ: {
  47821. CollSeq *pColl = pOp->p4.pColl;
  47822. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  47823. break;
  47824. }
  47825. case P4_FUNCDEF: {
  47826. FuncDef *pDef = pOp->p4.pFunc;
  47827. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  47828. break;
  47829. }
  47830. case P4_INT64: {
  47831. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  47832. break;
  47833. }
  47834. case P4_INT32: {
  47835. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  47836. break;
  47837. }
  47838. case P4_REAL: {
  47839. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  47840. break;
  47841. }
  47842. case P4_MEM: {
  47843. Mem *pMem = pOp->p4.pMem;
  47844. if( pMem->flags & MEM_Str ){
  47845. zP4 = pMem->z;
  47846. }else if( pMem->flags & MEM_Int ){
  47847. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  47848. }else if( pMem->flags & MEM_Real ){
  47849. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  47850. }else if( pMem->flags & MEM_Null ){
  47851. sqlite3_snprintf(nTemp, zTemp, "NULL");
  47852. }else{
  47853. assert( pMem->flags & MEM_Blob );
  47854. zP4 = "(blob)";
  47855. }
  47856. break;
  47857. }
  47858. #ifndef SQLITE_OMIT_VIRTUALTABLE
  47859. case P4_VTAB: {
  47860. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  47861. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  47862. break;
  47863. }
  47864. #endif
  47865. case P4_INTARRAY: {
  47866. sqlite3_snprintf(nTemp, zTemp, "intarray");
  47867. break;
  47868. }
  47869. case P4_SUBPROGRAM: {
  47870. sqlite3_snprintf(nTemp, zTemp, "program");
  47871. break;
  47872. }
  47873. case P4_ADVANCE: {
  47874. zTemp[0] = 0;
  47875. break;
  47876. }
  47877. default: {
  47878. zP4 = pOp->p4.z;
  47879. if( zP4==0 ){
  47880. zP4 = zTemp;
  47881. zTemp[0] = 0;
  47882. }
  47883. }
  47884. }
  47885. assert( zP4!=0 );
  47886. return zP4;
  47887. }
  47888. #endif
  47889. /*
  47890. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  47891. **
  47892. ** The prepared statements need to know in advance the complete set of
  47893. ** attached databases that will be use. A mask of these databases
  47894. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  47895. ** p->btreeMask of databases that will require a lock.
  47896. */
  47897. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  47898. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  47899. assert( i<(int)sizeof(p->btreeMask)*8 );
  47900. p->btreeMask |= ((yDbMask)1)<<i;
  47901. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  47902. p->lockMask |= ((yDbMask)1)<<i;
  47903. }
  47904. }
  47905. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  47906. /*
  47907. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  47908. ** this routine obtains the mutex associated with each BtShared structure
  47909. ** that may be accessed by the VM passed as an argument. In doing so it also
  47910. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  47911. ** that the correct busy-handler callback is invoked if required.
  47912. **
  47913. ** If SQLite is not threadsafe but does support shared-cache mode, then
  47914. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  47915. ** of all of BtShared structures accessible via the database handle
  47916. ** associated with the VM.
  47917. **
  47918. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  47919. ** function is a no-op.
  47920. **
  47921. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  47922. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  47923. ** corresponding to btrees that use shared cache. Then the runtime of
  47924. ** this routine is N*N. But as N is rarely more than 1, this should not
  47925. ** be a problem.
  47926. */
  47927. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  47928. int i;
  47929. yDbMask mask;
  47930. sqlite3 *db;
  47931. Db *aDb;
  47932. int nDb;
  47933. if( p->lockMask==0 ) return; /* The common case */
  47934. db = p->db;
  47935. aDb = db->aDb;
  47936. nDb = db->nDb;
  47937. for(i=0, mask=1; i<nDb; i++, mask += mask){
  47938. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  47939. sqlite3BtreeEnter(aDb[i].pBt);
  47940. }
  47941. }
  47942. }
  47943. #endif
  47944. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  47945. /*
  47946. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  47947. */
  47948. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  47949. int i;
  47950. yDbMask mask;
  47951. sqlite3 *db;
  47952. Db *aDb;
  47953. int nDb;
  47954. if( p->lockMask==0 ) return; /* The common case */
  47955. db = p->db;
  47956. aDb = db->aDb;
  47957. nDb = db->nDb;
  47958. for(i=0, mask=1; i<nDb; i++, mask += mask){
  47959. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  47960. sqlite3BtreeLeave(aDb[i].pBt);
  47961. }
  47962. }
  47963. }
  47964. #endif
  47965. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  47966. /*
  47967. ** Print a single opcode. This routine is used for debugging only.
  47968. */
  47969. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  47970. char *zP4;
  47971. char zPtr[50];
  47972. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  47973. if( pOut==0 ) pOut = stdout;
  47974. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  47975. fprintf(pOut, zFormat1, pc,
  47976. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  47977. #ifdef SQLITE_DEBUG
  47978. pOp->zComment ? pOp->zComment : ""
  47979. #else
  47980. ""
  47981. #endif
  47982. );
  47983. fflush(pOut);
  47984. }
  47985. #endif
  47986. /*
  47987. ** Release an array of N Mem elements
  47988. */
  47989. static void releaseMemArray(Mem *p, int N){
  47990. if( p && N ){
  47991. Mem *pEnd;
  47992. sqlite3 *db = p->db;
  47993. u8 malloc_failed = db->mallocFailed;
  47994. if( db->pnBytesFreed ){
  47995. for(pEnd=&p[N]; p<pEnd; p++){
  47996. sqlite3DbFree(db, p->zMalloc);
  47997. }
  47998. return;
  47999. }
  48000. for(pEnd=&p[N]; p<pEnd; p++){
  48001. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  48002. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  48003. ** that takes advantage of the fact that the memory cell value is
  48004. ** being set to NULL after releasing any dynamic resources.
  48005. **
  48006. ** The justification for duplicating code is that according to
  48007. ** callgrind, this causes a certain test case to hit the CPU 4.7
  48008. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  48009. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  48010. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  48011. ** with no indexes using a single prepared INSERT statement, bind()
  48012. ** and reset(). Inserts are grouped into a transaction.
  48013. */
  48014. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  48015. sqlite3VdbeMemRelease(p);
  48016. }else if( p->zMalloc ){
  48017. sqlite3DbFree(db, p->zMalloc);
  48018. p->zMalloc = 0;
  48019. }
  48020. p->flags = MEM_Invalid;
  48021. }
  48022. db->mallocFailed = malloc_failed;
  48023. }
  48024. }
  48025. /*
  48026. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  48027. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  48028. */
  48029. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  48030. int i;
  48031. Mem *aMem = VdbeFrameMem(p);
  48032. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  48033. for(i=0; i<p->nChildCsr; i++){
  48034. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  48035. }
  48036. releaseMemArray(aMem, p->nChildMem);
  48037. sqlite3DbFree(p->v->db, p);
  48038. }
  48039. #ifndef SQLITE_OMIT_EXPLAIN
  48040. /*
  48041. ** Give a listing of the program in the virtual machine.
  48042. **
  48043. ** The interface is the same as sqlite3VdbeExec(). But instead of
  48044. ** running the code, it invokes the callback once for each instruction.
  48045. ** This feature is used to implement "EXPLAIN".
  48046. **
  48047. ** When p->explain==1, each instruction is listed. When
  48048. ** p->explain==2, only OP_Explain instructions are listed and these
  48049. ** are shown in a different format. p->explain==2 is used to implement
  48050. ** EXPLAIN QUERY PLAN.
  48051. **
  48052. ** When p->explain==1, first the main program is listed, then each of
  48053. ** the trigger subprograms are listed one by one.
  48054. */
  48055. SQLITE_PRIVATE int sqlite3VdbeList(
  48056. Vdbe *p /* The VDBE */
  48057. ){
  48058. int nRow; /* Stop when row count reaches this */
  48059. int nSub = 0; /* Number of sub-vdbes seen so far */
  48060. SubProgram **apSub = 0; /* Array of sub-vdbes */
  48061. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  48062. sqlite3 *db = p->db; /* The database connection */
  48063. int i; /* Loop counter */
  48064. int rc = SQLITE_OK; /* Return code */
  48065. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  48066. assert( p->explain );
  48067. assert( p->magic==VDBE_MAGIC_RUN );
  48068. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  48069. /* Even though this opcode does not use dynamic strings for
  48070. ** the result, result columns may become dynamic if the user calls
  48071. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  48072. */
  48073. releaseMemArray(pMem, 8);
  48074. p->pResultSet = 0;
  48075. if( p->rc==SQLITE_NOMEM ){
  48076. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  48077. ** sqlite3_column_text16() failed. */
  48078. db->mallocFailed = 1;
  48079. return SQLITE_ERROR;
  48080. }
  48081. /* When the number of output rows reaches nRow, that means the
  48082. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  48083. ** nRow is the sum of the number of rows in the main program, plus
  48084. ** the sum of the number of rows in all trigger subprograms encountered
  48085. ** so far. The nRow value will increase as new trigger subprograms are
  48086. ** encountered, but p->pc will eventually catch up to nRow.
  48087. */
  48088. nRow = p->nOp;
  48089. if( p->explain==1 ){
  48090. /* The first 8 memory cells are used for the result set. So we will
  48091. ** commandeer the 9th cell to use as storage for an array of pointers
  48092. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  48093. ** cells. */
  48094. assert( p->nMem>9 );
  48095. pSub = &p->aMem[9];
  48096. if( pSub->flags&MEM_Blob ){
  48097. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  48098. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  48099. nSub = pSub->n/sizeof(Vdbe*);
  48100. apSub = (SubProgram **)pSub->z;
  48101. }
  48102. for(i=0; i<nSub; i++){
  48103. nRow += apSub[i]->nOp;
  48104. }
  48105. }
  48106. do{
  48107. i = p->pc++;
  48108. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  48109. if( i>=nRow ){
  48110. p->rc = SQLITE_OK;
  48111. rc = SQLITE_DONE;
  48112. }else if( db->u1.isInterrupted ){
  48113. p->rc = SQLITE_INTERRUPT;
  48114. rc = SQLITE_ERROR;
  48115. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  48116. }else{
  48117. char *z;
  48118. Op *pOp;
  48119. if( i<p->nOp ){
  48120. /* The output line number is small enough that we are still in the
  48121. ** main program. */
  48122. pOp = &p->aOp[i];
  48123. }else{
  48124. /* We are currently listing subprograms. Figure out which one and
  48125. ** pick up the appropriate opcode. */
  48126. int j;
  48127. i -= p->nOp;
  48128. for(j=0; i>=apSub[j]->nOp; j++){
  48129. i -= apSub[j]->nOp;
  48130. }
  48131. pOp = &apSub[j]->aOp[i];
  48132. }
  48133. if( p->explain==1 ){
  48134. pMem->flags = MEM_Int;
  48135. pMem->type = SQLITE_INTEGER;
  48136. pMem->u.i = i; /* Program counter */
  48137. pMem++;
  48138. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  48139. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  48140. assert( pMem->z!=0 );
  48141. pMem->n = sqlite3Strlen30(pMem->z);
  48142. pMem->type = SQLITE_TEXT;
  48143. pMem->enc = SQLITE_UTF8;
  48144. pMem++;
  48145. /* When an OP_Program opcode is encounter (the only opcode that has
  48146. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  48147. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  48148. ** has not already been seen.
  48149. */
  48150. if( pOp->p4type==P4_SUBPROGRAM ){
  48151. int nByte = (nSub+1)*sizeof(SubProgram*);
  48152. int j;
  48153. for(j=0; j<nSub; j++){
  48154. if( apSub[j]==pOp->p4.pProgram ) break;
  48155. }
  48156. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  48157. apSub = (SubProgram **)pSub->z;
  48158. apSub[nSub++] = pOp->p4.pProgram;
  48159. pSub->flags |= MEM_Blob;
  48160. pSub->n = nSub*sizeof(SubProgram*);
  48161. }
  48162. }
  48163. }
  48164. pMem->flags = MEM_Int;
  48165. pMem->u.i = pOp->p1; /* P1 */
  48166. pMem->type = SQLITE_INTEGER;
  48167. pMem++;
  48168. pMem->flags = MEM_Int;
  48169. pMem->u.i = pOp->p2; /* P2 */
  48170. pMem->type = SQLITE_INTEGER;
  48171. pMem++;
  48172. pMem->flags = MEM_Int;
  48173. pMem->u.i = pOp->p3; /* P3 */
  48174. pMem->type = SQLITE_INTEGER;
  48175. pMem++;
  48176. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  48177. assert( p->db->mallocFailed );
  48178. return SQLITE_ERROR;
  48179. }
  48180. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  48181. z = displayP4(pOp, pMem->z, 32);
  48182. if( z!=pMem->z ){
  48183. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  48184. }else{
  48185. assert( pMem->z!=0 );
  48186. pMem->n = sqlite3Strlen30(pMem->z);
  48187. pMem->enc = SQLITE_UTF8;
  48188. }
  48189. pMem->type = SQLITE_TEXT;
  48190. pMem++;
  48191. if( p->explain==1 ){
  48192. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  48193. assert( p->db->mallocFailed );
  48194. return SQLITE_ERROR;
  48195. }
  48196. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  48197. pMem->n = 2;
  48198. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  48199. pMem->type = SQLITE_TEXT;
  48200. pMem->enc = SQLITE_UTF8;
  48201. pMem++;
  48202. #ifdef SQLITE_DEBUG
  48203. if( pOp->zComment ){
  48204. pMem->flags = MEM_Str|MEM_Term;
  48205. pMem->z = pOp->zComment;
  48206. pMem->n = sqlite3Strlen30(pMem->z);
  48207. pMem->enc = SQLITE_UTF8;
  48208. pMem->type = SQLITE_TEXT;
  48209. }else
  48210. #endif
  48211. {
  48212. pMem->flags = MEM_Null; /* Comment */
  48213. pMem->type = SQLITE_NULL;
  48214. }
  48215. }
  48216. p->nResColumn = 8 - 4*(p->explain-1);
  48217. p->pResultSet = &p->aMem[1];
  48218. p->rc = SQLITE_OK;
  48219. rc = SQLITE_ROW;
  48220. }
  48221. return rc;
  48222. }
  48223. #endif /* SQLITE_OMIT_EXPLAIN */
  48224. #ifdef SQLITE_DEBUG
  48225. /*
  48226. ** Print the SQL that was used to generate a VDBE program.
  48227. */
  48228. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  48229. int nOp = p->nOp;
  48230. VdbeOp *pOp;
  48231. if( nOp<1 ) return;
  48232. pOp = &p->aOp[0];
  48233. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  48234. const char *z = pOp->p4.z;
  48235. while( sqlite3Isspace(*z) ) z++;
  48236. printf("SQL: [%s]\n", z);
  48237. }
  48238. }
  48239. #endif
  48240. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  48241. /*
  48242. ** Print an IOTRACE message showing SQL content.
  48243. */
  48244. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  48245. int nOp = p->nOp;
  48246. VdbeOp *pOp;
  48247. if( sqlite3IoTrace==0 ) return;
  48248. if( nOp<1 ) return;
  48249. pOp = &p->aOp[0];
  48250. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  48251. int i, j;
  48252. char z[1000];
  48253. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  48254. for(i=0; sqlite3Isspace(z[i]); i++){}
  48255. for(j=0; z[i]; i++){
  48256. if( sqlite3Isspace(z[i]) ){
  48257. if( z[i-1]!=' ' ){
  48258. z[j++] = ' ';
  48259. }
  48260. }else{
  48261. z[j++] = z[i];
  48262. }
  48263. }
  48264. z[j] = 0;
  48265. sqlite3IoTrace("SQL %s\n", z);
  48266. }
  48267. }
  48268. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  48269. /*
  48270. ** Allocate space from a fixed size buffer and return a pointer to
  48271. ** that space. If insufficient space is available, return NULL.
  48272. **
  48273. ** The pBuf parameter is the initial value of a pointer which will
  48274. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  48275. ** NULL, it means that memory space has already been allocated and that
  48276. ** this routine should not allocate any new memory. When pBuf is not
  48277. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  48278. ** is NULL.
  48279. **
  48280. ** nByte is the number of bytes of space needed.
  48281. **
  48282. ** *ppFrom points to available space and pEnd points to the end of the
  48283. ** available space. When space is allocated, *ppFrom is advanced past
  48284. ** the end of the allocated space.
  48285. **
  48286. ** *pnByte is a counter of the number of bytes of space that have failed
  48287. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  48288. ** request, then increment *pnByte by the amount of the request.
  48289. */
  48290. static void *allocSpace(
  48291. void *pBuf, /* Where return pointer will be stored */
  48292. int nByte, /* Number of bytes to allocate */
  48293. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  48294. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  48295. int *pnByte /* If allocation cannot be made, increment *pnByte */
  48296. ){
  48297. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  48298. if( pBuf ) return pBuf;
  48299. nByte = ROUND8(nByte);
  48300. if( &(*ppFrom)[nByte] <= pEnd ){
  48301. pBuf = (void*)*ppFrom;
  48302. *ppFrom += nByte;
  48303. }else{
  48304. *pnByte += nByte;
  48305. }
  48306. return pBuf;
  48307. }
  48308. /*
  48309. ** Rewind the VDBE back to the beginning in preparation for
  48310. ** running it.
  48311. */
  48312. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  48313. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  48314. int i;
  48315. #endif
  48316. assert( p!=0 );
  48317. assert( p->magic==VDBE_MAGIC_INIT );
  48318. /* There should be at least one opcode.
  48319. */
  48320. assert( p->nOp>0 );
  48321. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  48322. p->magic = VDBE_MAGIC_RUN;
  48323. #ifdef SQLITE_DEBUG
  48324. for(i=1; i<p->nMem; i++){
  48325. assert( p->aMem[i].db==p->db );
  48326. }
  48327. #endif
  48328. p->pc = -1;
  48329. p->rc = SQLITE_OK;
  48330. p->errorAction = OE_Abort;
  48331. p->magic = VDBE_MAGIC_RUN;
  48332. p->nChange = 0;
  48333. p->cacheCtr = 1;
  48334. p->minWriteFileFormat = 255;
  48335. p->iStatement = 0;
  48336. p->nFkConstraint = 0;
  48337. #ifdef VDBE_PROFILE
  48338. for(i=0; i<p->nOp; i++){
  48339. p->aOp[i].cnt = 0;
  48340. p->aOp[i].cycles = 0;
  48341. }
  48342. #endif
  48343. }
  48344. /*
  48345. ** Prepare a virtual machine for execution for the first time after
  48346. ** creating the virtual machine. This involves things such
  48347. ** as allocating stack space and initializing the program counter.
  48348. ** After the VDBE has be prepped, it can be executed by one or more
  48349. ** calls to sqlite3VdbeExec().
  48350. **
  48351. ** This function may be called exact once on a each virtual machine.
  48352. ** After this routine is called the VM has been "packaged" and is ready
  48353. ** to run. After this routine is called, futher calls to
  48354. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  48355. ** the Vdbe from the Parse object that helped generate it so that the
  48356. ** the Vdbe becomes an independent entity and the Parse object can be
  48357. ** destroyed.
  48358. **
  48359. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  48360. ** to its initial state after it has been run.
  48361. */
  48362. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  48363. Vdbe *p, /* The VDBE */
  48364. Parse *pParse /* Parsing context */
  48365. ){
  48366. sqlite3 *db; /* The database connection */
  48367. int nVar; /* Number of parameters */
  48368. int nMem; /* Number of VM memory registers */
  48369. int nCursor; /* Number of cursors required */
  48370. int nArg; /* Number of arguments in subprograms */
  48371. int nOnce; /* Number of OP_Once instructions */
  48372. int n; /* Loop counter */
  48373. u8 *zCsr; /* Memory available for allocation */
  48374. u8 *zEnd; /* First byte past allocated memory */
  48375. int nByte; /* How much extra memory is needed */
  48376. assert( p!=0 );
  48377. assert( p->nOp>0 );
  48378. assert( pParse!=0 );
  48379. assert( p->magic==VDBE_MAGIC_INIT );
  48380. db = p->db;
  48381. assert( db->mallocFailed==0 );
  48382. nVar = pParse->nVar;
  48383. nMem = pParse->nMem;
  48384. nCursor = pParse->nTab;
  48385. nArg = pParse->nMaxArg;
  48386. nOnce = pParse->nOnce;
  48387. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  48388. /* For each cursor required, also allocate a memory cell. Memory
  48389. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  48390. ** the vdbe program. Instead they are used to allocate space for
  48391. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  48392. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  48393. ** stores the blob of memory associated with cursor 1, etc.
  48394. **
  48395. ** See also: allocateCursor().
  48396. */
  48397. nMem += nCursor;
  48398. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  48399. ** an array to marshal SQL function arguments in.
  48400. */
  48401. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  48402. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  48403. resolveP2Values(p, &nArg);
  48404. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  48405. if( pParse->explain && nMem<10 ){
  48406. nMem = 10;
  48407. }
  48408. memset(zCsr, 0, zEnd-zCsr);
  48409. zCsr += (zCsr - (u8*)0)&7;
  48410. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  48411. p->expired = 0;
  48412. /* Memory for registers, parameters, cursor, etc, is allocated in two
  48413. ** passes. On the first pass, we try to reuse unused space at the
  48414. ** end of the opcode array. If we are unable to satisfy all memory
  48415. ** requirements by reusing the opcode array tail, then the second
  48416. ** pass will fill in the rest using a fresh allocation.
  48417. **
  48418. ** This two-pass approach that reuses as much memory as possible from
  48419. ** the leftover space at the end of the opcode array can significantly
  48420. ** reduce the amount of memory held by a prepared statement.
  48421. */
  48422. do {
  48423. nByte = 0;
  48424. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  48425. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  48426. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  48427. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  48428. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  48429. &zCsr, zEnd, &nByte);
  48430. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  48431. if( nByte ){
  48432. p->pFree = sqlite3DbMallocZero(db, nByte);
  48433. }
  48434. zCsr = p->pFree;
  48435. zEnd = &zCsr[nByte];
  48436. }while( nByte && !db->mallocFailed );
  48437. p->nCursor = nCursor;
  48438. p->nOnceFlag = nOnce;
  48439. if( p->aVar ){
  48440. p->nVar = (ynVar)nVar;
  48441. for(n=0; n<nVar; n++){
  48442. p->aVar[n].flags = MEM_Null;
  48443. p->aVar[n].db = db;
  48444. }
  48445. }
  48446. if( p->azVar ){
  48447. p->nzVar = pParse->nzVar;
  48448. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  48449. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  48450. }
  48451. if( p->aMem ){
  48452. p->aMem--; /* aMem[] goes from 1..nMem */
  48453. p->nMem = nMem; /* not from 0..nMem-1 */
  48454. for(n=1; n<=nMem; n++){
  48455. p->aMem[n].flags = MEM_Invalid;
  48456. p->aMem[n].db = db;
  48457. }
  48458. }
  48459. p->explain = pParse->explain;
  48460. sqlite3VdbeRewind(p);
  48461. }
  48462. /*
  48463. ** Close a VDBE cursor and release all the resources that cursor
  48464. ** happens to hold.
  48465. */
  48466. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  48467. if( pCx==0 ){
  48468. return;
  48469. }
  48470. sqlite3VdbeSorterClose(p->db, pCx);
  48471. if( pCx->pBt ){
  48472. sqlite3BtreeClose(pCx->pBt);
  48473. /* The pCx->pCursor will be close automatically, if it exists, by
  48474. ** the call above. */
  48475. }else if( pCx->pCursor ){
  48476. sqlite3BtreeCloseCursor(pCx->pCursor);
  48477. }
  48478. #ifndef SQLITE_OMIT_VIRTUALTABLE
  48479. if( pCx->pVtabCursor ){
  48480. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  48481. const sqlite3_module *pModule = pCx->pModule;
  48482. p->inVtabMethod = 1;
  48483. pModule->xClose(pVtabCursor);
  48484. p->inVtabMethod = 0;
  48485. }
  48486. #endif
  48487. }
  48488. /*
  48489. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  48490. ** is used, for example, when a trigger sub-program is halted to restore
  48491. ** control to the main program.
  48492. */
  48493. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  48494. Vdbe *v = pFrame->v;
  48495. v->aOnceFlag = pFrame->aOnceFlag;
  48496. v->nOnceFlag = pFrame->nOnceFlag;
  48497. v->aOp = pFrame->aOp;
  48498. v->nOp = pFrame->nOp;
  48499. v->aMem = pFrame->aMem;
  48500. v->nMem = pFrame->nMem;
  48501. v->apCsr = pFrame->apCsr;
  48502. v->nCursor = pFrame->nCursor;
  48503. v->db->lastRowid = pFrame->lastRowid;
  48504. v->nChange = pFrame->nChange;
  48505. return pFrame->pc;
  48506. }
  48507. /*
  48508. ** Close all cursors.
  48509. **
  48510. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  48511. ** cell array. This is necessary as the memory cell array may contain
  48512. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  48513. ** open cursors.
  48514. */
  48515. static void closeAllCursors(Vdbe *p){
  48516. if( p->pFrame ){
  48517. VdbeFrame *pFrame;
  48518. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  48519. sqlite3VdbeFrameRestore(pFrame);
  48520. }
  48521. p->pFrame = 0;
  48522. p->nFrame = 0;
  48523. if( p->apCsr ){
  48524. int i;
  48525. for(i=0; i<p->nCursor; i++){
  48526. VdbeCursor *pC = p->apCsr[i];
  48527. if( pC ){
  48528. sqlite3VdbeFreeCursor(p, pC);
  48529. p->apCsr[i] = 0;
  48530. }
  48531. }
  48532. }
  48533. if( p->aMem ){
  48534. releaseMemArray(&p->aMem[1], p->nMem);
  48535. }
  48536. while( p->pDelFrame ){
  48537. VdbeFrame *pDel = p->pDelFrame;
  48538. p->pDelFrame = pDel->pParent;
  48539. sqlite3VdbeFrameDelete(pDel);
  48540. }
  48541. /* Delete any auxdata allocations made by the VM */
  48542. sqlite3VdbeDeleteAuxData(p, -1, 0);
  48543. assert( p->pAuxData==0 );
  48544. }
  48545. /*
  48546. ** Clean up the VM after execution.
  48547. **
  48548. ** This routine will automatically close any cursors, lists, and/or
  48549. ** sorters that were left open. It also deletes the values of
  48550. ** variables in the aVar[] array.
  48551. */
  48552. static void Cleanup(Vdbe *p){
  48553. sqlite3 *db = p->db;
  48554. #ifdef SQLITE_DEBUG
  48555. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  48556. ** Vdbe.aMem[] arrays have already been cleaned up. */
  48557. int i;
  48558. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  48559. if( p->aMem ){
  48560. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  48561. }
  48562. #endif
  48563. sqlite3DbFree(db, p->zErrMsg);
  48564. p->zErrMsg = 0;
  48565. p->pResultSet = 0;
  48566. }
  48567. /*
  48568. ** Set the number of result columns that will be returned by this SQL
  48569. ** statement. This is now set at compile time, rather than during
  48570. ** execution of the vdbe program so that sqlite3_column_count() can
  48571. ** be called on an SQL statement before sqlite3_step().
  48572. */
  48573. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  48574. Mem *pColName;
  48575. int n;
  48576. sqlite3 *db = p->db;
  48577. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  48578. sqlite3DbFree(db, p->aColName);
  48579. n = nResColumn*COLNAME_N;
  48580. p->nResColumn = (u16)nResColumn;
  48581. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  48582. if( p->aColName==0 ) return;
  48583. while( n-- > 0 ){
  48584. pColName->flags = MEM_Null;
  48585. pColName->db = p->db;
  48586. pColName++;
  48587. }
  48588. }
  48589. /*
  48590. ** Set the name of the idx'th column to be returned by the SQL statement.
  48591. ** zName must be a pointer to a nul terminated string.
  48592. **
  48593. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  48594. **
  48595. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  48596. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  48597. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  48598. */
  48599. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  48600. Vdbe *p, /* Vdbe being configured */
  48601. int idx, /* Index of column zName applies to */
  48602. int var, /* One of the COLNAME_* constants */
  48603. const char *zName, /* Pointer to buffer containing name */
  48604. void (*xDel)(void*) /* Memory management strategy for zName */
  48605. ){
  48606. int rc;
  48607. Mem *pColName;
  48608. assert( idx<p->nResColumn );
  48609. assert( var<COLNAME_N );
  48610. if( p->db->mallocFailed ){
  48611. assert( !zName || xDel!=SQLITE_DYNAMIC );
  48612. return SQLITE_NOMEM;
  48613. }
  48614. assert( p->aColName!=0 );
  48615. pColName = &(p->aColName[idx+var*p->nResColumn]);
  48616. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  48617. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  48618. return rc;
  48619. }
  48620. /*
  48621. ** A read or write transaction may or may not be active on database handle
  48622. ** db. If a transaction is active, commit it. If there is a
  48623. ** write-transaction spanning more than one database file, this routine
  48624. ** takes care of the master journal trickery.
  48625. */
  48626. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  48627. int i;
  48628. int nTrans = 0; /* Number of databases with an active write-transaction */
  48629. int rc = SQLITE_OK;
  48630. int needXcommit = 0;
  48631. #ifdef SQLITE_OMIT_VIRTUALTABLE
  48632. /* With this option, sqlite3VtabSync() is defined to be simply
  48633. ** SQLITE_OK so p is not used.
  48634. */
  48635. UNUSED_PARAMETER(p);
  48636. #endif
  48637. /* Before doing anything else, call the xSync() callback for any
  48638. ** virtual module tables written in this transaction. This has to
  48639. ** be done before determining whether a master journal file is
  48640. ** required, as an xSync() callback may add an attached database
  48641. ** to the transaction.
  48642. */
  48643. rc = sqlite3VtabSync(db, p);
  48644. /* This loop determines (a) if the commit hook should be invoked and
  48645. ** (b) how many database files have open write transactions, not
  48646. ** including the temp database. (b) is important because if more than
  48647. ** one database file has an open write transaction, a master journal
  48648. ** file is required for an atomic commit.
  48649. */
  48650. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48651. Btree *pBt = db->aDb[i].pBt;
  48652. if( sqlite3BtreeIsInTrans(pBt) ){
  48653. needXcommit = 1;
  48654. if( i!=1 ) nTrans++;
  48655. sqlite3BtreeEnter(pBt);
  48656. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  48657. sqlite3BtreeLeave(pBt);
  48658. }
  48659. }
  48660. if( rc!=SQLITE_OK ){
  48661. return rc;
  48662. }
  48663. /* If there are any write-transactions at all, invoke the commit hook */
  48664. if( needXcommit && db->xCommitCallback ){
  48665. rc = db->xCommitCallback(db->pCommitArg);
  48666. if( rc ){
  48667. return SQLITE_CONSTRAINT_COMMITHOOK;
  48668. }
  48669. }
  48670. /* The simple case - no more than one database file (not counting the
  48671. ** TEMP database) has a transaction active. There is no need for the
  48672. ** master-journal.
  48673. **
  48674. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  48675. ** string, it means the main database is :memory: or a temp file. In
  48676. ** that case we do not support atomic multi-file commits, so use the
  48677. ** simple case then too.
  48678. */
  48679. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  48680. || nTrans<=1
  48681. ){
  48682. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48683. Btree *pBt = db->aDb[i].pBt;
  48684. if( pBt ){
  48685. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  48686. }
  48687. }
  48688. /* Do the commit only if all databases successfully complete phase 1.
  48689. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  48690. ** IO error while deleting or truncating a journal file. It is unlikely,
  48691. ** but could happen. In this case abandon processing and return the error.
  48692. */
  48693. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48694. Btree *pBt = db->aDb[i].pBt;
  48695. if( pBt ){
  48696. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  48697. }
  48698. }
  48699. if( rc==SQLITE_OK ){
  48700. sqlite3VtabCommit(db);
  48701. }
  48702. }
  48703. /* The complex case - There is a multi-file write-transaction active.
  48704. ** This requires a master journal file to ensure the transaction is
  48705. ** committed atomicly.
  48706. */
  48707. #ifndef SQLITE_OMIT_DISKIO
  48708. else{
  48709. sqlite3_vfs *pVfs = db->pVfs;
  48710. int needSync = 0;
  48711. char *zMaster = 0; /* File-name for the master journal */
  48712. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  48713. sqlite3_file *pMaster = 0;
  48714. i64 offset = 0;
  48715. int res;
  48716. int retryCount = 0;
  48717. int nMainFile;
  48718. /* Select a master journal file name */
  48719. nMainFile = sqlite3Strlen30(zMainFile);
  48720. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  48721. if( zMaster==0 ) return SQLITE_NOMEM;
  48722. do {
  48723. u32 iRandom;
  48724. if( retryCount ){
  48725. if( retryCount>100 ){
  48726. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  48727. sqlite3OsDelete(pVfs, zMaster, 0);
  48728. break;
  48729. }else if( retryCount==1 ){
  48730. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  48731. }
  48732. }
  48733. retryCount++;
  48734. sqlite3_randomness(sizeof(iRandom), &iRandom);
  48735. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  48736. (iRandom>>8)&0xffffff, iRandom&0xff);
  48737. /* The antipenultimate character of the master journal name must
  48738. ** be "9" to avoid name collisions when using 8+3 filenames. */
  48739. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  48740. sqlite3FileSuffix3(zMainFile, zMaster);
  48741. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  48742. }while( rc==SQLITE_OK && res );
  48743. if( rc==SQLITE_OK ){
  48744. /* Open the master journal. */
  48745. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  48746. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  48747. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  48748. );
  48749. }
  48750. if( rc!=SQLITE_OK ){
  48751. sqlite3DbFree(db, zMaster);
  48752. return rc;
  48753. }
  48754. /* Write the name of each database file in the transaction into the new
  48755. ** master journal file. If an error occurs at this point close
  48756. ** and delete the master journal file. All the individual journal files
  48757. ** still have 'null' as the master journal pointer, so they will roll
  48758. ** back independently if a failure occurs.
  48759. */
  48760. for(i=0; i<db->nDb; i++){
  48761. Btree *pBt = db->aDb[i].pBt;
  48762. if( sqlite3BtreeIsInTrans(pBt) ){
  48763. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  48764. if( zFile==0 ){
  48765. continue; /* Ignore TEMP and :memory: databases */
  48766. }
  48767. assert( zFile[0]!=0 );
  48768. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  48769. needSync = 1;
  48770. }
  48771. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  48772. offset += sqlite3Strlen30(zFile)+1;
  48773. if( rc!=SQLITE_OK ){
  48774. sqlite3OsCloseFree(pMaster);
  48775. sqlite3OsDelete(pVfs, zMaster, 0);
  48776. sqlite3DbFree(db, zMaster);
  48777. return rc;
  48778. }
  48779. }
  48780. }
  48781. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  48782. ** flag is set this is not required.
  48783. */
  48784. if( needSync
  48785. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  48786. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  48787. ){
  48788. sqlite3OsCloseFree(pMaster);
  48789. sqlite3OsDelete(pVfs, zMaster, 0);
  48790. sqlite3DbFree(db, zMaster);
  48791. return rc;
  48792. }
  48793. /* Sync all the db files involved in the transaction. The same call
  48794. ** sets the master journal pointer in each individual journal. If
  48795. ** an error occurs here, do not delete the master journal file.
  48796. **
  48797. ** If the error occurs during the first call to
  48798. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  48799. ** master journal file will be orphaned. But we cannot delete it,
  48800. ** in case the master journal file name was written into the journal
  48801. ** file before the failure occurred.
  48802. */
  48803. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48804. Btree *pBt = db->aDb[i].pBt;
  48805. if( pBt ){
  48806. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  48807. }
  48808. }
  48809. sqlite3OsCloseFree(pMaster);
  48810. assert( rc!=SQLITE_BUSY );
  48811. if( rc!=SQLITE_OK ){
  48812. sqlite3DbFree(db, zMaster);
  48813. return rc;
  48814. }
  48815. /* Delete the master journal file. This commits the transaction. After
  48816. ** doing this the directory is synced again before any individual
  48817. ** transaction files are deleted.
  48818. */
  48819. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  48820. sqlite3DbFree(db, zMaster);
  48821. zMaster = 0;
  48822. if( rc ){
  48823. return rc;
  48824. }
  48825. /* All files and directories have already been synced, so the following
  48826. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  48827. ** deleting or truncating journals. If something goes wrong while
  48828. ** this is happening we don't really care. The integrity of the
  48829. ** transaction is already guaranteed, but some stray 'cold' journals
  48830. ** may be lying around. Returning an error code won't help matters.
  48831. */
  48832. disable_simulated_io_errors();
  48833. sqlite3BeginBenignMalloc();
  48834. for(i=0; i<db->nDb; i++){
  48835. Btree *pBt = db->aDb[i].pBt;
  48836. if( pBt ){
  48837. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  48838. }
  48839. }
  48840. sqlite3EndBenignMalloc();
  48841. enable_simulated_io_errors();
  48842. sqlite3VtabCommit(db);
  48843. }
  48844. #endif
  48845. return rc;
  48846. }
  48847. /*
  48848. ** This routine checks that the sqlite3.nVdbeActive count variable
  48849. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  48850. ** currently active. An assertion fails if the two counts do not match.
  48851. ** This is an internal self-check only - it is not an essential processing
  48852. ** step.
  48853. **
  48854. ** This is a no-op if NDEBUG is defined.
  48855. */
  48856. #ifndef NDEBUG
  48857. static void checkActiveVdbeCnt(sqlite3 *db){
  48858. Vdbe *p;
  48859. int cnt = 0;
  48860. int nWrite = 0;
  48861. int nRead = 0;
  48862. p = db->pVdbe;
  48863. while( p ){
  48864. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  48865. cnt++;
  48866. if( p->readOnly==0 ) nWrite++;
  48867. if( p->bIsReader ) nRead++;
  48868. }
  48869. p = p->pNext;
  48870. }
  48871. assert( cnt==db->nVdbeActive );
  48872. assert( nWrite==db->nVdbeWrite );
  48873. assert( nRead==db->nVdbeRead );
  48874. }
  48875. #else
  48876. #define checkActiveVdbeCnt(x)
  48877. #endif
  48878. /*
  48879. ** If the Vdbe passed as the first argument opened a statement-transaction,
  48880. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  48881. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  48882. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  48883. ** statement transaction is committed.
  48884. **
  48885. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  48886. ** Otherwise SQLITE_OK.
  48887. */
  48888. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  48889. sqlite3 *const db = p->db;
  48890. int rc = SQLITE_OK;
  48891. /* If p->iStatement is greater than zero, then this Vdbe opened a
  48892. ** statement transaction that should be closed here. The only exception
  48893. ** is that an IO error may have occurred, causing an emergency rollback.
  48894. ** In this case (db->nStatement==0), and there is nothing to do.
  48895. */
  48896. if( db->nStatement && p->iStatement ){
  48897. int i;
  48898. const int iSavepoint = p->iStatement-1;
  48899. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  48900. assert( db->nStatement>0 );
  48901. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  48902. for(i=0; i<db->nDb; i++){
  48903. int rc2 = SQLITE_OK;
  48904. Btree *pBt = db->aDb[i].pBt;
  48905. if( pBt ){
  48906. if( eOp==SAVEPOINT_ROLLBACK ){
  48907. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  48908. }
  48909. if( rc2==SQLITE_OK ){
  48910. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  48911. }
  48912. if( rc==SQLITE_OK ){
  48913. rc = rc2;
  48914. }
  48915. }
  48916. }
  48917. db->nStatement--;
  48918. p->iStatement = 0;
  48919. if( rc==SQLITE_OK ){
  48920. if( eOp==SAVEPOINT_ROLLBACK ){
  48921. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  48922. }
  48923. if( rc==SQLITE_OK ){
  48924. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  48925. }
  48926. }
  48927. /* If the statement transaction is being rolled back, also restore the
  48928. ** database handles deferred constraint counter to the value it had when
  48929. ** the statement transaction was opened. */
  48930. if( eOp==SAVEPOINT_ROLLBACK ){
  48931. db->nDeferredCons = p->nStmtDefCons;
  48932. db->nDeferredImmCons = p->nStmtDefImmCons;
  48933. }
  48934. }
  48935. return rc;
  48936. }
  48937. /*
  48938. ** This function is called when a transaction opened by the database
  48939. ** handle associated with the VM passed as an argument is about to be
  48940. ** committed. If there are outstanding deferred foreign key constraint
  48941. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  48942. **
  48943. ** If there are outstanding FK violations and this function returns
  48944. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  48945. ** and write an error message to it. Then return SQLITE_ERROR.
  48946. */
  48947. #ifndef SQLITE_OMIT_FOREIGN_KEY
  48948. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  48949. sqlite3 *db = p->db;
  48950. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  48951. || (!deferred && p->nFkConstraint>0)
  48952. ){
  48953. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  48954. p->errorAction = OE_Abort;
  48955. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  48956. return SQLITE_ERROR;
  48957. }
  48958. return SQLITE_OK;
  48959. }
  48960. #endif
  48961. /*
  48962. ** This routine is called the when a VDBE tries to halt. If the VDBE
  48963. ** has made changes and is in autocommit mode, then commit those
  48964. ** changes. If a rollback is needed, then do the rollback.
  48965. **
  48966. ** This routine is the only way to move the state of a VM from
  48967. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  48968. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  48969. **
  48970. ** Return an error code. If the commit could not complete because of
  48971. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  48972. ** means the close did not happen and needs to be repeated.
  48973. */
  48974. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  48975. int rc; /* Used to store transient return codes */
  48976. sqlite3 *db = p->db;
  48977. /* This function contains the logic that determines if a statement or
  48978. ** transaction will be committed or rolled back as a result of the
  48979. ** execution of this virtual machine.
  48980. **
  48981. ** If any of the following errors occur:
  48982. **
  48983. ** SQLITE_NOMEM
  48984. ** SQLITE_IOERR
  48985. ** SQLITE_FULL
  48986. ** SQLITE_INTERRUPT
  48987. **
  48988. ** Then the internal cache might have been left in an inconsistent
  48989. ** state. We need to rollback the statement transaction, if there is
  48990. ** one, or the complete transaction if there is no statement transaction.
  48991. */
  48992. if( p->db->mallocFailed ){
  48993. p->rc = SQLITE_NOMEM;
  48994. }
  48995. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  48996. closeAllCursors(p);
  48997. if( p->magic!=VDBE_MAGIC_RUN ){
  48998. return SQLITE_OK;
  48999. }
  49000. checkActiveVdbeCnt(db);
  49001. /* No commit or rollback needed if the program never started or if the
  49002. ** SQL statement does not read or write a database file. */
  49003. if( p->pc>=0 && p->bIsReader ){
  49004. int mrc; /* Primary error code from p->rc */
  49005. int eStatementOp = 0;
  49006. int isSpecialError; /* Set to true if a 'special' error */
  49007. /* Lock all btrees used by the statement */
  49008. sqlite3VdbeEnter(p);
  49009. /* Check for one of the special errors */
  49010. mrc = p->rc & 0xff;
  49011. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  49012. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  49013. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  49014. if( isSpecialError ){
  49015. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  49016. ** no rollback is necessary. Otherwise, at least a savepoint
  49017. ** transaction must be rolled back to restore the database to a
  49018. ** consistent state.
  49019. **
  49020. ** Even if the statement is read-only, it is important to perform
  49021. ** a statement or transaction rollback operation. If the error
  49022. ** occurred while writing to the journal, sub-journal or database
  49023. ** file as part of an effort to free up cache space (see function
  49024. ** pagerStress() in pager.c), the rollback is required to restore
  49025. ** the pager to a consistent state.
  49026. */
  49027. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  49028. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  49029. eStatementOp = SAVEPOINT_ROLLBACK;
  49030. }else{
  49031. /* We are forced to roll back the active transaction. Before doing
  49032. ** so, abort any other statements this handle currently has active.
  49033. */
  49034. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49035. sqlite3CloseSavepoints(db);
  49036. db->autoCommit = 1;
  49037. }
  49038. }
  49039. }
  49040. /* Check for immediate foreign key violations. */
  49041. if( p->rc==SQLITE_OK ){
  49042. sqlite3VdbeCheckFk(p, 0);
  49043. }
  49044. /* If the auto-commit flag is set and this is the only active writer
  49045. ** VM, then we do either a commit or rollback of the current transaction.
  49046. **
  49047. ** Note: This block also runs if one of the special errors handled
  49048. ** above has occurred.
  49049. */
  49050. if( !sqlite3VtabInSync(db)
  49051. && db->autoCommit
  49052. && db->nVdbeWrite==(p->readOnly==0)
  49053. ){
  49054. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  49055. rc = sqlite3VdbeCheckFk(p, 1);
  49056. if( rc!=SQLITE_OK ){
  49057. if( NEVER(p->readOnly) ){
  49058. sqlite3VdbeLeave(p);
  49059. return SQLITE_ERROR;
  49060. }
  49061. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  49062. }else{
  49063. /* The auto-commit flag is true, the vdbe program was successful
  49064. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  49065. ** key constraints to hold up the transaction. This means a commit
  49066. ** is required. */
  49067. rc = vdbeCommit(db, p);
  49068. }
  49069. if( rc==SQLITE_BUSY && p->readOnly ){
  49070. sqlite3VdbeLeave(p);
  49071. return SQLITE_BUSY;
  49072. }else if( rc!=SQLITE_OK ){
  49073. p->rc = rc;
  49074. sqlite3RollbackAll(db, SQLITE_OK);
  49075. }else{
  49076. db->nDeferredCons = 0;
  49077. db->nDeferredImmCons = 0;
  49078. db->flags &= ~SQLITE_DeferFKs;
  49079. sqlite3CommitInternalChanges(db);
  49080. }
  49081. }else{
  49082. sqlite3RollbackAll(db, SQLITE_OK);
  49083. }
  49084. db->nStatement = 0;
  49085. }else if( eStatementOp==0 ){
  49086. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  49087. eStatementOp = SAVEPOINT_RELEASE;
  49088. }else if( p->errorAction==OE_Abort ){
  49089. eStatementOp = SAVEPOINT_ROLLBACK;
  49090. }else{
  49091. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49092. sqlite3CloseSavepoints(db);
  49093. db->autoCommit = 1;
  49094. }
  49095. }
  49096. /* If eStatementOp is non-zero, then a statement transaction needs to
  49097. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  49098. ** do so. If this operation returns an error, and the current statement
  49099. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  49100. ** current statement error code.
  49101. */
  49102. if( eStatementOp ){
  49103. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  49104. if( rc ){
  49105. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  49106. p->rc = rc;
  49107. sqlite3DbFree(db, p->zErrMsg);
  49108. p->zErrMsg = 0;
  49109. }
  49110. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49111. sqlite3CloseSavepoints(db);
  49112. db->autoCommit = 1;
  49113. }
  49114. }
  49115. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  49116. ** has been rolled back, update the database connection change-counter.
  49117. */
  49118. if( p->changeCntOn ){
  49119. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  49120. sqlite3VdbeSetChanges(db, p->nChange);
  49121. }else{
  49122. sqlite3VdbeSetChanges(db, 0);
  49123. }
  49124. p->nChange = 0;
  49125. }
  49126. /* Release the locks */
  49127. sqlite3VdbeLeave(p);
  49128. }
  49129. /* We have successfully halted and closed the VM. Record this fact. */
  49130. if( p->pc>=0 ){
  49131. db->nVdbeActive--;
  49132. if( !p->readOnly ) db->nVdbeWrite--;
  49133. if( p->bIsReader ) db->nVdbeRead--;
  49134. assert( db->nVdbeActive>=db->nVdbeRead );
  49135. assert( db->nVdbeRead>=db->nVdbeWrite );
  49136. assert( db->nVdbeWrite>=0 );
  49137. }
  49138. p->magic = VDBE_MAGIC_HALT;
  49139. checkActiveVdbeCnt(db);
  49140. if( p->db->mallocFailed ){
  49141. p->rc = SQLITE_NOMEM;
  49142. }
  49143. /* If the auto-commit flag is set to true, then any locks that were held
  49144. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  49145. ** to invoke any required unlock-notify callbacks.
  49146. */
  49147. if( db->autoCommit ){
  49148. sqlite3ConnectionUnlocked(db);
  49149. }
  49150. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  49151. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  49152. }
  49153. /*
  49154. ** Each VDBE holds the result of the most recent sqlite3_step() call
  49155. ** in p->rc. This routine sets that result back to SQLITE_OK.
  49156. */
  49157. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  49158. p->rc = SQLITE_OK;
  49159. }
  49160. /*
  49161. ** Copy the error code and error message belonging to the VDBE passed
  49162. ** as the first argument to its database handle (so that they will be
  49163. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  49164. **
  49165. ** This function does not clear the VDBE error code or message, just
  49166. ** copies them to the database handle.
  49167. */
  49168. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  49169. sqlite3 *db = p->db;
  49170. int rc = p->rc;
  49171. if( p->zErrMsg ){
  49172. u8 mallocFailed = db->mallocFailed;
  49173. sqlite3BeginBenignMalloc();
  49174. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  49175. sqlite3EndBenignMalloc();
  49176. db->mallocFailed = mallocFailed;
  49177. db->errCode = rc;
  49178. }else{
  49179. sqlite3Error(db, rc, 0);
  49180. }
  49181. return rc;
  49182. }
  49183. #ifdef SQLITE_ENABLE_SQLLOG
  49184. /*
  49185. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  49186. ** invoke it.
  49187. */
  49188. static void vdbeInvokeSqllog(Vdbe *v){
  49189. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  49190. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  49191. assert( v->db->init.busy==0 );
  49192. if( zExpanded ){
  49193. sqlite3GlobalConfig.xSqllog(
  49194. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  49195. );
  49196. sqlite3DbFree(v->db, zExpanded);
  49197. }
  49198. }
  49199. }
  49200. #else
  49201. # define vdbeInvokeSqllog(x)
  49202. #endif
  49203. /*
  49204. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  49205. ** Write any error messages into *pzErrMsg. Return the result code.
  49206. **
  49207. ** After this routine is run, the VDBE should be ready to be executed
  49208. ** again.
  49209. **
  49210. ** To look at it another way, this routine resets the state of the
  49211. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  49212. ** VDBE_MAGIC_INIT.
  49213. */
  49214. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  49215. sqlite3 *db;
  49216. db = p->db;
  49217. /* If the VM did not run to completion or if it encountered an
  49218. ** error, then it might not have been halted properly. So halt
  49219. ** it now.
  49220. */
  49221. sqlite3VdbeHalt(p);
  49222. /* If the VDBE has be run even partially, then transfer the error code
  49223. ** and error message from the VDBE into the main database structure. But
  49224. ** if the VDBE has just been set to run but has not actually executed any
  49225. ** instructions yet, leave the main database error information unchanged.
  49226. */
  49227. if( p->pc>=0 ){
  49228. vdbeInvokeSqllog(p);
  49229. sqlite3VdbeTransferError(p);
  49230. sqlite3DbFree(db, p->zErrMsg);
  49231. p->zErrMsg = 0;
  49232. if( p->runOnlyOnce ) p->expired = 1;
  49233. }else if( p->rc && p->expired ){
  49234. /* The expired flag was set on the VDBE before the first call
  49235. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  49236. ** called), set the database error in this case as well.
  49237. */
  49238. sqlite3Error(db, p->rc, 0);
  49239. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  49240. sqlite3DbFree(db, p->zErrMsg);
  49241. p->zErrMsg = 0;
  49242. }
  49243. /* Reclaim all memory used by the VDBE
  49244. */
  49245. Cleanup(p);
  49246. /* Save profiling information from this VDBE run.
  49247. */
  49248. #ifdef VDBE_PROFILE
  49249. {
  49250. FILE *out = fopen("vdbe_profile.out", "a");
  49251. if( out ){
  49252. int i;
  49253. fprintf(out, "---- ");
  49254. for(i=0; i<p->nOp; i++){
  49255. fprintf(out, "%02x", p->aOp[i].opcode);
  49256. }
  49257. fprintf(out, "\n");
  49258. for(i=0; i<p->nOp; i++){
  49259. fprintf(out, "%6d %10lld %8lld ",
  49260. p->aOp[i].cnt,
  49261. p->aOp[i].cycles,
  49262. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  49263. );
  49264. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  49265. }
  49266. fclose(out);
  49267. }
  49268. }
  49269. #endif
  49270. p->iCurrentTime = 0;
  49271. p->magic = VDBE_MAGIC_INIT;
  49272. return p->rc & db->errMask;
  49273. }
  49274. /*
  49275. ** Clean up and delete a VDBE after execution. Return an integer which is
  49276. ** the result code. Write any error message text into *pzErrMsg.
  49277. */
  49278. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  49279. int rc = SQLITE_OK;
  49280. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  49281. rc = sqlite3VdbeReset(p);
  49282. assert( (rc & p->db->errMask)==rc );
  49283. }
  49284. sqlite3VdbeDelete(p);
  49285. return rc;
  49286. }
  49287. /*
  49288. ** If parameter iOp is less than zero, then invoke the destructor for
  49289. ** all auxiliary data pointers currently cached by the VM passed as
  49290. ** the first argument.
  49291. **
  49292. ** Or, if iOp is greater than or equal to zero, then the destructor is
  49293. ** only invoked for those auxiliary data pointers created by the user
  49294. ** function invoked by the OP_Function opcode at instruction iOp of
  49295. ** VM pVdbe, and only then if:
  49296. **
  49297. ** * the associated function parameter is the 32nd or later (counting
  49298. ** from left to right), or
  49299. **
  49300. ** * the corresponding bit in argument mask is clear (where the first
  49301. ** function parameter corrsponds to bit 0 etc.).
  49302. */
  49303. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  49304. AuxData **pp = &pVdbe->pAuxData;
  49305. while( *pp ){
  49306. AuxData *pAux = *pp;
  49307. if( (iOp<0)
  49308. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
  49309. ){
  49310. if( pAux->xDelete ){
  49311. pAux->xDelete(pAux->pAux);
  49312. }
  49313. *pp = pAux->pNext;
  49314. sqlite3DbFree(pVdbe->db, pAux);
  49315. }else{
  49316. pp= &pAux->pNext;
  49317. }
  49318. }
  49319. }
  49320. /*
  49321. ** Free all memory associated with the Vdbe passed as the second argument,
  49322. ** except for object itself, which is preserved.
  49323. **
  49324. ** The difference between this function and sqlite3VdbeDelete() is that
  49325. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  49326. ** the database connection and frees the object itself.
  49327. */
  49328. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  49329. SubProgram *pSub, *pNext;
  49330. int i;
  49331. assert( p->db==0 || p->db==db );
  49332. releaseMemArray(p->aVar, p->nVar);
  49333. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  49334. for(pSub=p->pProgram; pSub; pSub=pNext){
  49335. pNext = pSub->pNext;
  49336. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  49337. sqlite3DbFree(db, pSub);
  49338. }
  49339. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  49340. vdbeFreeOpArray(db, p->aOp, p->nOp);
  49341. sqlite3DbFree(db, p->aLabel);
  49342. sqlite3DbFree(db, p->aColName);
  49343. sqlite3DbFree(db, p->zSql);
  49344. sqlite3DbFree(db, p->pFree);
  49345. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  49346. sqlite3DbFree(db, p->zExplain);
  49347. sqlite3DbFree(db, p->pExplain);
  49348. #endif
  49349. }
  49350. /*
  49351. ** Delete an entire VDBE.
  49352. */
  49353. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  49354. sqlite3 *db;
  49355. if( NEVER(p==0) ) return;
  49356. db = p->db;
  49357. assert( sqlite3_mutex_held(db->mutex) );
  49358. sqlite3VdbeClearObject(db, p);
  49359. if( p->pPrev ){
  49360. p->pPrev->pNext = p->pNext;
  49361. }else{
  49362. assert( db->pVdbe==p );
  49363. db->pVdbe = p->pNext;
  49364. }
  49365. if( p->pNext ){
  49366. p->pNext->pPrev = p->pPrev;
  49367. }
  49368. p->magic = VDBE_MAGIC_DEAD;
  49369. p->db = 0;
  49370. sqlite3DbFree(db, p);
  49371. }
  49372. /*
  49373. ** Make sure the cursor p is ready to read or write the row to which it
  49374. ** was last positioned. Return an error code if an OOM fault or I/O error
  49375. ** prevents us from positioning the cursor to its correct position.
  49376. **
  49377. ** If a MoveTo operation is pending on the given cursor, then do that
  49378. ** MoveTo now. If no move is pending, check to see if the row has been
  49379. ** deleted out from under the cursor and if it has, mark the row as
  49380. ** a NULL row.
  49381. **
  49382. ** If the cursor is already pointing to the correct row and that row has
  49383. ** not been deleted out from under the cursor, then this routine is a no-op.
  49384. */
  49385. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  49386. if( p->deferredMoveto ){
  49387. int res, rc;
  49388. #ifdef SQLITE_TEST
  49389. extern int sqlite3_search_count;
  49390. #endif
  49391. assert( p->isTable );
  49392. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  49393. if( rc ) return rc;
  49394. p->lastRowid = p->movetoTarget;
  49395. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  49396. p->rowidIsValid = 1;
  49397. #ifdef SQLITE_TEST
  49398. sqlite3_search_count++;
  49399. #endif
  49400. p->deferredMoveto = 0;
  49401. p->cacheStatus = CACHE_STALE;
  49402. }else if( ALWAYS(p->pCursor) ){
  49403. int hasMoved;
  49404. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  49405. if( rc ) return rc;
  49406. if( hasMoved ){
  49407. p->cacheStatus = CACHE_STALE;
  49408. p->nullRow = 1;
  49409. }
  49410. }
  49411. return SQLITE_OK;
  49412. }
  49413. /*
  49414. ** The following functions:
  49415. **
  49416. ** sqlite3VdbeSerialType()
  49417. ** sqlite3VdbeSerialTypeLen()
  49418. ** sqlite3VdbeSerialLen()
  49419. ** sqlite3VdbeSerialPut()
  49420. ** sqlite3VdbeSerialGet()
  49421. **
  49422. ** encapsulate the code that serializes values for storage in SQLite
  49423. ** data and index records. Each serialized value consists of a
  49424. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  49425. ** integer, stored as a varint.
  49426. **
  49427. ** In an SQLite index record, the serial type is stored directly before
  49428. ** the blob of data that it corresponds to. In a table record, all serial
  49429. ** types are stored at the start of the record, and the blobs of data at
  49430. ** the end. Hence these functions allow the caller to handle the
  49431. ** serial-type and data blob separately.
  49432. **
  49433. ** The following table describes the various storage classes for data:
  49434. **
  49435. ** serial type bytes of data type
  49436. ** -------------- --------------- ---------------
  49437. ** 0 0 NULL
  49438. ** 1 1 signed integer
  49439. ** 2 2 signed integer
  49440. ** 3 3 signed integer
  49441. ** 4 4 signed integer
  49442. ** 5 6 signed integer
  49443. ** 6 8 signed integer
  49444. ** 7 8 IEEE float
  49445. ** 8 0 Integer constant 0
  49446. ** 9 0 Integer constant 1
  49447. ** 10,11 reserved for expansion
  49448. ** N>=12 and even (N-12)/2 BLOB
  49449. ** N>=13 and odd (N-13)/2 text
  49450. **
  49451. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  49452. ** of SQLite will not understand those serial types.
  49453. */
  49454. /*
  49455. ** Return the serial-type for the value stored in pMem.
  49456. */
  49457. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  49458. int flags = pMem->flags;
  49459. int n;
  49460. if( flags&MEM_Null ){
  49461. return 0;
  49462. }
  49463. if( flags&MEM_Int ){
  49464. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  49465. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  49466. i64 i = pMem->u.i;
  49467. u64 u;
  49468. if( i<0 ){
  49469. if( i<(-MAX_6BYTE) ) return 6;
  49470. /* Previous test prevents: u = -(-9223372036854775808) */
  49471. u = -i;
  49472. }else{
  49473. u = i;
  49474. }
  49475. if( u<=127 ){
  49476. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  49477. }
  49478. if( u<=32767 ) return 2;
  49479. if( u<=8388607 ) return 3;
  49480. if( u<=2147483647 ) return 4;
  49481. if( u<=MAX_6BYTE ) return 5;
  49482. return 6;
  49483. }
  49484. if( flags&MEM_Real ){
  49485. return 7;
  49486. }
  49487. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  49488. n = pMem->n;
  49489. if( flags & MEM_Zero ){
  49490. n += pMem->u.nZero;
  49491. }
  49492. assert( n>=0 );
  49493. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  49494. }
  49495. /*
  49496. ** Return the length of the data corresponding to the supplied serial-type.
  49497. */
  49498. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  49499. if( serial_type>=12 ){
  49500. return (serial_type-12)/2;
  49501. }else{
  49502. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  49503. return aSize[serial_type];
  49504. }
  49505. }
  49506. /*
  49507. ** If we are on an architecture with mixed-endian floating
  49508. ** points (ex: ARM7) then swap the lower 4 bytes with the
  49509. ** upper 4 bytes. Return the result.
  49510. **
  49511. ** For most architectures, this is a no-op.
  49512. **
  49513. ** (later): It is reported to me that the mixed-endian problem
  49514. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  49515. ** that early versions of GCC stored the two words of a 64-bit
  49516. ** float in the wrong order. And that error has been propagated
  49517. ** ever since. The blame is not necessarily with GCC, though.
  49518. ** GCC might have just copying the problem from a prior compiler.
  49519. ** I am also told that newer versions of GCC that follow a different
  49520. ** ABI get the byte order right.
  49521. **
  49522. ** Developers using SQLite on an ARM7 should compile and run their
  49523. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  49524. ** enabled, some asserts below will ensure that the byte order of
  49525. ** floating point values is correct.
  49526. **
  49527. ** (2007-08-30) Frank van Vugt has studied this problem closely
  49528. ** and has send his findings to the SQLite developers. Frank
  49529. ** writes that some Linux kernels offer floating point hardware
  49530. ** emulation that uses only 32-bit mantissas instead of a full
  49531. ** 48-bits as required by the IEEE standard. (This is the
  49532. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  49533. ** byte swapping becomes very complicated. To avoid problems,
  49534. ** the necessary byte swapping is carried out using a 64-bit integer
  49535. ** rather than a 64-bit float. Frank assures us that the code here
  49536. ** works for him. We, the developers, have no way to independently
  49537. ** verify this, but Frank seems to know what he is talking about
  49538. ** so we trust him.
  49539. */
  49540. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  49541. static u64 floatSwap(u64 in){
  49542. union {
  49543. u64 r;
  49544. u32 i[2];
  49545. } u;
  49546. u32 t;
  49547. u.r = in;
  49548. t = u.i[0];
  49549. u.i[0] = u.i[1];
  49550. u.i[1] = t;
  49551. return u.r;
  49552. }
  49553. # define swapMixedEndianFloat(X) X = floatSwap(X)
  49554. #else
  49555. # define swapMixedEndianFloat(X)
  49556. #endif
  49557. /*
  49558. ** Write the serialized data blob for the value stored in pMem into
  49559. ** buf. It is assumed that the caller has allocated sufficient space.
  49560. ** Return the number of bytes written.
  49561. **
  49562. ** nBuf is the amount of space left in buf[]. nBuf must always be
  49563. ** large enough to hold the entire field. Except, if the field is
  49564. ** a blob with a zero-filled tail, then buf[] might be just the right
  49565. ** size to hold everything except for the zero-filled tail. If buf[]
  49566. ** is only big enough to hold the non-zero prefix, then only write that
  49567. ** prefix into buf[]. But if buf[] is large enough to hold both the
  49568. ** prefix and the tail then write the prefix and set the tail to all
  49569. ** zeros.
  49570. **
  49571. ** Return the number of bytes actually written into buf[]. The number
  49572. ** of bytes in the zero-filled tail is included in the return value only
  49573. ** if those bytes were zeroed in buf[].
  49574. */
  49575. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  49576. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  49577. u32 len;
  49578. /* Integer and Real */
  49579. if( serial_type<=7 && serial_type>0 ){
  49580. u64 v;
  49581. u32 i;
  49582. if( serial_type==7 ){
  49583. assert( sizeof(v)==sizeof(pMem->r) );
  49584. memcpy(&v, &pMem->r, sizeof(v));
  49585. swapMixedEndianFloat(v);
  49586. }else{
  49587. v = pMem->u.i;
  49588. }
  49589. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  49590. assert( len<=(u32)nBuf );
  49591. while( i-- ){
  49592. buf[i] = (u8)(v&0xFF);
  49593. v >>= 8;
  49594. }
  49595. return len;
  49596. }
  49597. /* String or blob */
  49598. if( serial_type>=12 ){
  49599. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  49600. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  49601. assert( pMem->n<=nBuf );
  49602. len = pMem->n;
  49603. memcpy(buf, pMem->z, len);
  49604. if( pMem->flags & MEM_Zero ){
  49605. len += pMem->u.nZero;
  49606. assert( nBuf>=0 );
  49607. if( len > (u32)nBuf ){
  49608. len = (u32)nBuf;
  49609. }
  49610. memset(&buf[pMem->n], 0, len-pMem->n);
  49611. }
  49612. return len;
  49613. }
  49614. /* NULL or constants 0 or 1 */
  49615. return 0;
  49616. }
  49617. /*
  49618. ** Deserialize the data blob pointed to by buf as serial type serial_type
  49619. ** and store the result in pMem. Return the number of bytes read.
  49620. */
  49621. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  49622. const unsigned char *buf, /* Buffer to deserialize from */
  49623. u32 serial_type, /* Serial type to deserialize */
  49624. Mem *pMem /* Memory cell to write value into */
  49625. ){
  49626. switch( serial_type ){
  49627. case 10: /* Reserved for future use */
  49628. case 11: /* Reserved for future use */
  49629. case 0: { /* NULL */
  49630. pMem->flags = MEM_Null;
  49631. break;
  49632. }
  49633. case 1: { /* 1-byte signed integer */
  49634. pMem->u.i = (signed char)buf[0];
  49635. pMem->flags = MEM_Int;
  49636. return 1;
  49637. }
  49638. case 2: { /* 2-byte signed integer */
  49639. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  49640. pMem->flags = MEM_Int;
  49641. return 2;
  49642. }
  49643. case 3: { /* 3-byte signed integer */
  49644. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  49645. pMem->flags = MEM_Int;
  49646. return 3;
  49647. }
  49648. case 4: { /* 4-byte signed integer */
  49649. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  49650. pMem->flags = MEM_Int;
  49651. return 4;
  49652. }
  49653. case 5: { /* 6-byte signed integer */
  49654. u64 x = (((signed char)buf[0])<<8) | buf[1];
  49655. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  49656. x = (x<<32) | y;
  49657. pMem->u.i = *(i64*)&x;
  49658. pMem->flags = MEM_Int;
  49659. return 6;
  49660. }
  49661. case 6: /* 8-byte signed integer */
  49662. case 7: { /* IEEE floating point */
  49663. u64 x;
  49664. u32 y;
  49665. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  49666. /* Verify that integers and floating point values use the same
  49667. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  49668. ** defined that 64-bit floating point values really are mixed
  49669. ** endian.
  49670. */
  49671. static const u64 t1 = ((u64)0x3ff00000)<<32;
  49672. static const double r1 = 1.0;
  49673. u64 t2 = t1;
  49674. swapMixedEndianFloat(t2);
  49675. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  49676. #endif
  49677. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  49678. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  49679. x = (x<<32) | y;
  49680. if( serial_type==6 ){
  49681. pMem->u.i = *(i64*)&x;
  49682. pMem->flags = MEM_Int;
  49683. }else{
  49684. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  49685. swapMixedEndianFloat(x);
  49686. memcpy(&pMem->r, &x, sizeof(x));
  49687. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  49688. }
  49689. return 8;
  49690. }
  49691. case 8: /* Integer 0 */
  49692. case 9: { /* Integer 1 */
  49693. pMem->u.i = serial_type-8;
  49694. pMem->flags = MEM_Int;
  49695. return 0;
  49696. }
  49697. default: {
  49698. u32 len = (serial_type-12)/2;
  49699. pMem->z = (char *)buf;
  49700. pMem->n = len;
  49701. pMem->xDel = 0;
  49702. if( serial_type&0x01 ){
  49703. pMem->flags = MEM_Str | MEM_Ephem;
  49704. }else{
  49705. pMem->flags = MEM_Blob | MEM_Ephem;
  49706. }
  49707. return len;
  49708. }
  49709. }
  49710. return 0;
  49711. }
  49712. /*
  49713. ** This routine is used to allocate sufficient space for an UnpackedRecord
  49714. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  49715. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  49716. **
  49717. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  49718. ** the unaligned buffer passed via the second and third arguments (presumably
  49719. ** stack space). If the former, then *ppFree is set to a pointer that should
  49720. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  49721. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  49722. ** before returning.
  49723. **
  49724. ** If an OOM error occurs, NULL is returned.
  49725. */
  49726. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  49727. KeyInfo *pKeyInfo, /* Description of the record */
  49728. char *pSpace, /* Unaligned space available */
  49729. int szSpace, /* Size of pSpace[] in bytes */
  49730. char **ppFree /* OUT: Caller should free this pointer */
  49731. ){
  49732. UnpackedRecord *p; /* Unpacked record to return */
  49733. int nOff; /* Increment pSpace by nOff to align it */
  49734. int nByte; /* Number of bytes required for *p */
  49735. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  49736. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  49737. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  49738. */
  49739. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  49740. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  49741. if( nByte>szSpace+nOff ){
  49742. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  49743. *ppFree = (char *)p;
  49744. if( !p ) return 0;
  49745. }else{
  49746. p = (UnpackedRecord*)&pSpace[nOff];
  49747. *ppFree = 0;
  49748. }
  49749. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  49750. assert( pKeyInfo->aSortOrder!=0 );
  49751. p->pKeyInfo = pKeyInfo;
  49752. p->nField = pKeyInfo->nField + 1;
  49753. return p;
  49754. }
  49755. /*
  49756. ** Given the nKey-byte encoding of a record in pKey[], populate the
  49757. ** UnpackedRecord structure indicated by the fourth argument with the
  49758. ** contents of the decoded record.
  49759. */
  49760. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  49761. KeyInfo *pKeyInfo, /* Information about the record format */
  49762. int nKey, /* Size of the binary record */
  49763. const void *pKey, /* The binary record */
  49764. UnpackedRecord *p /* Populate this structure before returning. */
  49765. ){
  49766. const unsigned char *aKey = (const unsigned char *)pKey;
  49767. int d;
  49768. u32 idx; /* Offset in aKey[] to read from */
  49769. u16 u; /* Unsigned loop counter */
  49770. u32 szHdr;
  49771. Mem *pMem = p->aMem;
  49772. p->flags = 0;
  49773. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  49774. idx = getVarint32(aKey, szHdr);
  49775. d = szHdr;
  49776. u = 0;
  49777. while( idx<szHdr && u<p->nField && d<=nKey ){
  49778. u32 serial_type;
  49779. idx += getVarint32(&aKey[idx], serial_type);
  49780. pMem->enc = pKeyInfo->enc;
  49781. pMem->db = pKeyInfo->db;
  49782. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  49783. pMem->zMalloc = 0;
  49784. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  49785. pMem++;
  49786. u++;
  49787. }
  49788. assert( u<=pKeyInfo->nField + 1 );
  49789. p->nField = u;
  49790. }
  49791. /*
  49792. ** This function compares the two table rows or index records
  49793. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  49794. ** or positive integer if key1 is less than, equal to or
  49795. ** greater than key2. The {nKey1, pKey1} key must be a blob
  49796. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  49797. ** key must be a parsed key such as obtained from
  49798. ** sqlite3VdbeParseRecord.
  49799. **
  49800. ** Key1 and Key2 do not have to contain the same number of fields.
  49801. ** The key with fewer fields is usually compares less than the
  49802. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  49803. ** and the common prefixes are equal, then key1 is less than key2.
  49804. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  49805. ** equal, then the keys are considered to be equal and
  49806. ** the parts beyond the common prefix are ignored.
  49807. */
  49808. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  49809. int nKey1, const void *pKey1, /* Left key */
  49810. UnpackedRecord *pPKey2 /* Right key */
  49811. ){
  49812. u32 d1; /* Offset into aKey[] of next data element */
  49813. u32 idx1; /* Offset into aKey[] of next header element */
  49814. u32 szHdr1; /* Number of bytes in header */
  49815. int i = 0;
  49816. int rc = 0;
  49817. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  49818. KeyInfo *pKeyInfo;
  49819. Mem mem1;
  49820. pKeyInfo = pPKey2->pKeyInfo;
  49821. mem1.enc = pKeyInfo->enc;
  49822. mem1.db = pKeyInfo->db;
  49823. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  49824. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  49825. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  49826. ** We could initialize it, as shown here, to silence those complaints.
  49827. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  49828. ** the unnecessary initialization has a measurable negative performance
  49829. ** impact, since this routine is a very high runner. And so, we choose
  49830. ** to ignore the compiler warnings and leave this variable uninitialized.
  49831. */
  49832. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  49833. idx1 = getVarint32(aKey1, szHdr1);
  49834. d1 = szHdr1;
  49835. assert( pKeyInfo->nField+1>=pPKey2->nField );
  49836. assert( pKeyInfo->aSortOrder!=0 );
  49837. while( idx1<szHdr1 && i<pPKey2->nField ){
  49838. u32 serial_type1;
  49839. /* Read the serial types for the next element in each key. */
  49840. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  49841. /* Verify that there is enough key space remaining to avoid
  49842. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  49843. ** always be greater than or equal to the amount of required key space.
  49844. ** Use that approximation to avoid the more expensive call to
  49845. ** sqlite3VdbeSerialTypeLen() in the common case.
  49846. */
  49847. if( d1+serial_type1+2>(u32)nKey1
  49848. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  49849. ){
  49850. break;
  49851. }
  49852. /* Extract the values to be compared.
  49853. */
  49854. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  49855. /* Do the comparison
  49856. */
  49857. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  49858. if( rc!=0 ){
  49859. assert( mem1.zMalloc==0 ); /* See comment below */
  49860. /* Invert the result if we are using DESC sort order. */
  49861. if( pKeyInfo->aSortOrder[i] ){
  49862. rc = -rc;
  49863. }
  49864. /* If the PREFIX_SEARCH flag is set and all fields except the final
  49865. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  49866. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  49867. ** This is used by the OP_IsUnique opcode.
  49868. */
  49869. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  49870. assert( idx1==szHdr1 && rc );
  49871. assert( mem1.flags & MEM_Int );
  49872. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  49873. pPKey2->rowid = mem1.u.i;
  49874. }
  49875. return rc;
  49876. }
  49877. i++;
  49878. }
  49879. /* No memory allocation is ever used on mem1. Prove this using
  49880. ** the following assert(). If the assert() fails, it indicates a
  49881. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  49882. */
  49883. assert( mem1.zMalloc==0 );
  49884. /* rc==0 here means that one of the keys ran out of fields and
  49885. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  49886. ** flag is set, then break the tie by treating key2 as larger.
  49887. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  49888. ** are considered to be equal. Otherwise, the longer key is the
  49889. ** larger. As it happens, the pPKey2 will always be the longer
  49890. ** if there is a difference.
  49891. */
  49892. assert( rc==0 );
  49893. if( pPKey2->flags & UNPACKED_INCRKEY ){
  49894. rc = -1;
  49895. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  49896. /* Leave rc==0 */
  49897. }else if( idx1<szHdr1 ){
  49898. rc = 1;
  49899. }
  49900. return rc;
  49901. }
  49902. /*
  49903. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  49904. ** Read the rowid (the last field in the record) and store it in *rowid.
  49905. ** Return SQLITE_OK if everything works, or an error code otherwise.
  49906. **
  49907. ** pCur might be pointing to text obtained from a corrupt database file.
  49908. ** So the content cannot be trusted. Do appropriate checks on the content.
  49909. */
  49910. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  49911. i64 nCellKey = 0;
  49912. int rc;
  49913. u32 szHdr; /* Size of the header */
  49914. u32 typeRowid; /* Serial type of the rowid */
  49915. u32 lenRowid; /* Size of the rowid */
  49916. Mem m, v;
  49917. UNUSED_PARAMETER(db);
  49918. /* Get the size of the index entry. Only indices entries of less
  49919. ** than 2GiB are support - anything large must be database corruption.
  49920. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  49921. ** this code can safely assume that nCellKey is 32-bits
  49922. */
  49923. assert( sqlite3BtreeCursorIsValid(pCur) );
  49924. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  49925. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  49926. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  49927. /* Read in the complete content of the index entry */
  49928. memset(&m, 0, sizeof(m));
  49929. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  49930. if( rc ){
  49931. return rc;
  49932. }
  49933. /* The index entry must begin with a header size */
  49934. (void)getVarint32((u8*)m.z, szHdr);
  49935. testcase( szHdr==3 );
  49936. testcase( szHdr==m.n );
  49937. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  49938. goto idx_rowid_corruption;
  49939. }
  49940. /* The last field of the index should be an integer - the ROWID.
  49941. ** Verify that the last entry really is an integer. */
  49942. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  49943. testcase( typeRowid==1 );
  49944. testcase( typeRowid==2 );
  49945. testcase( typeRowid==3 );
  49946. testcase( typeRowid==4 );
  49947. testcase( typeRowid==5 );
  49948. testcase( typeRowid==6 );
  49949. testcase( typeRowid==8 );
  49950. testcase( typeRowid==9 );
  49951. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  49952. goto idx_rowid_corruption;
  49953. }
  49954. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  49955. testcase( (u32)m.n==szHdr+lenRowid );
  49956. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  49957. goto idx_rowid_corruption;
  49958. }
  49959. /* Fetch the integer off the end of the index record */
  49960. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  49961. *rowid = v.u.i;
  49962. sqlite3VdbeMemRelease(&m);
  49963. return SQLITE_OK;
  49964. /* Jump here if database corruption is detected after m has been
  49965. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  49966. idx_rowid_corruption:
  49967. testcase( m.zMalloc!=0 );
  49968. sqlite3VdbeMemRelease(&m);
  49969. return SQLITE_CORRUPT_BKPT;
  49970. }
  49971. /*
  49972. ** Compare the key of the index entry that cursor pC is pointing to against
  49973. ** the key string in pUnpacked. Write into *pRes a number
  49974. ** that is negative, zero, or positive if pC is less than, equal to,
  49975. ** or greater than pUnpacked. Return SQLITE_OK on success.
  49976. **
  49977. ** pUnpacked is either created without a rowid or is truncated so that it
  49978. ** omits the rowid at the end. The rowid at the end of the index entry
  49979. ** is ignored as well. Hence, this routine only compares the prefixes
  49980. ** of the keys prior to the final rowid, not the entire key.
  49981. */
  49982. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  49983. VdbeCursor *pC, /* The cursor to compare against */
  49984. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  49985. int *res /* Write the comparison result here */
  49986. ){
  49987. i64 nCellKey = 0;
  49988. int rc;
  49989. BtCursor *pCur = pC->pCursor;
  49990. Mem m;
  49991. assert( sqlite3BtreeCursorIsValid(pCur) );
  49992. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  49993. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  49994. /* nCellKey will always be between 0 and 0xffffffff because of the say
  49995. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  49996. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  49997. *res = 0;
  49998. return SQLITE_CORRUPT_BKPT;
  49999. }
  50000. memset(&m, 0, sizeof(m));
  50001. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  50002. if( rc ){
  50003. return rc;
  50004. }
  50005. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  50006. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  50007. sqlite3VdbeMemRelease(&m);
  50008. return SQLITE_OK;
  50009. }
  50010. /*
  50011. ** This routine sets the value to be returned by subsequent calls to
  50012. ** sqlite3_changes() on the database handle 'db'.
  50013. */
  50014. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  50015. assert( sqlite3_mutex_held(db->mutex) );
  50016. db->nChange = nChange;
  50017. db->nTotalChange += nChange;
  50018. }
  50019. /*
  50020. ** Set a flag in the vdbe to update the change counter when it is finalised
  50021. ** or reset.
  50022. */
  50023. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  50024. v->changeCntOn = 1;
  50025. }
  50026. /*
  50027. ** Mark every prepared statement associated with a database connection
  50028. ** as expired.
  50029. **
  50030. ** An expired statement means that recompilation of the statement is
  50031. ** recommend. Statements expire when things happen that make their
  50032. ** programs obsolete. Removing user-defined functions or collating
  50033. ** sequences, or changing an authorization function are the types of
  50034. ** things that make prepared statements obsolete.
  50035. */
  50036. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  50037. Vdbe *p;
  50038. for(p = db->pVdbe; p; p=p->pNext){
  50039. p->expired = 1;
  50040. }
  50041. }
  50042. /*
  50043. ** Return the database associated with the Vdbe.
  50044. */
  50045. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  50046. return v->db;
  50047. }
  50048. /*
  50049. ** Return a pointer to an sqlite3_value structure containing the value bound
  50050. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  50051. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  50052. ** constants) to the value before returning it.
  50053. **
  50054. ** The returned value must be freed by the caller using sqlite3ValueFree().
  50055. */
  50056. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  50057. assert( iVar>0 );
  50058. if( v ){
  50059. Mem *pMem = &v->aVar[iVar-1];
  50060. if( 0==(pMem->flags & MEM_Null) ){
  50061. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  50062. if( pRet ){
  50063. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  50064. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  50065. sqlite3VdbeMemStoreType((Mem *)pRet);
  50066. }
  50067. return pRet;
  50068. }
  50069. }
  50070. return 0;
  50071. }
  50072. /*
  50073. ** Configure SQL variable iVar so that binding a new value to it signals
  50074. ** to sqlite3_reoptimize() that re-preparing the statement may result
  50075. ** in a better query plan.
  50076. */
  50077. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  50078. assert( iVar>0 );
  50079. if( iVar>32 ){
  50080. v->expmask = 0xffffffff;
  50081. }else{
  50082. v->expmask |= ((u32)1 << (iVar-1));
  50083. }
  50084. }
  50085. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50086. /*
  50087. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  50088. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  50089. ** in memory obtained from sqlite3DbMalloc).
  50090. */
  50091. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  50092. sqlite3 *db = p->db;
  50093. sqlite3DbFree(db, p->zErrMsg);
  50094. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  50095. sqlite3_free(pVtab->zErrMsg);
  50096. pVtab->zErrMsg = 0;
  50097. }
  50098. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50099. /************** End of vdbeaux.c *********************************************/
  50100. /************** Begin file vdbeapi.c *****************************************/
  50101. /*
  50102. ** 2004 May 26
  50103. **
  50104. ** The author disclaims copyright to this source code. In place of
  50105. ** a legal notice, here is a blessing:
  50106. **
  50107. ** May you do good and not evil.
  50108. ** May you find forgiveness for yourself and forgive others.
  50109. ** May you share freely, never taking more than you give.
  50110. **
  50111. *************************************************************************
  50112. **
  50113. ** This file contains code use to implement APIs that are part of the
  50114. ** VDBE.
  50115. */
  50116. #ifndef SQLITE_OMIT_DEPRECATED
  50117. /*
  50118. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  50119. ** to be recompiled. A statement needs to be recompiled whenever the
  50120. ** execution environment changes in a way that would alter the program
  50121. ** that sqlite3_prepare() generates. For example, if new functions or
  50122. ** collating sequences are registered or if an authorizer function is
  50123. ** added or changed.
  50124. */
  50125. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  50126. Vdbe *p = (Vdbe*)pStmt;
  50127. return p==0 || p->expired;
  50128. }
  50129. #endif
  50130. /*
  50131. ** Check on a Vdbe to make sure it has not been finalized. Log
  50132. ** an error and return true if it has been finalized (or is otherwise
  50133. ** invalid). Return false if it is ok.
  50134. */
  50135. static int vdbeSafety(Vdbe *p){
  50136. if( p->db==0 ){
  50137. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  50138. return 1;
  50139. }else{
  50140. return 0;
  50141. }
  50142. }
  50143. static int vdbeSafetyNotNull(Vdbe *p){
  50144. if( p==0 ){
  50145. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  50146. return 1;
  50147. }else{
  50148. return vdbeSafety(p);
  50149. }
  50150. }
  50151. /*
  50152. ** The following routine destroys a virtual machine that is created by
  50153. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  50154. ** success/failure code that describes the result of executing the virtual
  50155. ** machine.
  50156. **
  50157. ** This routine sets the error code and string returned by
  50158. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  50159. */
  50160. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  50161. int rc;
  50162. if( pStmt==0 ){
  50163. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  50164. ** pointer is a harmless no-op. */
  50165. rc = SQLITE_OK;
  50166. }else{
  50167. Vdbe *v = (Vdbe*)pStmt;
  50168. sqlite3 *db = v->db;
  50169. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  50170. sqlite3_mutex_enter(db->mutex);
  50171. rc = sqlite3VdbeFinalize(v);
  50172. rc = sqlite3ApiExit(db, rc);
  50173. sqlite3LeaveMutexAndCloseZombie(db);
  50174. }
  50175. return rc;
  50176. }
  50177. /*
  50178. ** Terminate the current execution of an SQL statement and reset it
  50179. ** back to its starting state so that it can be reused. A success code from
  50180. ** the prior execution is returned.
  50181. **
  50182. ** This routine sets the error code and string returned by
  50183. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  50184. */
  50185. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  50186. int rc;
  50187. if( pStmt==0 ){
  50188. rc = SQLITE_OK;
  50189. }else{
  50190. Vdbe *v = (Vdbe*)pStmt;
  50191. sqlite3_mutex_enter(v->db->mutex);
  50192. rc = sqlite3VdbeReset(v);
  50193. sqlite3VdbeRewind(v);
  50194. assert( (rc & (v->db->errMask))==rc );
  50195. rc = sqlite3ApiExit(v->db, rc);
  50196. sqlite3_mutex_leave(v->db->mutex);
  50197. }
  50198. return rc;
  50199. }
  50200. /*
  50201. ** Set all the parameters in the compiled SQL statement to NULL.
  50202. */
  50203. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  50204. int i;
  50205. int rc = SQLITE_OK;
  50206. Vdbe *p = (Vdbe*)pStmt;
  50207. #if SQLITE_THREADSAFE
  50208. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  50209. #endif
  50210. sqlite3_mutex_enter(mutex);
  50211. for(i=0; i<p->nVar; i++){
  50212. sqlite3VdbeMemRelease(&p->aVar[i]);
  50213. p->aVar[i].flags = MEM_Null;
  50214. }
  50215. if( p->isPrepareV2 && p->expmask ){
  50216. p->expired = 1;
  50217. }
  50218. sqlite3_mutex_leave(mutex);
  50219. return rc;
  50220. }
  50221. /**************************** sqlite3_value_ *******************************
  50222. ** The following routines extract information from a Mem or sqlite3_value
  50223. ** structure.
  50224. */
  50225. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  50226. Mem *p = (Mem*)pVal;
  50227. if( p->flags & (MEM_Blob|MEM_Str) ){
  50228. sqlite3VdbeMemExpandBlob(p);
  50229. p->flags &= ~MEM_Str;
  50230. p->flags |= MEM_Blob;
  50231. return p->n ? p->z : 0;
  50232. }else{
  50233. return sqlite3_value_text(pVal);
  50234. }
  50235. }
  50236. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  50237. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  50238. }
  50239. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  50240. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  50241. }
  50242. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  50243. return sqlite3VdbeRealValue((Mem*)pVal);
  50244. }
  50245. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  50246. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  50247. }
  50248. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  50249. return sqlite3VdbeIntValue((Mem*)pVal);
  50250. }
  50251. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  50252. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  50253. }
  50254. #ifndef SQLITE_OMIT_UTF16
  50255. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  50256. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  50257. }
  50258. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  50259. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  50260. }
  50261. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  50262. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  50263. }
  50264. #endif /* SQLITE_OMIT_UTF16 */
  50265. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  50266. return pVal->type;
  50267. }
  50268. /**************************** sqlite3_result_ *******************************
  50269. ** The following routines are used by user-defined functions to specify
  50270. ** the function result.
  50271. **
  50272. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  50273. ** result as a string or blob but if the string or blob is too large, it
  50274. ** then sets the error code to SQLITE_TOOBIG
  50275. */
  50276. static void setResultStrOrError(
  50277. sqlite3_context *pCtx, /* Function context */
  50278. const char *z, /* String pointer */
  50279. int n, /* Bytes in string, or negative */
  50280. u8 enc, /* Encoding of z. 0 for BLOBs */
  50281. void (*xDel)(void*) /* Destructor function */
  50282. ){
  50283. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  50284. sqlite3_result_error_toobig(pCtx);
  50285. }
  50286. }
  50287. SQLITE_API void sqlite3_result_blob(
  50288. sqlite3_context *pCtx,
  50289. const void *z,
  50290. int n,
  50291. void (*xDel)(void *)
  50292. ){
  50293. assert( n>=0 );
  50294. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50295. setResultStrOrError(pCtx, z, n, 0, xDel);
  50296. }
  50297. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  50298. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50299. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  50300. }
  50301. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  50302. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50303. pCtx->isError = SQLITE_ERROR;
  50304. pCtx->fErrorOrAux = 1;
  50305. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  50306. }
  50307. #ifndef SQLITE_OMIT_UTF16
  50308. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  50309. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50310. pCtx->isError = SQLITE_ERROR;
  50311. pCtx->fErrorOrAux = 1;
  50312. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  50313. }
  50314. #endif
  50315. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  50316. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50317. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  50318. }
  50319. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  50320. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50321. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  50322. }
  50323. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  50324. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50325. sqlite3VdbeMemSetNull(&pCtx->s);
  50326. }
  50327. SQLITE_API void sqlite3_result_text(
  50328. sqlite3_context *pCtx,
  50329. const char *z,
  50330. int n,
  50331. void (*xDel)(void *)
  50332. ){
  50333. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50334. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  50335. }
  50336. #ifndef SQLITE_OMIT_UTF16
  50337. SQLITE_API void sqlite3_result_text16(
  50338. sqlite3_context *pCtx,
  50339. const void *z,
  50340. int n,
  50341. void (*xDel)(void *)
  50342. ){
  50343. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50344. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  50345. }
  50346. SQLITE_API void sqlite3_result_text16be(
  50347. sqlite3_context *pCtx,
  50348. const void *z,
  50349. int n,
  50350. void (*xDel)(void *)
  50351. ){
  50352. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50353. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  50354. }
  50355. SQLITE_API void sqlite3_result_text16le(
  50356. sqlite3_context *pCtx,
  50357. const void *z,
  50358. int n,
  50359. void (*xDel)(void *)
  50360. ){
  50361. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50362. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  50363. }
  50364. #endif /* SQLITE_OMIT_UTF16 */
  50365. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  50366. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50367. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  50368. }
  50369. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  50370. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50371. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  50372. }
  50373. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  50374. pCtx->isError = errCode;
  50375. pCtx->fErrorOrAux = 1;
  50376. if( pCtx->s.flags & MEM_Null ){
  50377. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  50378. SQLITE_UTF8, SQLITE_STATIC);
  50379. }
  50380. }
  50381. /* Force an SQLITE_TOOBIG error. */
  50382. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  50383. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50384. pCtx->isError = SQLITE_TOOBIG;
  50385. pCtx->fErrorOrAux = 1;
  50386. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  50387. SQLITE_UTF8, SQLITE_STATIC);
  50388. }
  50389. /* An SQLITE_NOMEM error. */
  50390. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  50391. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50392. sqlite3VdbeMemSetNull(&pCtx->s);
  50393. pCtx->isError = SQLITE_NOMEM;
  50394. pCtx->fErrorOrAux = 1;
  50395. pCtx->s.db->mallocFailed = 1;
  50396. }
  50397. /*
  50398. ** This function is called after a transaction has been committed. It
  50399. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  50400. */
  50401. static int doWalCallbacks(sqlite3 *db){
  50402. int rc = SQLITE_OK;
  50403. #ifndef SQLITE_OMIT_WAL
  50404. int i;
  50405. for(i=0; i<db->nDb; i++){
  50406. Btree *pBt = db->aDb[i].pBt;
  50407. if( pBt ){
  50408. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  50409. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  50410. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  50411. }
  50412. }
  50413. }
  50414. #endif
  50415. return rc;
  50416. }
  50417. /*
  50418. ** Execute the statement pStmt, either until a row of data is ready, the
  50419. ** statement is completely executed or an error occurs.
  50420. **
  50421. ** This routine implements the bulk of the logic behind the sqlite_step()
  50422. ** API. The only thing omitted is the automatic recompile if a
  50423. ** schema change has occurred. That detail is handled by the
  50424. ** outer sqlite3_step() wrapper procedure.
  50425. */
  50426. static int sqlite3Step(Vdbe *p){
  50427. sqlite3 *db;
  50428. int rc;
  50429. assert(p);
  50430. if( p->magic!=VDBE_MAGIC_RUN ){
  50431. /* We used to require that sqlite3_reset() be called before retrying
  50432. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  50433. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  50434. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  50435. ** This "automatic-reset" change is not technically an incompatibility,
  50436. ** since any application that receives an SQLITE_MISUSE is broken by
  50437. ** definition.
  50438. **
  50439. ** Nevertheless, some published applications that were originally written
  50440. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  50441. ** returns, and those were broken by the automatic-reset change. As a
  50442. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  50443. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  50444. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  50445. ** or SQLITE_BUSY error.
  50446. */
  50447. #ifdef SQLITE_OMIT_AUTORESET
  50448. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  50449. sqlite3_reset((sqlite3_stmt*)p);
  50450. }else{
  50451. return SQLITE_MISUSE_BKPT;
  50452. }
  50453. #else
  50454. sqlite3_reset((sqlite3_stmt*)p);
  50455. #endif
  50456. }
  50457. /* Check that malloc() has not failed. If it has, return early. */
  50458. db = p->db;
  50459. if( db->mallocFailed ){
  50460. p->rc = SQLITE_NOMEM;
  50461. return SQLITE_NOMEM;
  50462. }
  50463. if( p->pc<=0 && p->expired ){
  50464. p->rc = SQLITE_SCHEMA;
  50465. rc = SQLITE_ERROR;
  50466. goto end_of_step;
  50467. }
  50468. if( p->pc<0 ){
  50469. /* If there are no other statements currently running, then
  50470. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  50471. ** from interrupting a statement that has not yet started.
  50472. */
  50473. if( db->nVdbeActive==0 ){
  50474. db->u1.isInterrupted = 0;
  50475. }
  50476. assert( db->nVdbeWrite>0 || db->autoCommit==0
  50477. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  50478. );
  50479. #ifndef SQLITE_OMIT_TRACE
  50480. if( db->xProfile && !db->init.busy ){
  50481. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  50482. }
  50483. #endif
  50484. db->nVdbeActive++;
  50485. if( p->readOnly==0 ) db->nVdbeWrite++;
  50486. if( p->bIsReader ) db->nVdbeRead++;
  50487. p->pc = 0;
  50488. }
  50489. #ifndef SQLITE_OMIT_EXPLAIN
  50490. if( p->explain ){
  50491. rc = sqlite3VdbeList(p);
  50492. }else
  50493. #endif /* SQLITE_OMIT_EXPLAIN */
  50494. {
  50495. db->nVdbeExec++;
  50496. rc = sqlite3VdbeExec(p);
  50497. db->nVdbeExec--;
  50498. }
  50499. #ifndef SQLITE_OMIT_TRACE
  50500. /* Invoke the profile callback if there is one
  50501. */
  50502. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  50503. sqlite3_int64 iNow;
  50504. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  50505. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  50506. }
  50507. #endif
  50508. if( rc==SQLITE_DONE ){
  50509. assert( p->rc==SQLITE_OK );
  50510. p->rc = doWalCallbacks(db);
  50511. if( p->rc!=SQLITE_OK ){
  50512. rc = SQLITE_ERROR;
  50513. }
  50514. }
  50515. db->errCode = rc;
  50516. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  50517. p->rc = SQLITE_NOMEM;
  50518. }
  50519. end_of_step:
  50520. /* At this point local variable rc holds the value that should be
  50521. ** returned if this statement was compiled using the legacy
  50522. ** sqlite3_prepare() interface. According to the docs, this can only
  50523. ** be one of the values in the first assert() below. Variable p->rc
  50524. ** contains the value that would be returned if sqlite3_finalize()
  50525. ** were called on statement p.
  50526. */
  50527. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  50528. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  50529. );
  50530. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  50531. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  50532. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  50533. ** error has occurred, then return the error code in p->rc to the
  50534. ** caller. Set the error code in the database handle to the same value.
  50535. */
  50536. rc = sqlite3VdbeTransferError(p);
  50537. }
  50538. return (rc&db->errMask);
  50539. }
  50540. /*
  50541. ** This is the top-level implementation of sqlite3_step(). Call
  50542. ** sqlite3Step() to do most of the work. If a schema error occurs,
  50543. ** call sqlite3Reprepare() and try again.
  50544. */
  50545. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  50546. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  50547. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  50548. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  50549. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  50550. sqlite3 *db; /* The database connection */
  50551. if( vdbeSafetyNotNull(v) ){
  50552. return SQLITE_MISUSE_BKPT;
  50553. }
  50554. db = v->db;
  50555. sqlite3_mutex_enter(db->mutex);
  50556. v->doingRerun = 0;
  50557. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  50558. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  50559. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  50560. sqlite3_reset(pStmt);
  50561. v->doingRerun = 1;
  50562. assert( v->expired==0 );
  50563. }
  50564. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  50565. /* This case occurs after failing to recompile an sql statement.
  50566. ** The error message from the SQL compiler has already been loaded
  50567. ** into the database handle. This block copies the error message
  50568. ** from the database handle into the statement and sets the statement
  50569. ** program counter to 0 to ensure that when the statement is
  50570. ** finalized or reset the parser error message is available via
  50571. ** sqlite3_errmsg() and sqlite3_errcode().
  50572. */
  50573. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  50574. sqlite3DbFree(db, v->zErrMsg);
  50575. if( !db->mallocFailed ){
  50576. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  50577. v->rc = rc2;
  50578. } else {
  50579. v->zErrMsg = 0;
  50580. v->rc = rc = SQLITE_NOMEM;
  50581. }
  50582. }
  50583. rc = sqlite3ApiExit(db, rc);
  50584. sqlite3_mutex_leave(db->mutex);
  50585. return rc;
  50586. }
  50587. /*
  50588. ** Extract the user data from a sqlite3_context structure and return a
  50589. ** pointer to it.
  50590. */
  50591. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  50592. assert( p && p->pFunc );
  50593. return p->pFunc->pUserData;
  50594. }
  50595. /*
  50596. ** Extract the user data from a sqlite3_context structure and return a
  50597. ** pointer to it.
  50598. **
  50599. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  50600. ** returns a copy of the pointer to the database connection (the 1st
  50601. ** parameter) of the sqlite3_create_function() and
  50602. ** sqlite3_create_function16() routines that originally registered the
  50603. ** application defined function.
  50604. */
  50605. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  50606. assert( p && p->pFunc );
  50607. return p->s.db;
  50608. }
  50609. /*
  50610. ** Return the current time for a statement
  50611. */
  50612. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  50613. Vdbe *v = p->pVdbe;
  50614. int rc;
  50615. if( v->iCurrentTime==0 ){
  50616. rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
  50617. if( rc ) v->iCurrentTime = 0;
  50618. }
  50619. return v->iCurrentTime;
  50620. }
  50621. /*
  50622. ** The following is the implementation of an SQL function that always
  50623. ** fails with an error message stating that the function is used in the
  50624. ** wrong context. The sqlite3_overload_function() API might construct
  50625. ** SQL function that use this routine so that the functions will exist
  50626. ** for name resolution but are actually overloaded by the xFindFunction
  50627. ** method of virtual tables.
  50628. */
  50629. SQLITE_PRIVATE void sqlite3InvalidFunction(
  50630. sqlite3_context *context, /* The function calling context */
  50631. int NotUsed, /* Number of arguments to the function */
  50632. sqlite3_value **NotUsed2 /* Value of each argument */
  50633. ){
  50634. const char *zName = context->pFunc->zName;
  50635. char *zErr;
  50636. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  50637. zErr = sqlite3_mprintf(
  50638. "unable to use function %s in the requested context", zName);
  50639. sqlite3_result_error(context, zErr, -1);
  50640. sqlite3_free(zErr);
  50641. }
  50642. /*
  50643. ** Allocate or return the aggregate context for a user function. A new
  50644. ** context is allocated on the first call. Subsequent calls return the
  50645. ** same context that was returned on prior calls.
  50646. */
  50647. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  50648. Mem *pMem;
  50649. assert( p && p->pFunc && p->pFunc->xStep );
  50650. assert( sqlite3_mutex_held(p->s.db->mutex) );
  50651. pMem = p->pMem;
  50652. testcase( nByte<0 );
  50653. if( (pMem->flags & MEM_Agg)==0 ){
  50654. if( nByte<=0 ){
  50655. sqlite3VdbeMemReleaseExternal(pMem);
  50656. pMem->flags = MEM_Null;
  50657. pMem->z = 0;
  50658. }else{
  50659. sqlite3VdbeMemGrow(pMem, nByte, 0);
  50660. pMem->flags = MEM_Agg;
  50661. pMem->u.pDef = p->pFunc;
  50662. if( pMem->z ){
  50663. memset(pMem->z, 0, nByte);
  50664. }
  50665. }
  50666. }
  50667. return (void*)pMem->z;
  50668. }
  50669. /*
  50670. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  50671. ** the user-function defined by pCtx.
  50672. */
  50673. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  50674. AuxData *pAuxData;
  50675. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50676. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  50677. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  50678. }
  50679. return (pAuxData ? pAuxData->pAux : 0);
  50680. }
  50681. /*
  50682. ** Set the auxilary data pointer and delete function, for the iArg'th
  50683. ** argument to the user-function defined by pCtx. Any previous value is
  50684. ** deleted by calling the delete function specified when it was set.
  50685. */
  50686. SQLITE_API void sqlite3_set_auxdata(
  50687. sqlite3_context *pCtx,
  50688. int iArg,
  50689. void *pAux,
  50690. void (*xDelete)(void*)
  50691. ){
  50692. AuxData *pAuxData;
  50693. Vdbe *pVdbe = pCtx->pVdbe;
  50694. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50695. if( iArg<0 ) goto failed;
  50696. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  50697. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  50698. }
  50699. if( pAuxData==0 ){
  50700. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  50701. if( !pAuxData ) goto failed;
  50702. pAuxData->iOp = pCtx->iOp;
  50703. pAuxData->iArg = iArg;
  50704. pAuxData->pNext = pVdbe->pAuxData;
  50705. pVdbe->pAuxData = pAuxData;
  50706. if( pCtx->fErrorOrAux==0 ){
  50707. pCtx->isError = 0;
  50708. pCtx->fErrorOrAux = 1;
  50709. }
  50710. }else if( pAuxData->xDelete ){
  50711. pAuxData->xDelete(pAuxData->pAux);
  50712. }
  50713. pAuxData->pAux = pAux;
  50714. pAuxData->xDelete = xDelete;
  50715. return;
  50716. failed:
  50717. if( xDelete ){
  50718. xDelete(pAux);
  50719. }
  50720. }
  50721. #ifndef SQLITE_OMIT_DEPRECATED
  50722. /*
  50723. ** Return the number of times the Step function of a aggregate has been
  50724. ** called.
  50725. **
  50726. ** This function is deprecated. Do not use it for new code. It is
  50727. ** provide only to avoid breaking legacy code. New aggregate function
  50728. ** implementations should keep their own counts within their aggregate
  50729. ** context.
  50730. */
  50731. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  50732. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  50733. return p->pMem->n;
  50734. }
  50735. #endif
  50736. /*
  50737. ** Return the number of columns in the result set for the statement pStmt.
  50738. */
  50739. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  50740. Vdbe *pVm = (Vdbe *)pStmt;
  50741. return pVm ? pVm->nResColumn : 0;
  50742. }
  50743. /*
  50744. ** Return the number of values available from the current row of the
  50745. ** currently executing statement pStmt.
  50746. */
  50747. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  50748. Vdbe *pVm = (Vdbe *)pStmt;
  50749. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  50750. return pVm->nResColumn;
  50751. }
  50752. /*
  50753. ** Check to see if column iCol of the given statement is valid. If
  50754. ** it is, return a pointer to the Mem for the value of that column.
  50755. ** If iCol is not valid, return a pointer to a Mem which has a value
  50756. ** of NULL.
  50757. */
  50758. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  50759. Vdbe *pVm;
  50760. Mem *pOut;
  50761. pVm = (Vdbe *)pStmt;
  50762. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  50763. sqlite3_mutex_enter(pVm->db->mutex);
  50764. pOut = &pVm->pResultSet[i];
  50765. }else{
  50766. /* If the value passed as the second argument is out of range, return
  50767. ** a pointer to the following static Mem object which contains the
  50768. ** value SQL NULL. Even though the Mem structure contains an element
  50769. ** of type i64, on certain architectures (x86) with certain compiler
  50770. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  50771. ** instead of an 8-byte one. This all works fine, except that when
  50772. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  50773. ** that a Mem structure is located on an 8-byte boundary. To prevent
  50774. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  50775. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  50776. ** __attribute__((aligned(8))) macro. */
  50777. static const Mem nullMem
  50778. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  50779. __attribute__((aligned(8)))
  50780. #endif
  50781. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  50782. #ifdef SQLITE_DEBUG
  50783. 0, 0, /* pScopyFrom, pFiller */
  50784. #endif
  50785. 0, 0 };
  50786. if( pVm && ALWAYS(pVm->db) ){
  50787. sqlite3_mutex_enter(pVm->db->mutex);
  50788. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  50789. }
  50790. pOut = (Mem*)&nullMem;
  50791. }
  50792. return pOut;
  50793. }
  50794. /*
  50795. ** This function is called after invoking an sqlite3_value_XXX function on a
  50796. ** column value (i.e. a value returned by evaluating an SQL expression in the
  50797. ** select list of a SELECT statement) that may cause a malloc() failure. If
  50798. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  50799. ** code of statement pStmt set to SQLITE_NOMEM.
  50800. **
  50801. ** Specifically, this is called from within:
  50802. **
  50803. ** sqlite3_column_int()
  50804. ** sqlite3_column_int64()
  50805. ** sqlite3_column_text()
  50806. ** sqlite3_column_text16()
  50807. ** sqlite3_column_real()
  50808. ** sqlite3_column_bytes()
  50809. ** sqlite3_column_bytes16()
  50810. ** sqiite3_column_blob()
  50811. */
  50812. static void columnMallocFailure(sqlite3_stmt *pStmt)
  50813. {
  50814. /* If malloc() failed during an encoding conversion within an
  50815. ** sqlite3_column_XXX API, then set the return code of the statement to
  50816. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  50817. ** and _finalize() will return NOMEM.
  50818. */
  50819. Vdbe *p = (Vdbe *)pStmt;
  50820. if( p ){
  50821. p->rc = sqlite3ApiExit(p->db, p->rc);
  50822. sqlite3_mutex_leave(p->db->mutex);
  50823. }
  50824. }
  50825. /**************************** sqlite3_column_ *******************************
  50826. ** The following routines are used to access elements of the current row
  50827. ** in the result set.
  50828. */
  50829. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  50830. const void *val;
  50831. val = sqlite3_value_blob( columnMem(pStmt,i) );
  50832. /* Even though there is no encoding conversion, value_blob() might
  50833. ** need to call malloc() to expand the result of a zeroblob()
  50834. ** expression.
  50835. */
  50836. columnMallocFailure(pStmt);
  50837. return val;
  50838. }
  50839. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  50840. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  50841. columnMallocFailure(pStmt);
  50842. return val;
  50843. }
  50844. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  50845. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  50846. columnMallocFailure(pStmt);
  50847. return val;
  50848. }
  50849. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  50850. double val = sqlite3_value_double( columnMem(pStmt,i) );
  50851. columnMallocFailure(pStmt);
  50852. return val;
  50853. }
  50854. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  50855. int val = sqlite3_value_int( columnMem(pStmt,i) );
  50856. columnMallocFailure(pStmt);
  50857. return val;
  50858. }
  50859. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  50860. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  50861. columnMallocFailure(pStmt);
  50862. return val;
  50863. }
  50864. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  50865. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  50866. columnMallocFailure(pStmt);
  50867. return val;
  50868. }
  50869. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  50870. Mem *pOut = columnMem(pStmt, i);
  50871. if( pOut->flags&MEM_Static ){
  50872. pOut->flags &= ~MEM_Static;
  50873. pOut->flags |= MEM_Ephem;
  50874. }
  50875. columnMallocFailure(pStmt);
  50876. return (sqlite3_value *)pOut;
  50877. }
  50878. #ifndef SQLITE_OMIT_UTF16
  50879. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  50880. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  50881. columnMallocFailure(pStmt);
  50882. return val;
  50883. }
  50884. #endif /* SQLITE_OMIT_UTF16 */
  50885. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  50886. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  50887. columnMallocFailure(pStmt);
  50888. return iType;
  50889. }
  50890. /*
  50891. ** Convert the N-th element of pStmt->pColName[] into a string using
  50892. ** xFunc() then return that string. If N is out of range, return 0.
  50893. **
  50894. ** There are up to 5 names for each column. useType determines which
  50895. ** name is returned. Here are the names:
  50896. **
  50897. ** 0 The column name as it should be displayed for output
  50898. ** 1 The datatype name for the column
  50899. ** 2 The name of the database that the column derives from
  50900. ** 3 The name of the table that the column derives from
  50901. ** 4 The name of the table column that the result column derives from
  50902. **
  50903. ** If the result is not a simple column reference (if it is an expression
  50904. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  50905. */
  50906. static const void *columnName(
  50907. sqlite3_stmt *pStmt,
  50908. int N,
  50909. const void *(*xFunc)(Mem*),
  50910. int useType
  50911. ){
  50912. const void *ret = 0;
  50913. Vdbe *p = (Vdbe *)pStmt;
  50914. int n;
  50915. sqlite3 *db = p->db;
  50916. assert( db!=0 );
  50917. n = sqlite3_column_count(pStmt);
  50918. if( N<n && N>=0 ){
  50919. N += useType*n;
  50920. sqlite3_mutex_enter(db->mutex);
  50921. assert( db->mallocFailed==0 );
  50922. ret = xFunc(&p->aColName[N]);
  50923. /* A malloc may have failed inside of the xFunc() call. If this
  50924. ** is the case, clear the mallocFailed flag and return NULL.
  50925. */
  50926. if( db->mallocFailed ){
  50927. db->mallocFailed = 0;
  50928. ret = 0;
  50929. }
  50930. sqlite3_mutex_leave(db->mutex);
  50931. }
  50932. return ret;
  50933. }
  50934. /*
  50935. ** Return the name of the Nth column of the result set returned by SQL
  50936. ** statement pStmt.
  50937. */
  50938. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  50939. return columnName(
  50940. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  50941. }
  50942. #ifndef SQLITE_OMIT_UTF16
  50943. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  50944. return columnName(
  50945. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  50946. }
  50947. #endif
  50948. /*
  50949. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  50950. ** not define OMIT_DECLTYPE.
  50951. */
  50952. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  50953. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  50954. and SQLITE_ENABLE_COLUMN_METADATA"
  50955. #endif
  50956. #ifndef SQLITE_OMIT_DECLTYPE
  50957. /*
  50958. ** Return the column declaration type (if applicable) of the 'i'th column
  50959. ** of the result set of SQL statement pStmt.
  50960. */
  50961. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  50962. return columnName(
  50963. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  50964. }
  50965. #ifndef SQLITE_OMIT_UTF16
  50966. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  50967. return columnName(
  50968. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  50969. }
  50970. #endif /* SQLITE_OMIT_UTF16 */
  50971. #endif /* SQLITE_OMIT_DECLTYPE */
  50972. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  50973. /*
  50974. ** Return the name of the database from which a result column derives.
  50975. ** NULL is returned if the result column is an expression or constant or
  50976. ** anything else which is not an unabiguous reference to a database column.
  50977. */
  50978. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  50979. return columnName(
  50980. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  50981. }
  50982. #ifndef SQLITE_OMIT_UTF16
  50983. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  50984. return columnName(
  50985. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  50986. }
  50987. #endif /* SQLITE_OMIT_UTF16 */
  50988. /*
  50989. ** Return the name of the table from which a result column derives.
  50990. ** NULL is returned if the result column is an expression or constant or
  50991. ** anything else which is not an unabiguous reference to a database column.
  50992. */
  50993. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  50994. return columnName(
  50995. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  50996. }
  50997. #ifndef SQLITE_OMIT_UTF16
  50998. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  50999. return columnName(
  51000. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  51001. }
  51002. #endif /* SQLITE_OMIT_UTF16 */
  51003. /*
  51004. ** Return the name of the table column from which a result column derives.
  51005. ** NULL is returned if the result column is an expression or constant or
  51006. ** anything else which is not an unabiguous reference to a database column.
  51007. */
  51008. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  51009. return columnName(
  51010. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  51011. }
  51012. #ifndef SQLITE_OMIT_UTF16
  51013. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  51014. return columnName(
  51015. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  51016. }
  51017. #endif /* SQLITE_OMIT_UTF16 */
  51018. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  51019. /******************************* sqlite3_bind_ ***************************
  51020. **
  51021. ** Routines used to attach values to wildcards in a compiled SQL statement.
  51022. */
  51023. /*
  51024. ** Unbind the value bound to variable i in virtual machine p. This is the
  51025. ** the same as binding a NULL value to the column. If the "i" parameter is
  51026. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  51027. **
  51028. ** A successful evaluation of this routine acquires the mutex on p.
  51029. ** the mutex is released if any kind of error occurs.
  51030. **
  51031. ** The error code stored in database p->db is overwritten with the return
  51032. ** value in any case.
  51033. */
  51034. static int vdbeUnbind(Vdbe *p, int i){
  51035. Mem *pVar;
  51036. if( vdbeSafetyNotNull(p) ){
  51037. return SQLITE_MISUSE_BKPT;
  51038. }
  51039. sqlite3_mutex_enter(p->db->mutex);
  51040. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  51041. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  51042. sqlite3_mutex_leave(p->db->mutex);
  51043. sqlite3_log(SQLITE_MISUSE,
  51044. "bind on a busy prepared statement: [%s]", p->zSql);
  51045. return SQLITE_MISUSE_BKPT;
  51046. }
  51047. if( i<1 || i>p->nVar ){
  51048. sqlite3Error(p->db, SQLITE_RANGE, 0);
  51049. sqlite3_mutex_leave(p->db->mutex);
  51050. return SQLITE_RANGE;
  51051. }
  51052. i--;
  51053. pVar = &p->aVar[i];
  51054. sqlite3VdbeMemRelease(pVar);
  51055. pVar->flags = MEM_Null;
  51056. sqlite3Error(p->db, SQLITE_OK, 0);
  51057. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  51058. ** binding a new value to this variable invalidates the current query plan.
  51059. **
  51060. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  51061. ** parameter in the WHERE clause might influence the choice of query plan
  51062. ** for a statement, then the statement will be automatically recompiled,
  51063. ** as if there had been a schema change, on the first sqlite3_step() call
  51064. ** following any change to the bindings of that parameter.
  51065. */
  51066. if( p->isPrepareV2 &&
  51067. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  51068. ){
  51069. p->expired = 1;
  51070. }
  51071. return SQLITE_OK;
  51072. }
  51073. /*
  51074. ** Bind a text or BLOB value.
  51075. */
  51076. static int bindText(
  51077. sqlite3_stmt *pStmt, /* The statement to bind against */
  51078. int i, /* Index of the parameter to bind */
  51079. const void *zData, /* Pointer to the data to be bound */
  51080. int nData, /* Number of bytes of data to be bound */
  51081. void (*xDel)(void*), /* Destructor for the data */
  51082. u8 encoding /* Encoding for the data */
  51083. ){
  51084. Vdbe *p = (Vdbe *)pStmt;
  51085. Mem *pVar;
  51086. int rc;
  51087. rc = vdbeUnbind(p, i);
  51088. if( rc==SQLITE_OK ){
  51089. if( zData!=0 ){
  51090. pVar = &p->aVar[i-1];
  51091. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  51092. if( rc==SQLITE_OK && encoding!=0 ){
  51093. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  51094. }
  51095. sqlite3Error(p->db, rc, 0);
  51096. rc = sqlite3ApiExit(p->db, rc);
  51097. }
  51098. sqlite3_mutex_leave(p->db->mutex);
  51099. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  51100. xDel((void*)zData);
  51101. }
  51102. return rc;
  51103. }
  51104. /*
  51105. ** Bind a blob value to an SQL statement variable.
  51106. */
  51107. SQLITE_API int sqlite3_bind_blob(
  51108. sqlite3_stmt *pStmt,
  51109. int i,
  51110. const void *zData,
  51111. int nData,
  51112. void (*xDel)(void*)
  51113. ){
  51114. return bindText(pStmt, i, zData, nData, xDel, 0);
  51115. }
  51116. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  51117. int rc;
  51118. Vdbe *p = (Vdbe *)pStmt;
  51119. rc = vdbeUnbind(p, i);
  51120. if( rc==SQLITE_OK ){
  51121. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  51122. sqlite3_mutex_leave(p->db->mutex);
  51123. }
  51124. return rc;
  51125. }
  51126. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  51127. return sqlite3_bind_int64(p, i, (i64)iValue);
  51128. }
  51129. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  51130. int rc;
  51131. Vdbe *p = (Vdbe *)pStmt;
  51132. rc = vdbeUnbind(p, i);
  51133. if( rc==SQLITE_OK ){
  51134. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  51135. sqlite3_mutex_leave(p->db->mutex);
  51136. }
  51137. return rc;
  51138. }
  51139. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  51140. int rc;
  51141. Vdbe *p = (Vdbe*)pStmt;
  51142. rc = vdbeUnbind(p, i);
  51143. if( rc==SQLITE_OK ){
  51144. sqlite3_mutex_leave(p->db->mutex);
  51145. }
  51146. return rc;
  51147. }
  51148. SQLITE_API int sqlite3_bind_text(
  51149. sqlite3_stmt *pStmt,
  51150. int i,
  51151. const char *zData,
  51152. int nData,
  51153. void (*xDel)(void*)
  51154. ){
  51155. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  51156. }
  51157. #ifndef SQLITE_OMIT_UTF16
  51158. SQLITE_API int sqlite3_bind_text16(
  51159. sqlite3_stmt *pStmt,
  51160. int i,
  51161. const void *zData,
  51162. int nData,
  51163. void (*xDel)(void*)
  51164. ){
  51165. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  51166. }
  51167. #endif /* SQLITE_OMIT_UTF16 */
  51168. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  51169. int rc;
  51170. switch( pValue->type ){
  51171. case SQLITE_INTEGER: {
  51172. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  51173. break;
  51174. }
  51175. case SQLITE_FLOAT: {
  51176. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  51177. break;
  51178. }
  51179. case SQLITE_BLOB: {
  51180. if( pValue->flags & MEM_Zero ){
  51181. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  51182. }else{
  51183. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  51184. }
  51185. break;
  51186. }
  51187. case SQLITE_TEXT: {
  51188. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  51189. pValue->enc);
  51190. break;
  51191. }
  51192. default: {
  51193. rc = sqlite3_bind_null(pStmt, i);
  51194. break;
  51195. }
  51196. }
  51197. return rc;
  51198. }
  51199. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  51200. int rc;
  51201. Vdbe *p = (Vdbe *)pStmt;
  51202. rc = vdbeUnbind(p, i);
  51203. if( rc==SQLITE_OK ){
  51204. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  51205. sqlite3_mutex_leave(p->db->mutex);
  51206. }
  51207. return rc;
  51208. }
  51209. /*
  51210. ** Return the number of wildcards that can be potentially bound to.
  51211. ** This routine is added to support DBD::SQLite.
  51212. */
  51213. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  51214. Vdbe *p = (Vdbe*)pStmt;
  51215. return p ? p->nVar : 0;
  51216. }
  51217. /*
  51218. ** Return the name of a wildcard parameter. Return NULL if the index
  51219. ** is out of range or if the wildcard is unnamed.
  51220. **
  51221. ** The result is always UTF-8.
  51222. */
  51223. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  51224. Vdbe *p = (Vdbe*)pStmt;
  51225. if( p==0 || i<1 || i>p->nzVar ){
  51226. return 0;
  51227. }
  51228. return p->azVar[i-1];
  51229. }
  51230. /*
  51231. ** Given a wildcard parameter name, return the index of the variable
  51232. ** with that name. If there is no variable with the given name,
  51233. ** return 0.
  51234. */
  51235. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  51236. int i;
  51237. if( p==0 ){
  51238. return 0;
  51239. }
  51240. if( zName ){
  51241. for(i=0; i<p->nzVar; i++){
  51242. const char *z = p->azVar[i];
  51243. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  51244. return i+1;
  51245. }
  51246. }
  51247. }
  51248. return 0;
  51249. }
  51250. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  51251. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  51252. }
  51253. /*
  51254. ** Transfer all bindings from the first statement over to the second.
  51255. */
  51256. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  51257. Vdbe *pFrom = (Vdbe*)pFromStmt;
  51258. Vdbe *pTo = (Vdbe*)pToStmt;
  51259. int i;
  51260. assert( pTo->db==pFrom->db );
  51261. assert( pTo->nVar==pFrom->nVar );
  51262. sqlite3_mutex_enter(pTo->db->mutex);
  51263. for(i=0; i<pFrom->nVar; i++){
  51264. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  51265. }
  51266. sqlite3_mutex_leave(pTo->db->mutex);
  51267. return SQLITE_OK;
  51268. }
  51269. #ifndef SQLITE_OMIT_DEPRECATED
  51270. /*
  51271. ** Deprecated external interface. Internal/core SQLite code
  51272. ** should call sqlite3TransferBindings.
  51273. **
  51274. ** Is is misuse to call this routine with statements from different
  51275. ** database connections. But as this is a deprecated interface, we
  51276. ** will not bother to check for that condition.
  51277. **
  51278. ** If the two statements contain a different number of bindings, then
  51279. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  51280. ** SQLITE_OK is returned.
  51281. */
  51282. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  51283. Vdbe *pFrom = (Vdbe*)pFromStmt;
  51284. Vdbe *pTo = (Vdbe*)pToStmt;
  51285. if( pFrom->nVar!=pTo->nVar ){
  51286. return SQLITE_ERROR;
  51287. }
  51288. if( pTo->isPrepareV2 && pTo->expmask ){
  51289. pTo->expired = 1;
  51290. }
  51291. if( pFrom->isPrepareV2 && pFrom->expmask ){
  51292. pFrom->expired = 1;
  51293. }
  51294. return sqlite3TransferBindings(pFromStmt, pToStmt);
  51295. }
  51296. #endif
  51297. /*
  51298. ** Return the sqlite3* database handle to which the prepared statement given
  51299. ** in the argument belongs. This is the same database handle that was
  51300. ** the first argument to the sqlite3_prepare() that was used to create
  51301. ** the statement in the first place.
  51302. */
  51303. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  51304. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  51305. }
  51306. /*
  51307. ** Return true if the prepared statement is guaranteed to not modify the
  51308. ** database.
  51309. */
  51310. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  51311. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  51312. }
  51313. /*
  51314. ** Return true if the prepared statement is in need of being reset.
  51315. */
  51316. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  51317. Vdbe *v = (Vdbe*)pStmt;
  51318. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  51319. }
  51320. /*
  51321. ** Return a pointer to the next prepared statement after pStmt associated
  51322. ** with database connection pDb. If pStmt is NULL, return the first
  51323. ** prepared statement for the database connection. Return NULL if there
  51324. ** are no more.
  51325. */
  51326. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  51327. sqlite3_stmt *pNext;
  51328. sqlite3_mutex_enter(pDb->mutex);
  51329. if( pStmt==0 ){
  51330. pNext = (sqlite3_stmt*)pDb->pVdbe;
  51331. }else{
  51332. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  51333. }
  51334. sqlite3_mutex_leave(pDb->mutex);
  51335. return pNext;
  51336. }
  51337. /*
  51338. ** Return the value of a status counter for a prepared statement
  51339. */
  51340. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  51341. Vdbe *pVdbe = (Vdbe*)pStmt;
  51342. u32 v = pVdbe->aCounter[op];
  51343. if( resetFlag ) pVdbe->aCounter[op] = 0;
  51344. return (int)v;
  51345. }
  51346. /************** End of vdbeapi.c *********************************************/
  51347. /************** Begin file vdbetrace.c ***************************************/
  51348. /*
  51349. ** 2009 November 25
  51350. **
  51351. ** The author disclaims copyright to this source code. In place of
  51352. ** a legal notice, here is a blessing:
  51353. **
  51354. ** May you do good and not evil.
  51355. ** May you find forgiveness for yourself and forgive others.
  51356. ** May you share freely, never taking more than you give.
  51357. **
  51358. *************************************************************************
  51359. **
  51360. ** This file contains code used to insert the values of host parameters
  51361. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  51362. **
  51363. ** The Vdbe parse-tree explainer is also found here.
  51364. */
  51365. #ifndef SQLITE_OMIT_TRACE
  51366. /*
  51367. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  51368. ** bytes in this text up to but excluding the first character in
  51369. ** a host parameter. If the text contains no host parameters, return
  51370. ** the total number of bytes in the text.
  51371. */
  51372. static int findNextHostParameter(const char *zSql, int *pnToken){
  51373. int tokenType;
  51374. int nTotal = 0;
  51375. int n;
  51376. *pnToken = 0;
  51377. while( zSql[0] ){
  51378. n = sqlite3GetToken((u8*)zSql, &tokenType);
  51379. assert( n>0 && tokenType!=TK_ILLEGAL );
  51380. if( tokenType==TK_VARIABLE ){
  51381. *pnToken = n;
  51382. break;
  51383. }
  51384. nTotal += n;
  51385. zSql += n;
  51386. }
  51387. return nTotal;
  51388. }
  51389. /*
  51390. ** This function returns a pointer to a nul-terminated string in memory
  51391. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  51392. ** string contains a copy of zRawSql but with host parameters expanded to
  51393. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  51394. ** then the returned string holds a copy of zRawSql with "-- " prepended
  51395. ** to each line of text.
  51396. **
  51397. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  51398. ** then long strings and blobs are truncated to that many bytes. This
  51399. ** can be used to prevent unreasonably large trace strings when dealing
  51400. ** with large (multi-megabyte) strings and blobs.
  51401. **
  51402. ** The calling function is responsible for making sure the memory returned
  51403. ** is eventually freed.
  51404. **
  51405. ** ALGORITHM: Scan the input string looking for host parameters in any of
  51406. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  51407. ** string literals, quoted identifier names, and comments. For text forms,
  51408. ** the host parameter index is found by scanning the perpared
  51409. ** statement for the corresponding OP_Variable opcode. Once the host
  51410. ** parameter index is known, locate the value in p->aVar[]. Then render
  51411. ** the value as a literal in place of the host parameter name.
  51412. */
  51413. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  51414. Vdbe *p, /* The prepared statement being evaluated */
  51415. const char *zRawSql /* Raw text of the SQL statement */
  51416. ){
  51417. sqlite3 *db; /* The database connection */
  51418. int idx = 0; /* Index of a host parameter */
  51419. int nextIndex = 1; /* Index of next ? host parameter */
  51420. int n; /* Length of a token prefix */
  51421. int nToken; /* Length of the parameter token */
  51422. int i; /* Loop counter */
  51423. Mem *pVar; /* Value of a host parameter */
  51424. StrAccum out; /* Accumulate the output here */
  51425. char zBase[100]; /* Initial working space */
  51426. db = p->db;
  51427. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  51428. db->aLimit[SQLITE_LIMIT_LENGTH]);
  51429. out.db = db;
  51430. if( db->nVdbeExec>1 ){
  51431. while( *zRawSql ){
  51432. const char *zStart = zRawSql;
  51433. while( *(zRawSql++)!='\n' && *zRawSql );
  51434. sqlite3StrAccumAppend(&out, "-- ", 3);
  51435. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  51436. }
  51437. }else{
  51438. while( zRawSql[0] ){
  51439. n = findNextHostParameter(zRawSql, &nToken);
  51440. assert( n>0 );
  51441. sqlite3StrAccumAppend(&out, zRawSql, n);
  51442. zRawSql += n;
  51443. assert( zRawSql[0] || nToken==0 );
  51444. if( nToken==0 ) break;
  51445. if( zRawSql[0]=='?' ){
  51446. if( nToken>1 ){
  51447. assert( sqlite3Isdigit(zRawSql[1]) );
  51448. sqlite3GetInt32(&zRawSql[1], &idx);
  51449. }else{
  51450. idx = nextIndex;
  51451. }
  51452. }else{
  51453. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  51454. testcase( zRawSql[0]==':' );
  51455. testcase( zRawSql[0]=='$' );
  51456. testcase( zRawSql[0]=='@' );
  51457. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  51458. assert( idx>0 );
  51459. }
  51460. zRawSql += nToken;
  51461. nextIndex = idx + 1;
  51462. assert( idx>0 && idx<=p->nVar );
  51463. pVar = &p->aVar[idx-1];
  51464. if( pVar->flags & MEM_Null ){
  51465. sqlite3StrAccumAppend(&out, "NULL", 4);
  51466. }else if( pVar->flags & MEM_Int ){
  51467. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  51468. }else if( pVar->flags & MEM_Real ){
  51469. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  51470. }else if( pVar->flags & MEM_Str ){
  51471. int nOut; /* Number of bytes of the string text to include in output */
  51472. #ifndef SQLITE_OMIT_UTF16
  51473. u8 enc = ENC(db);
  51474. Mem utf8;
  51475. if( enc!=SQLITE_UTF8 ){
  51476. memset(&utf8, 0, sizeof(utf8));
  51477. utf8.db = db;
  51478. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  51479. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  51480. pVar = &utf8;
  51481. }
  51482. #endif
  51483. nOut = pVar->n;
  51484. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51485. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  51486. nOut = SQLITE_TRACE_SIZE_LIMIT;
  51487. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  51488. }
  51489. #endif
  51490. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  51491. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51492. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  51493. #endif
  51494. #ifndef SQLITE_OMIT_UTF16
  51495. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  51496. #endif
  51497. }else if( pVar->flags & MEM_Zero ){
  51498. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  51499. }else{
  51500. int nOut; /* Number of bytes of the blob to include in output */
  51501. assert( pVar->flags & MEM_Blob );
  51502. sqlite3StrAccumAppend(&out, "x'", 2);
  51503. nOut = pVar->n;
  51504. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51505. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  51506. #endif
  51507. for(i=0; i<nOut; i++){
  51508. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  51509. }
  51510. sqlite3StrAccumAppend(&out, "'", 1);
  51511. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51512. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  51513. #endif
  51514. }
  51515. }
  51516. }
  51517. return sqlite3StrAccumFinish(&out);
  51518. }
  51519. #endif /* #ifndef SQLITE_OMIT_TRACE */
  51520. /*****************************************************************************
  51521. ** The following code implements the data-structure explaining logic
  51522. ** for the Vdbe.
  51523. */
  51524. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  51525. /*
  51526. ** Allocate a new Explain object
  51527. */
  51528. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  51529. if( pVdbe ){
  51530. Explain *p;
  51531. sqlite3BeginBenignMalloc();
  51532. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  51533. if( p ){
  51534. p->pVdbe = pVdbe;
  51535. sqlite3_free(pVdbe->pExplain);
  51536. pVdbe->pExplain = p;
  51537. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  51538. SQLITE_MAX_LENGTH);
  51539. p->str.useMalloc = 2;
  51540. }else{
  51541. sqlite3EndBenignMalloc();
  51542. }
  51543. }
  51544. }
  51545. /*
  51546. ** Return true if the Explain ends with a new-line.
  51547. */
  51548. static int endsWithNL(Explain *p){
  51549. return p && p->str.zText && p->str.nChar
  51550. && p->str.zText[p->str.nChar-1]=='\n';
  51551. }
  51552. /*
  51553. ** Append text to the indentation
  51554. */
  51555. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  51556. Explain *p;
  51557. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  51558. va_list ap;
  51559. if( p->nIndent && endsWithNL(p) ){
  51560. int n = p->nIndent;
  51561. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  51562. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  51563. }
  51564. va_start(ap, zFormat);
  51565. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  51566. va_end(ap);
  51567. }
  51568. }
  51569. /*
  51570. ** Append a '\n' if there is not already one.
  51571. */
  51572. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  51573. Explain *p;
  51574. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  51575. sqlite3StrAccumAppend(&p->str, "\n", 1);
  51576. }
  51577. }
  51578. /*
  51579. ** Push a new indentation level. Subsequent lines will be indented
  51580. ** so that they begin at the current cursor position.
  51581. */
  51582. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  51583. Explain *p;
  51584. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  51585. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  51586. const char *z = p->str.zText;
  51587. int i = p->str.nChar-1;
  51588. int x;
  51589. while( i>=0 && z[i]!='\n' ){ i--; }
  51590. x = (p->str.nChar - 1) - i;
  51591. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  51592. x = p->aIndent[p->nIndent-1];
  51593. }
  51594. p->aIndent[p->nIndent] = x;
  51595. }
  51596. p->nIndent++;
  51597. }
  51598. }
  51599. /*
  51600. ** Pop the indentation stack by one level.
  51601. */
  51602. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  51603. if( p && p->pExplain ) p->pExplain->nIndent--;
  51604. }
  51605. /*
  51606. ** Free the indentation structure
  51607. */
  51608. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  51609. if( pVdbe && pVdbe->pExplain ){
  51610. sqlite3_free(pVdbe->zExplain);
  51611. sqlite3ExplainNL(pVdbe);
  51612. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  51613. sqlite3_free(pVdbe->pExplain);
  51614. pVdbe->pExplain = 0;
  51615. sqlite3EndBenignMalloc();
  51616. }
  51617. }
  51618. /*
  51619. ** Return the explanation of a virtual machine.
  51620. */
  51621. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  51622. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  51623. }
  51624. #endif /* defined(SQLITE_DEBUG) */
  51625. /************** End of vdbetrace.c *******************************************/
  51626. /************** Begin file vdbe.c ********************************************/
  51627. /*
  51628. ** 2001 September 15
  51629. **
  51630. ** The author disclaims copyright to this source code. In place of
  51631. ** a legal notice, here is a blessing:
  51632. **
  51633. ** May you do good and not evil.
  51634. ** May you find forgiveness for yourself and forgive others.
  51635. ** May you share freely, never taking more than you give.
  51636. **
  51637. *************************************************************************
  51638. ** The code in this file implements execution method of the
  51639. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  51640. ** handles housekeeping details such as creating and deleting
  51641. ** VDBE instances. This file is solely interested in executing
  51642. ** the VDBE program.
  51643. **
  51644. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  51645. ** to a VDBE.
  51646. **
  51647. ** The SQL parser generates a program which is then executed by
  51648. ** the VDBE to do the work of the SQL statement. VDBE programs are
  51649. ** similar in form to assembly language. The program consists of
  51650. ** a linear sequence of operations. Each operation has an opcode
  51651. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  51652. ** is a null-terminated string. Operand P5 is an unsigned character.
  51653. ** Few opcodes use all 5 operands.
  51654. **
  51655. ** Computation results are stored on a set of registers numbered beginning
  51656. ** with 1 and going up to Vdbe.nMem. Each register can store
  51657. ** either an integer, a null-terminated string, a floating point
  51658. ** number, or the SQL "NULL" value. An implicit conversion from one
  51659. ** type to the other occurs as necessary.
  51660. **
  51661. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  51662. ** function which does the work of interpreting a VDBE program.
  51663. ** But other routines are also provided to help in building up
  51664. ** a program instruction by instruction.
  51665. **
  51666. ** Various scripts scan this source file in order to generate HTML
  51667. ** documentation, headers files, or other derived files. The formatting
  51668. ** of the code in this file is, therefore, important. See other comments
  51669. ** in this file for details. If in doubt, do not deviate from existing
  51670. ** commenting and indentation practices when changing or adding code.
  51671. */
  51672. /*
  51673. ** Invoke this macro on memory cells just prior to changing the
  51674. ** value of the cell. This macro verifies that shallow copies are
  51675. ** not misused.
  51676. */
  51677. #ifdef SQLITE_DEBUG
  51678. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  51679. #else
  51680. # define memAboutToChange(P,M)
  51681. #endif
  51682. /*
  51683. ** The following global variable is incremented every time a cursor
  51684. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  51685. ** procedures use this information to make sure that indices are
  51686. ** working correctly. This variable has no function other than to
  51687. ** help verify the correct operation of the library.
  51688. */
  51689. #ifdef SQLITE_TEST
  51690. SQLITE_API int sqlite3_search_count = 0;
  51691. #endif
  51692. /*
  51693. ** When this global variable is positive, it gets decremented once before
  51694. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  51695. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  51696. **
  51697. ** This facility is used for testing purposes only. It does not function
  51698. ** in an ordinary build.
  51699. */
  51700. #ifdef SQLITE_TEST
  51701. SQLITE_API int sqlite3_interrupt_count = 0;
  51702. #endif
  51703. /*
  51704. ** The next global variable is incremented each type the OP_Sort opcode
  51705. ** is executed. The test procedures use this information to make sure that
  51706. ** sorting is occurring or not occurring at appropriate times. This variable
  51707. ** has no function other than to help verify the correct operation of the
  51708. ** library.
  51709. */
  51710. #ifdef SQLITE_TEST
  51711. SQLITE_API int sqlite3_sort_count = 0;
  51712. #endif
  51713. /*
  51714. ** The next global variable records the size of the largest MEM_Blob
  51715. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  51716. ** use this information to make sure that the zero-blob functionality
  51717. ** is working correctly. This variable has no function other than to
  51718. ** help verify the correct operation of the library.
  51719. */
  51720. #ifdef SQLITE_TEST
  51721. SQLITE_API int sqlite3_max_blobsize = 0;
  51722. static void updateMaxBlobsize(Mem *p){
  51723. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  51724. sqlite3_max_blobsize = p->n;
  51725. }
  51726. }
  51727. #endif
  51728. /*
  51729. ** The next global variable is incremented each type the OP_Found opcode
  51730. ** is executed. This is used to test whether or not the foreign key
  51731. ** operation implemented using OP_FkIsZero is working. This variable
  51732. ** has no function other than to help verify the correct operation of the
  51733. ** library.
  51734. */
  51735. #ifdef SQLITE_TEST
  51736. SQLITE_API int sqlite3_found_count = 0;
  51737. #endif
  51738. /*
  51739. ** Test a register to see if it exceeds the current maximum blob size.
  51740. ** If it does, record the new maximum blob size.
  51741. */
  51742. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  51743. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  51744. #else
  51745. # define UPDATE_MAX_BLOBSIZE(P)
  51746. #endif
  51747. /*
  51748. ** Convert the given register into a string if it isn't one
  51749. ** already. Return non-zero if a malloc() fails.
  51750. */
  51751. #define Stringify(P, enc) \
  51752. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  51753. { goto no_mem; }
  51754. /*
  51755. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  51756. ** a pointer to a dynamically allocated string where some other entity
  51757. ** is responsible for deallocating that string. Because the register
  51758. ** does not control the string, it might be deleted without the register
  51759. ** knowing it.
  51760. **
  51761. ** This routine converts an ephemeral string into a dynamically allocated
  51762. ** string that the register itself controls. In other words, it
  51763. ** converts an MEM_Ephem string into an MEM_Dyn string.
  51764. */
  51765. #define Deephemeralize(P) \
  51766. if( ((P)->flags&MEM_Ephem)!=0 \
  51767. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  51768. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  51769. # define isSorter(x) ((x)->pSorter!=0)
  51770. /*
  51771. ** Argument pMem points at a register that will be passed to a
  51772. ** user-defined function or returned to the user as the result of a query.
  51773. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  51774. ** routines.
  51775. */
  51776. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  51777. int flags = pMem->flags;
  51778. if( flags & MEM_Null ){
  51779. pMem->type = SQLITE_NULL;
  51780. }
  51781. else if( flags & MEM_Int ){
  51782. pMem->type = SQLITE_INTEGER;
  51783. }
  51784. else if( flags & MEM_Real ){
  51785. pMem->type = SQLITE_FLOAT;
  51786. }
  51787. else if( flags & MEM_Str ){
  51788. pMem->type = SQLITE_TEXT;
  51789. }else{
  51790. pMem->type = SQLITE_BLOB;
  51791. }
  51792. }
  51793. /*
  51794. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  51795. ** if we run out of memory.
  51796. */
  51797. static VdbeCursor *allocateCursor(
  51798. Vdbe *p, /* The virtual machine */
  51799. int iCur, /* Index of the new VdbeCursor */
  51800. int nField, /* Number of fields in the table or index */
  51801. int iDb, /* Database the cursor belongs to, or -1 */
  51802. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  51803. ){
  51804. /* Find the memory cell that will be used to store the blob of memory
  51805. ** required for this VdbeCursor structure. It is convenient to use a
  51806. ** vdbe memory cell to manage the memory allocation required for a
  51807. ** VdbeCursor structure for the following reasons:
  51808. **
  51809. ** * Sometimes cursor numbers are used for a couple of different
  51810. ** purposes in a vdbe program. The different uses might require
  51811. ** different sized allocations. Memory cells provide growable
  51812. ** allocations.
  51813. **
  51814. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  51815. ** be freed lazily via the sqlite3_release_memory() API. This
  51816. ** minimizes the number of malloc calls made by the system.
  51817. **
  51818. ** Memory cells for cursors are allocated at the top of the address
  51819. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  51820. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  51821. */
  51822. Mem *pMem = &p->aMem[p->nMem-iCur];
  51823. int nByte;
  51824. VdbeCursor *pCx = 0;
  51825. nByte =
  51826. ROUND8(sizeof(VdbeCursor)) +
  51827. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  51828. 2*nField*sizeof(u32);
  51829. assert( iCur<p->nCursor );
  51830. if( p->apCsr[iCur] ){
  51831. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  51832. p->apCsr[iCur] = 0;
  51833. }
  51834. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  51835. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  51836. memset(pCx, 0, sizeof(VdbeCursor));
  51837. pCx->iDb = iDb;
  51838. pCx->nField = nField;
  51839. if( nField ){
  51840. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  51841. }
  51842. if( isBtreeCursor ){
  51843. pCx->pCursor = (BtCursor*)
  51844. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  51845. sqlite3BtreeCursorZero(pCx->pCursor);
  51846. }
  51847. }
  51848. return pCx;
  51849. }
  51850. /*
  51851. ** Try to convert a value into a numeric representation if we can
  51852. ** do so without loss of information. In other words, if the string
  51853. ** looks like a number, convert it into a number. If it does not
  51854. ** look like a number, leave it alone.
  51855. */
  51856. static void applyNumericAffinity(Mem *pRec){
  51857. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  51858. double rValue;
  51859. i64 iValue;
  51860. u8 enc = pRec->enc;
  51861. if( (pRec->flags&MEM_Str)==0 ) return;
  51862. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  51863. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  51864. pRec->u.i = iValue;
  51865. pRec->flags |= MEM_Int;
  51866. }else{
  51867. pRec->r = rValue;
  51868. pRec->flags |= MEM_Real;
  51869. }
  51870. }
  51871. }
  51872. /*
  51873. ** Processing is determine by the affinity parameter:
  51874. **
  51875. ** SQLITE_AFF_INTEGER:
  51876. ** SQLITE_AFF_REAL:
  51877. ** SQLITE_AFF_NUMERIC:
  51878. ** Try to convert pRec to an integer representation or a
  51879. ** floating-point representation if an integer representation
  51880. ** is not possible. Note that the integer representation is
  51881. ** always preferred, even if the affinity is REAL, because
  51882. ** an integer representation is more space efficient on disk.
  51883. **
  51884. ** SQLITE_AFF_TEXT:
  51885. ** Convert pRec to a text representation.
  51886. **
  51887. ** SQLITE_AFF_NONE:
  51888. ** No-op. pRec is unchanged.
  51889. */
  51890. static void applyAffinity(
  51891. Mem *pRec, /* The value to apply affinity to */
  51892. char affinity, /* The affinity to be applied */
  51893. u8 enc /* Use this text encoding */
  51894. ){
  51895. if( affinity==SQLITE_AFF_TEXT ){
  51896. /* Only attempt the conversion to TEXT if there is an integer or real
  51897. ** representation (blob and NULL do not get converted) but no string
  51898. ** representation.
  51899. */
  51900. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  51901. sqlite3VdbeMemStringify(pRec, enc);
  51902. }
  51903. pRec->flags &= ~(MEM_Real|MEM_Int);
  51904. }else if( affinity!=SQLITE_AFF_NONE ){
  51905. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  51906. || affinity==SQLITE_AFF_NUMERIC );
  51907. applyNumericAffinity(pRec);
  51908. if( pRec->flags & MEM_Real ){
  51909. sqlite3VdbeIntegerAffinity(pRec);
  51910. }
  51911. }
  51912. }
  51913. /*
  51914. ** Try to convert the type of a function argument or a result column
  51915. ** into a numeric representation. Use either INTEGER or REAL whichever
  51916. ** is appropriate. But only do the conversion if it is possible without
  51917. ** loss of information and return the revised type of the argument.
  51918. */
  51919. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  51920. Mem *pMem = (Mem*)pVal;
  51921. if( pMem->type==SQLITE_TEXT ){
  51922. applyNumericAffinity(pMem);
  51923. sqlite3VdbeMemStoreType(pMem);
  51924. }
  51925. return pMem->type;
  51926. }
  51927. /*
  51928. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  51929. ** not the internal Mem* type.
  51930. */
  51931. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  51932. sqlite3_value *pVal,
  51933. u8 affinity,
  51934. u8 enc
  51935. ){
  51936. applyAffinity((Mem *)pVal, affinity, enc);
  51937. }
  51938. #ifdef SQLITE_DEBUG
  51939. /*
  51940. ** Write a nice string representation of the contents of cell pMem
  51941. ** into buffer zBuf, length nBuf.
  51942. */
  51943. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  51944. char *zCsr = zBuf;
  51945. int f = pMem->flags;
  51946. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  51947. if( f&MEM_Blob ){
  51948. int i;
  51949. char c;
  51950. if( f & MEM_Dyn ){
  51951. c = 'z';
  51952. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  51953. }else if( f & MEM_Static ){
  51954. c = 't';
  51955. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  51956. }else if( f & MEM_Ephem ){
  51957. c = 'e';
  51958. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  51959. }else{
  51960. c = 's';
  51961. }
  51962. sqlite3_snprintf(100, zCsr, "%c", c);
  51963. zCsr += sqlite3Strlen30(zCsr);
  51964. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  51965. zCsr += sqlite3Strlen30(zCsr);
  51966. for(i=0; i<16 && i<pMem->n; i++){
  51967. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  51968. zCsr += sqlite3Strlen30(zCsr);
  51969. }
  51970. for(i=0; i<16 && i<pMem->n; i++){
  51971. char z = pMem->z[i];
  51972. if( z<32 || z>126 ) *zCsr++ = '.';
  51973. else *zCsr++ = z;
  51974. }
  51975. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  51976. zCsr += sqlite3Strlen30(zCsr);
  51977. if( f & MEM_Zero ){
  51978. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  51979. zCsr += sqlite3Strlen30(zCsr);
  51980. }
  51981. *zCsr = '\0';
  51982. }else if( f & MEM_Str ){
  51983. int j, k;
  51984. zBuf[0] = ' ';
  51985. if( f & MEM_Dyn ){
  51986. zBuf[1] = 'z';
  51987. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  51988. }else if( f & MEM_Static ){
  51989. zBuf[1] = 't';
  51990. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  51991. }else if( f & MEM_Ephem ){
  51992. zBuf[1] = 'e';
  51993. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  51994. }else{
  51995. zBuf[1] = 's';
  51996. }
  51997. k = 2;
  51998. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  51999. k += sqlite3Strlen30(&zBuf[k]);
  52000. zBuf[k++] = '[';
  52001. for(j=0; j<15 && j<pMem->n; j++){
  52002. u8 c = pMem->z[j];
  52003. if( c>=0x20 && c<0x7f ){
  52004. zBuf[k++] = c;
  52005. }else{
  52006. zBuf[k++] = '.';
  52007. }
  52008. }
  52009. zBuf[k++] = ']';
  52010. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  52011. k += sqlite3Strlen30(&zBuf[k]);
  52012. zBuf[k++] = 0;
  52013. }
  52014. }
  52015. #endif
  52016. #ifdef SQLITE_DEBUG
  52017. /*
  52018. ** Print the value of a register for tracing purposes:
  52019. */
  52020. static void memTracePrint(FILE *out, Mem *p){
  52021. if( p->flags & MEM_Invalid ){
  52022. fprintf(out, " undefined");
  52023. }else if( p->flags & MEM_Null ){
  52024. fprintf(out, " NULL");
  52025. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  52026. fprintf(out, " si:%lld", p->u.i);
  52027. }else if( p->flags & MEM_Int ){
  52028. fprintf(out, " i:%lld", p->u.i);
  52029. #ifndef SQLITE_OMIT_FLOATING_POINT
  52030. }else if( p->flags & MEM_Real ){
  52031. fprintf(out, " r:%g", p->r);
  52032. #endif
  52033. }else if( p->flags & MEM_RowSet ){
  52034. fprintf(out, " (rowset)");
  52035. }else{
  52036. char zBuf[200];
  52037. sqlite3VdbeMemPrettyPrint(p, zBuf);
  52038. fprintf(out, " ");
  52039. fprintf(out, "%s", zBuf);
  52040. }
  52041. }
  52042. static void registerTrace(FILE *out, int iReg, Mem *p){
  52043. fprintf(out, "REG[%d] = ", iReg);
  52044. memTracePrint(out, p);
  52045. fprintf(out, "\n");
  52046. }
  52047. #endif
  52048. #ifdef SQLITE_DEBUG
  52049. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  52050. #else
  52051. # define REGISTER_TRACE(R,M)
  52052. #endif
  52053. #ifdef VDBE_PROFILE
  52054. /*
  52055. ** hwtime.h contains inline assembler code for implementing
  52056. ** high-performance timing routines.
  52057. */
  52058. /************** Include hwtime.h in the middle of vdbe.c *********************/
  52059. /************** Begin file hwtime.h ******************************************/
  52060. /*
  52061. ** 2008 May 27
  52062. **
  52063. ** The author disclaims copyright to this source code. In place of
  52064. ** a legal notice, here is a blessing:
  52065. **
  52066. ** May you do good and not evil.
  52067. ** May you find forgiveness for yourself and forgive others.
  52068. ** May you share freely, never taking more than you give.
  52069. **
  52070. ******************************************************************************
  52071. **
  52072. ** This file contains inline asm code for retrieving "high-performance"
  52073. ** counters for x86 class CPUs.
  52074. */
  52075. #ifndef _HWTIME_H_
  52076. #define _HWTIME_H_
  52077. /*
  52078. ** The following routine only works on pentium-class (or newer) processors.
  52079. ** It uses the RDTSC opcode to read the cycle count value out of the
  52080. ** processor and returns that value. This can be used for high-res
  52081. ** profiling.
  52082. */
  52083. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  52084. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  52085. #if defined(__GNUC__)
  52086. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52087. unsigned int lo, hi;
  52088. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  52089. return (sqlite_uint64)hi << 32 | lo;
  52090. }
  52091. #elif defined(_MSC_VER)
  52092. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  52093. __asm {
  52094. rdtsc
  52095. ret ; return value at EDX:EAX
  52096. }
  52097. }
  52098. #endif
  52099. #elif (defined(__GNUC__) && defined(__x86_64__))
  52100. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52101. unsigned long val;
  52102. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  52103. return val;
  52104. }
  52105. #elif (defined(__GNUC__) && defined(__ppc__))
  52106. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52107. unsigned long long retval;
  52108. unsigned long junk;
  52109. __asm__ __volatile__ ("\n\
  52110. 1: mftbu %1\n\
  52111. mftb %L0\n\
  52112. mftbu %0\n\
  52113. cmpw %0,%1\n\
  52114. bne 1b"
  52115. : "=r" (retval), "=r" (junk));
  52116. return retval;
  52117. }
  52118. #else
  52119. #error Need implementation of sqlite3Hwtime() for your platform.
  52120. /*
  52121. ** To compile without implementing sqlite3Hwtime() for your platform,
  52122. ** you can remove the above #error and use the following
  52123. ** stub function. You will lose timing support for many
  52124. ** of the debugging and testing utilities, but it should at
  52125. ** least compile and run.
  52126. */
  52127. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  52128. #endif
  52129. #endif /* !defined(_HWTIME_H_) */
  52130. /************** End of hwtime.h **********************************************/
  52131. /************** Continuing where we left off in vdbe.c ***********************/
  52132. #endif
  52133. /*
  52134. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  52135. ** sqlite3_interrupt() routine has been called. If it has been, then
  52136. ** processing of the VDBE program is interrupted.
  52137. **
  52138. ** This macro added to every instruction that does a jump in order to
  52139. ** implement a loop. This test used to be on every single instruction,
  52140. ** but that meant we more testing than we needed. By only testing the
  52141. ** flag on jump instructions, we get a (small) speed improvement.
  52142. */
  52143. #define CHECK_FOR_INTERRUPT \
  52144. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  52145. #ifndef NDEBUG
  52146. /*
  52147. ** This function is only called from within an assert() expression. It
  52148. ** checks that the sqlite3.nTransaction variable is correctly set to
  52149. ** the number of non-transaction savepoints currently in the
  52150. ** linked list starting at sqlite3.pSavepoint.
  52151. **
  52152. ** Usage:
  52153. **
  52154. ** assert( checkSavepointCount(db) );
  52155. */
  52156. static int checkSavepointCount(sqlite3 *db){
  52157. int n = 0;
  52158. Savepoint *p;
  52159. for(p=db->pSavepoint; p; p=p->pNext) n++;
  52160. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  52161. return 1;
  52162. }
  52163. #endif
  52164. /*
  52165. ** Execute as much of a VDBE program as we can then return.
  52166. **
  52167. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  52168. ** close the program with a final OP_Halt and to set up the callbacks
  52169. ** and the error message pointer.
  52170. **
  52171. ** Whenever a row or result data is available, this routine will either
  52172. ** invoke the result callback (if there is one) or return with
  52173. ** SQLITE_ROW.
  52174. **
  52175. ** If an attempt is made to open a locked database, then this routine
  52176. ** will either invoke the busy callback (if there is one) or it will
  52177. ** return SQLITE_BUSY.
  52178. **
  52179. ** If an error occurs, an error message is written to memory obtained
  52180. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  52181. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  52182. **
  52183. ** If the callback ever returns non-zero, then the program exits
  52184. ** immediately. There will be no error message but the p->rc field is
  52185. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  52186. **
  52187. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  52188. ** routine to return SQLITE_ERROR.
  52189. **
  52190. ** Other fatal errors return SQLITE_ERROR.
  52191. **
  52192. ** After this routine has finished, sqlite3VdbeFinalize() should be
  52193. ** used to clean up the mess that was left behind.
  52194. */
  52195. SQLITE_PRIVATE int sqlite3VdbeExec(
  52196. Vdbe *p /* The VDBE */
  52197. ){
  52198. int pc=0; /* The program counter */
  52199. Op *aOp = p->aOp; /* Copy of p->aOp */
  52200. Op *pOp; /* Current operation */
  52201. int rc = SQLITE_OK; /* Value to return */
  52202. sqlite3 *db = p->db; /* The database */
  52203. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  52204. u8 encoding = ENC(db); /* The database encoding */
  52205. int iCompare = 0; /* Result of last OP_Compare operation */
  52206. unsigned nVmStep = 0; /* Number of virtual machine steps */
  52207. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52208. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  52209. #endif
  52210. Mem *aMem = p->aMem; /* Copy of p->aMem */
  52211. Mem *pIn1 = 0; /* 1st input operand */
  52212. Mem *pIn2 = 0; /* 2nd input operand */
  52213. Mem *pIn3 = 0; /* 3rd input operand */
  52214. Mem *pOut = 0; /* Output operand */
  52215. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  52216. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  52217. #ifdef VDBE_PROFILE
  52218. u64 start; /* CPU clock count at start of opcode */
  52219. int origPc; /* Program counter at start of opcode */
  52220. #endif
  52221. /********************************************************************
  52222. ** Automatically generated code
  52223. **
  52224. ** The following union is automatically generated by the
  52225. ** vdbe-compress.tcl script. The purpose of this union is to
  52226. ** reduce the amount of stack space required by this function.
  52227. ** See comments in the vdbe-compress.tcl script for details.
  52228. */
  52229. union vdbeExecUnion {
  52230. struct OP_Yield_stack_vars {
  52231. int pcDest;
  52232. } aa;
  52233. struct OP_Null_stack_vars {
  52234. int cnt;
  52235. u16 nullFlag;
  52236. } ab;
  52237. struct OP_Variable_stack_vars {
  52238. Mem *pVar; /* Value being transferred */
  52239. } ac;
  52240. struct OP_Move_stack_vars {
  52241. char *zMalloc; /* Holding variable for allocated memory */
  52242. int n; /* Number of registers left to copy */
  52243. int p1; /* Register to copy from */
  52244. int p2; /* Register to copy to */
  52245. } ad;
  52246. struct OP_Copy_stack_vars {
  52247. int n;
  52248. } ae;
  52249. struct OP_ResultRow_stack_vars {
  52250. Mem *pMem;
  52251. int i;
  52252. } af;
  52253. struct OP_Concat_stack_vars {
  52254. i64 nByte;
  52255. } ag;
  52256. struct OP_Remainder_stack_vars {
  52257. char bIntint; /* Started out as two integer operands */
  52258. int flags; /* Combined MEM_* flags from both inputs */
  52259. i64 iA; /* Integer value of left operand */
  52260. i64 iB; /* Integer value of right operand */
  52261. double rA; /* Real value of left operand */
  52262. double rB; /* Real value of right operand */
  52263. } ah;
  52264. struct OP_Function_stack_vars {
  52265. int i;
  52266. Mem *pArg;
  52267. sqlite3_context ctx;
  52268. sqlite3_value **apVal;
  52269. int n;
  52270. } ai;
  52271. struct OP_ShiftRight_stack_vars {
  52272. i64 iA;
  52273. u64 uA;
  52274. i64 iB;
  52275. u8 op;
  52276. } aj;
  52277. struct OP_Ge_stack_vars {
  52278. int res; /* Result of the comparison of pIn1 against pIn3 */
  52279. char affinity; /* Affinity to use for comparison */
  52280. u16 flags1; /* Copy of initial value of pIn1->flags */
  52281. u16 flags3; /* Copy of initial value of pIn3->flags */
  52282. } ak;
  52283. struct OP_Compare_stack_vars {
  52284. int n;
  52285. int i;
  52286. int p1;
  52287. int p2;
  52288. const KeyInfo *pKeyInfo;
  52289. int idx;
  52290. CollSeq *pColl; /* Collating sequence to use on this term */
  52291. int bRev; /* True for DESCENDING sort order */
  52292. } al;
  52293. struct OP_Or_stack_vars {
  52294. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  52295. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  52296. } am;
  52297. struct OP_IfNot_stack_vars {
  52298. int c;
  52299. } an;
  52300. struct OP_Column_stack_vars {
  52301. u32 payloadSize; /* Number of bytes in the record */
  52302. i64 payloadSize64; /* Number of bytes in the record */
  52303. int p1; /* P1 value of the opcode */
  52304. int p2; /* column number to retrieve */
  52305. VdbeCursor *pC; /* The VDBE cursor */
  52306. char *zRec; /* Pointer to complete record-data */
  52307. BtCursor *pCrsr; /* The BTree cursor */
  52308. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  52309. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  52310. int nField; /* number of fields in the record */
  52311. int len; /* The length of the serialized data for the column */
  52312. int i; /* Loop counter */
  52313. char *zData; /* Part of the record being decoded */
  52314. Mem *pDest; /* Where to write the extracted value */
  52315. Mem sMem; /* For storing the record being decoded */
  52316. u8 *zIdx; /* Index into header */
  52317. u8 *zEndHdr; /* Pointer to first byte after the header */
  52318. u32 offset; /* Offset into the data */
  52319. u32 szField; /* Number of bytes in the content of a field */
  52320. int szHdr; /* Size of the header size field at start of record */
  52321. int avail; /* Number of bytes of available data */
  52322. u32 t; /* A type code from the record header */
  52323. Mem *pReg; /* PseudoTable input register */
  52324. } ao;
  52325. struct OP_Affinity_stack_vars {
  52326. const char *zAffinity; /* The affinity to be applied */
  52327. char cAff; /* A single character of affinity */
  52328. } ap;
  52329. struct OP_MakeRecord_stack_vars {
  52330. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  52331. Mem *pRec; /* The new record */
  52332. u64 nData; /* Number of bytes of data space */
  52333. int nHdr; /* Number of bytes of header space */
  52334. i64 nByte; /* Data space required for this record */
  52335. int nZero; /* Number of zero bytes at the end of the record */
  52336. int nVarint; /* Number of bytes in a varint */
  52337. u32 serial_type; /* Type field */
  52338. Mem *pData0; /* First field to be combined into the record */
  52339. Mem *pLast; /* Last field of the record */
  52340. int nField; /* Number of fields in the record */
  52341. char *zAffinity; /* The affinity string for the record */
  52342. int file_format; /* File format to use for encoding */
  52343. int i; /* Space used in zNewRecord[] */
  52344. int len; /* Length of a field */
  52345. } aq;
  52346. struct OP_Count_stack_vars {
  52347. i64 nEntry;
  52348. BtCursor *pCrsr;
  52349. } ar;
  52350. struct OP_Savepoint_stack_vars {
  52351. int p1; /* Value of P1 operand */
  52352. char *zName; /* Name of savepoint */
  52353. int nName;
  52354. Savepoint *pNew;
  52355. Savepoint *pSavepoint;
  52356. Savepoint *pTmp;
  52357. int iSavepoint;
  52358. int ii;
  52359. } as;
  52360. struct OP_AutoCommit_stack_vars {
  52361. int desiredAutoCommit;
  52362. int iRollback;
  52363. int turnOnAC;
  52364. } at;
  52365. struct OP_Transaction_stack_vars {
  52366. Btree *pBt;
  52367. } au;
  52368. struct OP_ReadCookie_stack_vars {
  52369. int iMeta;
  52370. int iDb;
  52371. int iCookie;
  52372. } av;
  52373. struct OP_SetCookie_stack_vars {
  52374. Db *pDb;
  52375. } aw;
  52376. struct OP_VerifyCookie_stack_vars {
  52377. int iMeta;
  52378. int iGen;
  52379. Btree *pBt;
  52380. } ax;
  52381. struct OP_OpenWrite_stack_vars {
  52382. int nField;
  52383. KeyInfo *pKeyInfo;
  52384. int p2;
  52385. int iDb;
  52386. int wrFlag;
  52387. Btree *pX;
  52388. VdbeCursor *pCur;
  52389. Db *pDb;
  52390. } ay;
  52391. struct OP_OpenEphemeral_stack_vars {
  52392. VdbeCursor *pCx;
  52393. } az;
  52394. struct OP_SorterOpen_stack_vars {
  52395. VdbeCursor *pCx;
  52396. } ba;
  52397. struct OP_OpenPseudo_stack_vars {
  52398. VdbeCursor *pCx;
  52399. } bb;
  52400. struct OP_SeekGt_stack_vars {
  52401. int res;
  52402. int oc;
  52403. VdbeCursor *pC;
  52404. UnpackedRecord r;
  52405. int nField;
  52406. i64 iKey; /* The rowid we are to seek to */
  52407. } bc;
  52408. struct OP_Seek_stack_vars {
  52409. VdbeCursor *pC;
  52410. } bd;
  52411. struct OP_Found_stack_vars {
  52412. int alreadyExists;
  52413. VdbeCursor *pC;
  52414. int res;
  52415. char *pFree;
  52416. UnpackedRecord *pIdxKey;
  52417. UnpackedRecord r;
  52418. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  52419. } be;
  52420. struct OP_IsUnique_stack_vars {
  52421. u16 ii;
  52422. VdbeCursor *pCx;
  52423. BtCursor *pCrsr;
  52424. u16 nField;
  52425. Mem *aMx;
  52426. UnpackedRecord r; /* B-Tree index search key */
  52427. i64 R; /* Rowid stored in register P3 */
  52428. } bf;
  52429. struct OP_NotExists_stack_vars {
  52430. VdbeCursor *pC;
  52431. BtCursor *pCrsr;
  52432. int res;
  52433. u64 iKey;
  52434. } bg;
  52435. struct OP_NewRowid_stack_vars {
  52436. i64 v; /* The new rowid */
  52437. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  52438. int res; /* Result of an sqlite3BtreeLast() */
  52439. int cnt; /* Counter to limit the number of searches */
  52440. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  52441. VdbeFrame *pFrame; /* Root frame of VDBE */
  52442. } bh;
  52443. struct OP_InsertInt_stack_vars {
  52444. Mem *pData; /* MEM cell holding data for the record to be inserted */
  52445. Mem *pKey; /* MEM cell holding key for the record */
  52446. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  52447. VdbeCursor *pC; /* Cursor to table into which insert is written */
  52448. int nZero; /* Number of zero-bytes to append */
  52449. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  52450. const char *zDb; /* database name - used by the update hook */
  52451. const char *zTbl; /* Table name - used by the opdate hook */
  52452. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  52453. } bi;
  52454. struct OP_Delete_stack_vars {
  52455. i64 iKey;
  52456. VdbeCursor *pC;
  52457. } bj;
  52458. struct OP_SorterCompare_stack_vars {
  52459. VdbeCursor *pC;
  52460. int res;
  52461. } bk;
  52462. struct OP_SorterData_stack_vars {
  52463. VdbeCursor *pC;
  52464. } bl;
  52465. struct OP_RowData_stack_vars {
  52466. VdbeCursor *pC;
  52467. BtCursor *pCrsr;
  52468. u32 n;
  52469. i64 n64;
  52470. } bm;
  52471. struct OP_Rowid_stack_vars {
  52472. VdbeCursor *pC;
  52473. i64 v;
  52474. sqlite3_vtab *pVtab;
  52475. const sqlite3_module *pModule;
  52476. } bn;
  52477. struct OP_NullRow_stack_vars {
  52478. VdbeCursor *pC;
  52479. } bo;
  52480. struct OP_Last_stack_vars {
  52481. VdbeCursor *pC;
  52482. BtCursor *pCrsr;
  52483. int res;
  52484. } bp;
  52485. struct OP_Rewind_stack_vars {
  52486. VdbeCursor *pC;
  52487. BtCursor *pCrsr;
  52488. int res;
  52489. } bq;
  52490. struct OP_Next_stack_vars {
  52491. VdbeCursor *pC;
  52492. int res;
  52493. } br;
  52494. struct OP_IdxInsert_stack_vars {
  52495. VdbeCursor *pC;
  52496. BtCursor *pCrsr;
  52497. int nKey;
  52498. const char *zKey;
  52499. } bs;
  52500. struct OP_IdxDelete_stack_vars {
  52501. VdbeCursor *pC;
  52502. BtCursor *pCrsr;
  52503. int res;
  52504. UnpackedRecord r;
  52505. } bt;
  52506. struct OP_IdxRowid_stack_vars {
  52507. BtCursor *pCrsr;
  52508. VdbeCursor *pC;
  52509. i64 rowid;
  52510. } bu;
  52511. struct OP_IdxGE_stack_vars {
  52512. VdbeCursor *pC;
  52513. int res;
  52514. UnpackedRecord r;
  52515. } bv;
  52516. struct OP_Destroy_stack_vars {
  52517. int iMoved;
  52518. int iCnt;
  52519. Vdbe *pVdbe;
  52520. int iDb;
  52521. } bw;
  52522. struct OP_Clear_stack_vars {
  52523. int nChange;
  52524. } bx;
  52525. struct OP_CreateTable_stack_vars {
  52526. int pgno;
  52527. int flags;
  52528. Db *pDb;
  52529. } by;
  52530. struct OP_ParseSchema_stack_vars {
  52531. int iDb;
  52532. const char *zMaster;
  52533. char *zSql;
  52534. InitData initData;
  52535. } bz;
  52536. struct OP_IntegrityCk_stack_vars {
  52537. int nRoot; /* Number of tables to check. (Number of root pages.) */
  52538. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  52539. int j; /* Loop counter */
  52540. int nErr; /* Number of errors reported */
  52541. char *z; /* Text of the error report */
  52542. Mem *pnErr; /* Register keeping track of errors remaining */
  52543. } ca;
  52544. struct OP_RowSetRead_stack_vars {
  52545. i64 val;
  52546. } cb;
  52547. struct OP_RowSetTest_stack_vars {
  52548. int iSet;
  52549. int exists;
  52550. } cc;
  52551. struct OP_Program_stack_vars {
  52552. int nMem; /* Number of memory registers for sub-program */
  52553. int nByte; /* Bytes of runtime space required for sub-program */
  52554. Mem *pRt; /* Register to allocate runtime space */
  52555. Mem *pMem; /* Used to iterate through memory cells */
  52556. Mem *pEnd; /* Last memory cell in new array */
  52557. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  52558. SubProgram *pProgram; /* Sub-program to execute */
  52559. void *t; /* Token identifying trigger */
  52560. } cd;
  52561. struct OP_Param_stack_vars {
  52562. VdbeFrame *pFrame;
  52563. Mem *pIn;
  52564. } ce;
  52565. struct OP_MemMax_stack_vars {
  52566. Mem *pIn1;
  52567. VdbeFrame *pFrame;
  52568. } cf;
  52569. struct OP_AggStep_stack_vars {
  52570. int n;
  52571. int i;
  52572. Mem *pMem;
  52573. Mem *pRec;
  52574. sqlite3_context ctx;
  52575. sqlite3_value **apVal;
  52576. } cg;
  52577. struct OP_AggFinal_stack_vars {
  52578. Mem *pMem;
  52579. } ch;
  52580. struct OP_Checkpoint_stack_vars {
  52581. int i; /* Loop counter */
  52582. int aRes[3]; /* Results */
  52583. Mem *pMem; /* Write results here */
  52584. } ci;
  52585. struct OP_JournalMode_stack_vars {
  52586. Btree *pBt; /* Btree to change journal mode of */
  52587. Pager *pPager; /* Pager associated with pBt */
  52588. int eNew; /* New journal mode */
  52589. int eOld; /* The old journal mode */
  52590. #ifndef SQLITE_OMIT_WAL
  52591. const char *zFilename; /* Name of database file for pPager */
  52592. #endif
  52593. } cj;
  52594. struct OP_IncrVacuum_stack_vars {
  52595. Btree *pBt;
  52596. } ck;
  52597. struct OP_VBegin_stack_vars {
  52598. VTable *pVTab;
  52599. } cl;
  52600. struct OP_VOpen_stack_vars {
  52601. VdbeCursor *pCur;
  52602. sqlite3_vtab_cursor *pVtabCursor;
  52603. sqlite3_vtab *pVtab;
  52604. sqlite3_module *pModule;
  52605. } cm;
  52606. struct OP_VFilter_stack_vars {
  52607. int nArg;
  52608. int iQuery;
  52609. const sqlite3_module *pModule;
  52610. Mem *pQuery;
  52611. Mem *pArgc;
  52612. sqlite3_vtab_cursor *pVtabCursor;
  52613. sqlite3_vtab *pVtab;
  52614. VdbeCursor *pCur;
  52615. int res;
  52616. int i;
  52617. Mem **apArg;
  52618. } cn;
  52619. struct OP_VColumn_stack_vars {
  52620. sqlite3_vtab *pVtab;
  52621. const sqlite3_module *pModule;
  52622. Mem *pDest;
  52623. sqlite3_context sContext;
  52624. } co;
  52625. struct OP_VNext_stack_vars {
  52626. sqlite3_vtab *pVtab;
  52627. const sqlite3_module *pModule;
  52628. int res;
  52629. VdbeCursor *pCur;
  52630. } cp;
  52631. struct OP_VRename_stack_vars {
  52632. sqlite3_vtab *pVtab;
  52633. Mem *pName;
  52634. } cq;
  52635. struct OP_VUpdate_stack_vars {
  52636. sqlite3_vtab *pVtab;
  52637. sqlite3_module *pModule;
  52638. int nArg;
  52639. int i;
  52640. sqlite_int64 rowid;
  52641. Mem **apArg;
  52642. Mem *pX;
  52643. } cr;
  52644. struct OP_Trace_stack_vars {
  52645. char *zTrace;
  52646. char *z;
  52647. } cs;
  52648. } u;
  52649. /* End automatically generated code
  52650. ********************************************************************/
  52651. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  52652. sqlite3VdbeEnter(p);
  52653. if( p->rc==SQLITE_NOMEM ){
  52654. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  52655. ** sqlite3_column_text16() failed. */
  52656. goto no_mem;
  52657. }
  52658. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  52659. assert( p->bIsReader || p->readOnly!=0 );
  52660. p->rc = SQLITE_OK;
  52661. p->iCurrentTime = 0;
  52662. assert( p->explain==0 );
  52663. p->pResultSet = 0;
  52664. db->busyHandler.nBusy = 0;
  52665. CHECK_FOR_INTERRUPT;
  52666. sqlite3VdbeIOTraceSql(p);
  52667. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52668. if( db->xProgress ){
  52669. assert( 0 < db->nProgressOps );
  52670. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  52671. if( nProgressLimit==0 ){
  52672. nProgressLimit = db->nProgressOps;
  52673. }else{
  52674. nProgressLimit %= (unsigned)db->nProgressOps;
  52675. }
  52676. }
  52677. #endif
  52678. #ifdef SQLITE_DEBUG
  52679. sqlite3BeginBenignMalloc();
  52680. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  52681. int i;
  52682. printf("VDBE Program Listing:\n");
  52683. sqlite3VdbePrintSql(p);
  52684. for(i=0; i<p->nOp; i++){
  52685. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  52686. }
  52687. }
  52688. sqlite3EndBenignMalloc();
  52689. #endif
  52690. for(pc=p->pc; rc==SQLITE_OK; pc++){
  52691. assert( pc>=0 && pc<p->nOp );
  52692. if( db->mallocFailed ) goto no_mem;
  52693. #ifdef VDBE_PROFILE
  52694. origPc = pc;
  52695. start = sqlite3Hwtime();
  52696. #endif
  52697. nVmStep++;
  52698. pOp = &aOp[pc];
  52699. /* Only allow tracing if SQLITE_DEBUG is defined.
  52700. */
  52701. #ifdef SQLITE_DEBUG
  52702. if( p->trace ){
  52703. if( pc==0 ){
  52704. printf("VDBE Execution Trace:\n");
  52705. sqlite3VdbePrintSql(p);
  52706. }
  52707. sqlite3VdbePrintOp(p->trace, pc, pOp);
  52708. }
  52709. #endif
  52710. /* Check to see if we need to simulate an interrupt. This only happens
  52711. ** if we have a special test build.
  52712. */
  52713. #ifdef SQLITE_TEST
  52714. if( sqlite3_interrupt_count>0 ){
  52715. sqlite3_interrupt_count--;
  52716. if( sqlite3_interrupt_count==0 ){
  52717. sqlite3_interrupt(db);
  52718. }
  52719. }
  52720. #endif
  52721. /* On any opcode with the "out2-prerelease" tag, free any
  52722. ** external allocations out of mem[p2] and set mem[p2] to be
  52723. ** an undefined integer. Opcodes will either fill in the integer
  52724. ** value or convert mem[p2] to a different type.
  52725. */
  52726. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  52727. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  52728. assert( pOp->p2>0 );
  52729. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52730. pOut = &aMem[pOp->p2];
  52731. memAboutToChange(p, pOut);
  52732. VdbeMemRelease(pOut);
  52733. pOut->flags = MEM_Int;
  52734. }
  52735. /* Sanity checking on other operands */
  52736. #ifdef SQLITE_DEBUG
  52737. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  52738. assert( pOp->p1>0 );
  52739. assert( pOp->p1<=(p->nMem-p->nCursor) );
  52740. assert( memIsValid(&aMem[pOp->p1]) );
  52741. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  52742. }
  52743. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  52744. assert( pOp->p2>0 );
  52745. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52746. assert( memIsValid(&aMem[pOp->p2]) );
  52747. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  52748. }
  52749. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  52750. assert( pOp->p3>0 );
  52751. assert( pOp->p3<=(p->nMem-p->nCursor) );
  52752. assert( memIsValid(&aMem[pOp->p3]) );
  52753. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  52754. }
  52755. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  52756. assert( pOp->p2>0 );
  52757. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52758. memAboutToChange(p, &aMem[pOp->p2]);
  52759. }
  52760. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  52761. assert( pOp->p3>0 );
  52762. assert( pOp->p3<=(p->nMem-p->nCursor) );
  52763. memAboutToChange(p, &aMem[pOp->p3]);
  52764. }
  52765. #endif
  52766. switch( pOp->opcode ){
  52767. /*****************************************************************************
  52768. ** What follows is a massive switch statement where each case implements a
  52769. ** separate instruction in the virtual machine. If we follow the usual
  52770. ** indentation conventions, each case should be indented by 6 spaces. But
  52771. ** that is a lot of wasted space on the left margin. So the code within
  52772. ** the switch statement will break with convention and be flush-left. Another
  52773. ** big comment (similar to this one) will mark the point in the code where
  52774. ** we transition back to normal indentation.
  52775. **
  52776. ** The formatting of each case is important. The makefile for SQLite
  52777. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  52778. ** file looking for lines that begin with "case OP_". The opcodes.h files
  52779. ** will be filled with #defines that give unique integer values to each
  52780. ** opcode and the opcodes.c file is filled with an array of strings where
  52781. ** each string is the symbolic name for the corresponding opcode. If the
  52782. ** case statement is followed by a comment of the form "/# same as ... #/"
  52783. ** that comment is used to determine the particular value of the opcode.
  52784. **
  52785. ** Other keywords in the comment that follows each case are used to
  52786. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  52787. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  52788. ** the mkopcodeh.awk script for additional information.
  52789. **
  52790. ** Documentation about VDBE opcodes is generated by scanning this file
  52791. ** for lines of that contain "Opcode:". That line and all subsequent
  52792. ** comment lines are used in the generation of the opcode.html documentation
  52793. ** file.
  52794. **
  52795. ** SUMMARY:
  52796. **
  52797. ** Formatting is important to scripts that scan this file.
  52798. ** Do not deviate from the formatting style currently in use.
  52799. **
  52800. *****************************************************************************/
  52801. /* Opcode: Goto * P2 * * *
  52802. **
  52803. ** An unconditional jump to address P2.
  52804. ** The next instruction executed will be
  52805. ** the one at index P2 from the beginning of
  52806. ** the program.
  52807. */
  52808. case OP_Goto: { /* jump */
  52809. pc = pOp->p2 - 1;
  52810. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  52811. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  52812. ** completion. Check to see if sqlite3_interrupt() has been called
  52813. ** or if the progress callback needs to be invoked.
  52814. **
  52815. ** This code uses unstructured "goto" statements and does not look clean.
  52816. ** But that is not due to sloppy coding habits. The code is written this
  52817. ** way for performance, to avoid having to run the interrupt and progress
  52818. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  52819. ** faster according to "valgrind --tool=cachegrind" */
  52820. check_for_interrupt:
  52821. CHECK_FOR_INTERRUPT;
  52822. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52823. /* Call the progress callback if it is configured and the required number
  52824. ** of VDBE ops have been executed (either since this invocation of
  52825. ** sqlite3VdbeExec() or since last time the progress callback was called).
  52826. ** If the progress callback returns non-zero, exit the virtual machine with
  52827. ** a return code SQLITE_ABORT.
  52828. */
  52829. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  52830. int prc;
  52831. prc = db->xProgress(db->pProgressArg);
  52832. if( prc!=0 ){
  52833. rc = SQLITE_INTERRUPT;
  52834. goto vdbe_error_halt;
  52835. }
  52836. if( db->xProgress!=0 ){
  52837. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  52838. }
  52839. }
  52840. #endif
  52841. break;
  52842. }
  52843. /* Opcode: Gosub P1 P2 * * *
  52844. **
  52845. ** Write the current address onto register P1
  52846. ** and then jump to address P2.
  52847. */
  52848. case OP_Gosub: { /* jump */
  52849. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  52850. pIn1 = &aMem[pOp->p1];
  52851. assert( (pIn1->flags & MEM_Dyn)==0 );
  52852. memAboutToChange(p, pIn1);
  52853. pIn1->flags = MEM_Int;
  52854. pIn1->u.i = pc;
  52855. REGISTER_TRACE(pOp->p1, pIn1);
  52856. pc = pOp->p2 - 1;
  52857. break;
  52858. }
  52859. /* Opcode: Return P1 * * * *
  52860. **
  52861. ** Jump to the next instruction after the address in register P1.
  52862. */
  52863. case OP_Return: { /* in1 */
  52864. pIn1 = &aMem[pOp->p1];
  52865. assert( pIn1->flags & MEM_Int );
  52866. pc = (int)pIn1->u.i;
  52867. break;
  52868. }
  52869. /* Opcode: Yield P1 * * * *
  52870. **
  52871. ** Swap the program counter with the value in register P1.
  52872. */
  52873. case OP_Yield: { /* in1 */
  52874. #if 0 /* local variables moved into u.aa */
  52875. int pcDest;
  52876. #endif /* local variables moved into u.aa */
  52877. pIn1 = &aMem[pOp->p1];
  52878. assert( (pIn1->flags & MEM_Dyn)==0 );
  52879. pIn1->flags = MEM_Int;
  52880. u.aa.pcDest = (int)pIn1->u.i;
  52881. pIn1->u.i = pc;
  52882. REGISTER_TRACE(pOp->p1, pIn1);
  52883. pc = u.aa.pcDest;
  52884. break;
  52885. }
  52886. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  52887. **
  52888. ** Check the value in register P3. If it is NULL then Halt using
  52889. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  52890. ** value in register P3 is not NULL, then this routine is a no-op.
  52891. */
  52892. case OP_HaltIfNull: { /* in3 */
  52893. pIn3 = &aMem[pOp->p3];
  52894. if( (pIn3->flags & MEM_Null)==0 ) break;
  52895. /* Fall through into OP_Halt */
  52896. }
  52897. /* Opcode: Halt P1 P2 * P4 *
  52898. **
  52899. ** Exit immediately. All open cursors, etc are closed
  52900. ** automatically.
  52901. **
  52902. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  52903. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  52904. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  52905. ** whether or not to rollback the current transaction. Do not rollback
  52906. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  52907. ** then back out all changes that have occurred during this execution of the
  52908. ** VDBE, but do not rollback the transaction.
  52909. **
  52910. ** If P4 is not null then it is an error message string.
  52911. **
  52912. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  52913. ** every program. So a jump past the last instruction of the program
  52914. ** is the same as executing Halt.
  52915. */
  52916. case OP_Halt: {
  52917. if( pOp->p1==SQLITE_OK && p->pFrame ){
  52918. /* Halt the sub-program. Return control to the parent frame. */
  52919. VdbeFrame *pFrame = p->pFrame;
  52920. p->pFrame = pFrame->pParent;
  52921. p->nFrame--;
  52922. sqlite3VdbeSetChanges(db, p->nChange);
  52923. pc = sqlite3VdbeFrameRestore(pFrame);
  52924. lastRowid = db->lastRowid;
  52925. if( pOp->p2==OE_Ignore ){
  52926. /* Instruction pc is the OP_Program that invoked the sub-program
  52927. ** currently being halted. If the p2 instruction of this OP_Halt
  52928. ** instruction is set to OE_Ignore, then the sub-program is throwing
  52929. ** an IGNORE exception. In this case jump to the address specified
  52930. ** as the p2 of the calling OP_Program. */
  52931. pc = p->aOp[pc].p2-1;
  52932. }
  52933. aOp = p->aOp;
  52934. aMem = p->aMem;
  52935. break;
  52936. }
  52937. p->rc = pOp->p1;
  52938. p->errorAction = (u8)pOp->p2;
  52939. p->pc = pc;
  52940. if( pOp->p4.z ){
  52941. assert( p->rc!=SQLITE_OK );
  52942. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  52943. testcase( sqlite3GlobalConfig.xLog!=0 );
  52944. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  52945. }else if( p->rc ){
  52946. testcase( sqlite3GlobalConfig.xLog!=0 );
  52947. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  52948. }
  52949. rc = sqlite3VdbeHalt(p);
  52950. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  52951. if( rc==SQLITE_BUSY ){
  52952. p->rc = rc = SQLITE_BUSY;
  52953. }else{
  52954. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  52955. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  52956. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  52957. }
  52958. goto vdbe_return;
  52959. }
  52960. /* Opcode: Integer P1 P2 * * *
  52961. **
  52962. ** The 32-bit integer value P1 is written into register P2.
  52963. */
  52964. case OP_Integer: { /* out2-prerelease */
  52965. pOut->u.i = pOp->p1;
  52966. break;
  52967. }
  52968. /* Opcode: Int64 * P2 * P4 *
  52969. **
  52970. ** P4 is a pointer to a 64-bit integer value.
  52971. ** Write that value into register P2.
  52972. */
  52973. case OP_Int64: { /* out2-prerelease */
  52974. assert( pOp->p4.pI64!=0 );
  52975. pOut->u.i = *pOp->p4.pI64;
  52976. break;
  52977. }
  52978. #ifndef SQLITE_OMIT_FLOATING_POINT
  52979. /* Opcode: Real * P2 * P4 *
  52980. **
  52981. ** P4 is a pointer to a 64-bit floating point value.
  52982. ** Write that value into register P2.
  52983. */
  52984. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  52985. pOut->flags = MEM_Real;
  52986. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  52987. pOut->r = *pOp->p4.pReal;
  52988. break;
  52989. }
  52990. #endif
  52991. /* Opcode: String8 * P2 * P4 *
  52992. **
  52993. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  52994. ** into an OP_String before it is executed for the first time.
  52995. */
  52996. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  52997. assert( pOp->p4.z!=0 );
  52998. pOp->opcode = OP_String;
  52999. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  53000. #ifndef SQLITE_OMIT_UTF16
  53001. if( encoding!=SQLITE_UTF8 ){
  53002. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  53003. if( rc==SQLITE_TOOBIG ) goto too_big;
  53004. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  53005. assert( pOut->zMalloc==pOut->z );
  53006. assert( pOut->flags & MEM_Dyn );
  53007. pOut->zMalloc = 0;
  53008. pOut->flags |= MEM_Static;
  53009. pOut->flags &= ~MEM_Dyn;
  53010. if( pOp->p4type==P4_DYNAMIC ){
  53011. sqlite3DbFree(db, pOp->p4.z);
  53012. }
  53013. pOp->p4type = P4_DYNAMIC;
  53014. pOp->p4.z = pOut->z;
  53015. pOp->p1 = pOut->n;
  53016. }
  53017. #endif
  53018. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  53019. goto too_big;
  53020. }
  53021. /* Fall through to the next case, OP_String */
  53022. }
  53023. /* Opcode: String P1 P2 * P4 *
  53024. **
  53025. ** The string value P4 of length P1 (bytes) is stored in register P2.
  53026. */
  53027. case OP_String: { /* out2-prerelease */
  53028. assert( pOp->p4.z!=0 );
  53029. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  53030. pOut->z = pOp->p4.z;
  53031. pOut->n = pOp->p1;
  53032. pOut->enc = encoding;
  53033. UPDATE_MAX_BLOBSIZE(pOut);
  53034. break;
  53035. }
  53036. /* Opcode: Null P1 P2 P3 * *
  53037. **
  53038. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  53039. ** NULL into register P3 and every register in between P2 and P3. If P3
  53040. ** is less than P2 (typically P3 is zero) then only register P2 is
  53041. ** set to NULL.
  53042. **
  53043. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  53044. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  53045. ** OP_Ne or OP_Eq.
  53046. */
  53047. case OP_Null: { /* out2-prerelease */
  53048. #if 0 /* local variables moved into u.ab */
  53049. int cnt;
  53050. u16 nullFlag;
  53051. #endif /* local variables moved into u.ab */
  53052. u.ab.cnt = pOp->p3-pOp->p2;
  53053. assert( pOp->p3<=(p->nMem-p->nCursor) );
  53054. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  53055. while( u.ab.cnt>0 ){
  53056. pOut++;
  53057. memAboutToChange(p, pOut);
  53058. VdbeMemRelease(pOut);
  53059. pOut->flags = u.ab.nullFlag;
  53060. u.ab.cnt--;
  53061. }
  53062. break;
  53063. }
  53064. /* Opcode: Blob P1 P2 * P4
  53065. **
  53066. ** P4 points to a blob of data P1 bytes long. Store this
  53067. ** blob in register P2.
  53068. */
  53069. case OP_Blob: { /* out2-prerelease */
  53070. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  53071. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  53072. pOut->enc = encoding;
  53073. UPDATE_MAX_BLOBSIZE(pOut);
  53074. break;
  53075. }
  53076. /* Opcode: Variable P1 P2 * P4 *
  53077. **
  53078. ** Transfer the values of bound parameter P1 into register P2
  53079. **
  53080. ** If the parameter is named, then its name appears in P4 and P3==1.
  53081. ** The P4 value is used by sqlite3_bind_parameter_name().
  53082. */
  53083. case OP_Variable: { /* out2-prerelease */
  53084. #if 0 /* local variables moved into u.ac */
  53085. Mem *pVar; /* Value being transferred */
  53086. #endif /* local variables moved into u.ac */
  53087. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  53088. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  53089. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  53090. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  53091. goto too_big;
  53092. }
  53093. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  53094. UPDATE_MAX_BLOBSIZE(pOut);
  53095. break;
  53096. }
  53097. /* Opcode: Move P1 P2 P3 * *
  53098. **
  53099. ** Move the values in register P1..P1+P3 over into
  53100. ** registers P2..P2+P3. Registers P1..P1+P3 are
  53101. ** left holding a NULL. It is an error for register ranges
  53102. ** P1..P1+P3 and P2..P2+P3 to overlap.
  53103. */
  53104. case OP_Move: {
  53105. #if 0 /* local variables moved into u.ad */
  53106. char *zMalloc; /* Holding variable for allocated memory */
  53107. int n; /* Number of registers left to copy */
  53108. int p1; /* Register to copy from */
  53109. int p2; /* Register to copy to */
  53110. #endif /* local variables moved into u.ad */
  53111. u.ad.n = pOp->p3 + 1;
  53112. u.ad.p1 = pOp->p1;
  53113. u.ad.p2 = pOp->p2;
  53114. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  53115. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  53116. pIn1 = &aMem[u.ad.p1];
  53117. pOut = &aMem[u.ad.p2];
  53118. while( u.ad.n-- ){
  53119. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  53120. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  53121. assert( memIsValid(pIn1) );
  53122. memAboutToChange(p, pOut);
  53123. u.ad.zMalloc = pOut->zMalloc;
  53124. pOut->zMalloc = 0;
  53125. sqlite3VdbeMemMove(pOut, pIn1);
  53126. #ifdef SQLITE_DEBUG
  53127. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  53128. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  53129. }
  53130. #endif
  53131. pIn1->zMalloc = u.ad.zMalloc;
  53132. REGISTER_TRACE(u.ad.p2++, pOut);
  53133. pIn1++;
  53134. pOut++;
  53135. }
  53136. break;
  53137. }
  53138. /* Opcode: Copy P1 P2 P3 * *
  53139. **
  53140. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  53141. **
  53142. ** This instruction makes a deep copy of the value. A duplicate
  53143. ** is made of any string or blob constant. See also OP_SCopy.
  53144. */
  53145. case OP_Copy: {
  53146. #if 0 /* local variables moved into u.ae */
  53147. int n;
  53148. #endif /* local variables moved into u.ae */
  53149. u.ae.n = pOp->p3;
  53150. pIn1 = &aMem[pOp->p1];
  53151. pOut = &aMem[pOp->p2];
  53152. assert( pOut!=pIn1 );
  53153. while( 1 ){
  53154. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  53155. Deephemeralize(pOut);
  53156. #ifdef SQLITE_DEBUG
  53157. pOut->pScopyFrom = 0;
  53158. #endif
  53159. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  53160. if( (u.ae.n--)==0 ) break;
  53161. pOut++;
  53162. pIn1++;
  53163. }
  53164. break;
  53165. }
  53166. /* Opcode: SCopy P1 P2 * * *
  53167. **
  53168. ** Make a shallow copy of register P1 into register P2.
  53169. **
  53170. ** This instruction makes a shallow copy of the value. If the value
  53171. ** is a string or blob, then the copy is only a pointer to the
  53172. ** original and hence if the original changes so will the copy.
  53173. ** Worse, if the original is deallocated, the copy becomes invalid.
  53174. ** Thus the program must guarantee that the original will not change
  53175. ** during the lifetime of the copy. Use OP_Copy to make a complete
  53176. ** copy.
  53177. */
  53178. case OP_SCopy: { /* in1, out2 */
  53179. pIn1 = &aMem[pOp->p1];
  53180. pOut = &aMem[pOp->p2];
  53181. assert( pOut!=pIn1 );
  53182. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  53183. #ifdef SQLITE_DEBUG
  53184. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  53185. #endif
  53186. REGISTER_TRACE(pOp->p2, pOut);
  53187. break;
  53188. }
  53189. /* Opcode: ResultRow P1 P2 * * *
  53190. **
  53191. ** The registers P1 through P1+P2-1 contain a single row of
  53192. ** results. This opcode causes the sqlite3_step() call to terminate
  53193. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  53194. ** structure to provide access to the top P1 values as the result
  53195. ** row.
  53196. */
  53197. case OP_ResultRow: {
  53198. #if 0 /* local variables moved into u.af */
  53199. Mem *pMem;
  53200. int i;
  53201. #endif /* local variables moved into u.af */
  53202. assert( p->nResColumn==pOp->p2 );
  53203. assert( pOp->p1>0 );
  53204. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  53205. /* If this statement has violated immediate foreign key constraints, do
  53206. ** not return the number of rows modified. And do not RELEASE the statement
  53207. ** transaction. It needs to be rolled back. */
  53208. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  53209. assert( db->flags&SQLITE_CountRows );
  53210. assert( p->usesStmtJournal );
  53211. break;
  53212. }
  53213. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  53214. ** DML statements invoke this opcode to return the number of rows
  53215. ** modified to the user. This is the only way that a VM that
  53216. ** opens a statement transaction may invoke this opcode.
  53217. **
  53218. ** In case this is such a statement, close any statement transaction
  53219. ** opened by this VM before returning control to the user. This is to
  53220. ** ensure that statement-transactions are always nested, not overlapping.
  53221. ** If the open statement-transaction is not closed here, then the user
  53222. ** may step another VM that opens its own statement transaction. This
  53223. ** may lead to overlapping statement transactions.
  53224. **
  53225. ** The statement transaction is never a top-level transaction. Hence
  53226. ** the RELEASE call below can never fail.
  53227. */
  53228. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  53229. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  53230. if( NEVER(rc!=SQLITE_OK) ){
  53231. break;
  53232. }
  53233. /* Invalidate all ephemeral cursor row caches */
  53234. p->cacheCtr = (p->cacheCtr + 2)|1;
  53235. /* Make sure the results of the current row are \000 terminated
  53236. ** and have an assigned type. The results are de-ephemeralized as
  53237. ** a side effect.
  53238. */
  53239. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  53240. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  53241. assert( memIsValid(&u.af.pMem[u.af.i]) );
  53242. Deephemeralize(&u.af.pMem[u.af.i]);
  53243. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  53244. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  53245. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  53246. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  53247. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  53248. }
  53249. if( db->mallocFailed ) goto no_mem;
  53250. /* Return SQLITE_ROW
  53251. */
  53252. p->pc = pc + 1;
  53253. rc = SQLITE_ROW;
  53254. goto vdbe_return;
  53255. }
  53256. /* Opcode: Concat P1 P2 P3 * *
  53257. **
  53258. ** Add the text in register P1 onto the end of the text in
  53259. ** register P2 and store the result in register P3.
  53260. ** If either the P1 or P2 text are NULL then store NULL in P3.
  53261. **
  53262. ** P3 = P2 || P1
  53263. **
  53264. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  53265. ** if P3 is the same register as P2, the implementation is able
  53266. ** to avoid a memcpy().
  53267. */
  53268. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  53269. #if 0 /* local variables moved into u.ag */
  53270. i64 nByte;
  53271. #endif /* local variables moved into u.ag */
  53272. pIn1 = &aMem[pOp->p1];
  53273. pIn2 = &aMem[pOp->p2];
  53274. pOut = &aMem[pOp->p3];
  53275. assert( pIn1!=pOut );
  53276. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  53277. sqlite3VdbeMemSetNull(pOut);
  53278. break;
  53279. }
  53280. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  53281. Stringify(pIn1, encoding);
  53282. Stringify(pIn2, encoding);
  53283. u.ag.nByte = pIn1->n + pIn2->n;
  53284. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  53285. goto too_big;
  53286. }
  53287. MemSetTypeFlag(pOut, MEM_Str);
  53288. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  53289. goto no_mem;
  53290. }
  53291. if( pOut!=pIn2 ){
  53292. memcpy(pOut->z, pIn2->z, pIn2->n);
  53293. }
  53294. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  53295. pOut->z[u.ag.nByte] = 0;
  53296. pOut->z[u.ag.nByte+1] = 0;
  53297. pOut->flags |= MEM_Term;
  53298. pOut->n = (int)u.ag.nByte;
  53299. pOut->enc = encoding;
  53300. UPDATE_MAX_BLOBSIZE(pOut);
  53301. break;
  53302. }
  53303. /* Opcode: Add P1 P2 P3 * *
  53304. **
  53305. ** Add the value in register P1 to the value in register P2
  53306. ** and store the result in register P3.
  53307. ** If either input is NULL, the result is NULL.
  53308. */
  53309. /* Opcode: Multiply P1 P2 P3 * *
  53310. **
  53311. **
  53312. ** Multiply the value in register P1 by the value in register P2
  53313. ** and store the result in register P3.
  53314. ** If either input is NULL, the result is NULL.
  53315. */
  53316. /* Opcode: Subtract P1 P2 P3 * *
  53317. **
  53318. ** Subtract the value in register P1 from the value in register P2
  53319. ** and store the result in register P3.
  53320. ** If either input is NULL, the result is NULL.
  53321. */
  53322. /* Opcode: Divide P1 P2 P3 * *
  53323. **
  53324. ** Divide the value in register P1 by the value in register P2
  53325. ** and store the result in register P3 (P3=P2/P1). If the value in
  53326. ** register P1 is zero, then the result is NULL. If either input is
  53327. ** NULL, the result is NULL.
  53328. */
  53329. /* Opcode: Remainder P1 P2 P3 * *
  53330. **
  53331. ** Compute the remainder after integer division of the value in
  53332. ** register P1 by the value in register P2 and store the result in P3.
  53333. ** If the value in register P2 is zero the result is NULL.
  53334. ** If either operand is NULL, the result is NULL.
  53335. */
  53336. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  53337. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  53338. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  53339. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  53340. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  53341. #if 0 /* local variables moved into u.ah */
  53342. char bIntint; /* Started out as two integer operands */
  53343. int flags; /* Combined MEM_* flags from both inputs */
  53344. i64 iA; /* Integer value of left operand */
  53345. i64 iB; /* Integer value of right operand */
  53346. double rA; /* Real value of left operand */
  53347. double rB; /* Real value of right operand */
  53348. #endif /* local variables moved into u.ah */
  53349. pIn1 = &aMem[pOp->p1];
  53350. applyNumericAffinity(pIn1);
  53351. pIn2 = &aMem[pOp->p2];
  53352. applyNumericAffinity(pIn2);
  53353. pOut = &aMem[pOp->p3];
  53354. u.ah.flags = pIn1->flags | pIn2->flags;
  53355. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  53356. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  53357. u.ah.iA = pIn1->u.i;
  53358. u.ah.iB = pIn2->u.i;
  53359. u.ah.bIntint = 1;
  53360. switch( pOp->opcode ){
  53361. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53362. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53363. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53364. case OP_Divide: {
  53365. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53366. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  53367. u.ah.iB /= u.ah.iA;
  53368. break;
  53369. }
  53370. default: {
  53371. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53372. if( u.ah.iA==-1 ) u.ah.iA = 1;
  53373. u.ah.iB %= u.ah.iA;
  53374. break;
  53375. }
  53376. }
  53377. pOut->u.i = u.ah.iB;
  53378. MemSetTypeFlag(pOut, MEM_Int);
  53379. }else{
  53380. u.ah.bIntint = 0;
  53381. fp_math:
  53382. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  53383. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  53384. switch( pOp->opcode ){
  53385. case OP_Add: u.ah.rB += u.ah.rA; break;
  53386. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  53387. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  53388. case OP_Divide: {
  53389. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  53390. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  53391. u.ah.rB /= u.ah.rA;
  53392. break;
  53393. }
  53394. default: {
  53395. u.ah.iA = (i64)u.ah.rA;
  53396. u.ah.iB = (i64)u.ah.rB;
  53397. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53398. if( u.ah.iA==-1 ) u.ah.iA = 1;
  53399. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  53400. break;
  53401. }
  53402. }
  53403. #ifdef SQLITE_OMIT_FLOATING_POINT
  53404. pOut->u.i = u.ah.rB;
  53405. MemSetTypeFlag(pOut, MEM_Int);
  53406. #else
  53407. if( sqlite3IsNaN(u.ah.rB) ){
  53408. goto arithmetic_result_is_null;
  53409. }
  53410. pOut->r = u.ah.rB;
  53411. MemSetTypeFlag(pOut, MEM_Real);
  53412. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  53413. sqlite3VdbeIntegerAffinity(pOut);
  53414. }
  53415. #endif
  53416. }
  53417. break;
  53418. arithmetic_result_is_null:
  53419. sqlite3VdbeMemSetNull(pOut);
  53420. break;
  53421. }
  53422. /* Opcode: CollSeq P1 * * P4
  53423. **
  53424. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  53425. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  53426. ** be returned. This is used by the built-in min(), max() and nullif()
  53427. ** functions.
  53428. **
  53429. ** If P1 is not zero, then it is a register that a subsequent min() or
  53430. ** max() aggregate will set to 1 if the current row is not the minimum or
  53431. ** maximum. The P1 register is initialized to 0 by this instruction.
  53432. **
  53433. ** The interface used by the implementation of the aforementioned functions
  53434. ** to retrieve the collation sequence set by this opcode is not available
  53435. ** publicly, only to user functions defined in func.c.
  53436. */
  53437. case OP_CollSeq: {
  53438. assert( pOp->p4type==P4_COLLSEQ );
  53439. if( pOp->p1 ){
  53440. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  53441. }
  53442. break;
  53443. }
  53444. /* Opcode: Function P1 P2 P3 P4 P5
  53445. **
  53446. ** Invoke a user function (P4 is a pointer to a Function structure that
  53447. ** defines the function) with P5 arguments taken from register P2 and
  53448. ** successors. The result of the function is stored in register P3.
  53449. ** Register P3 must not be one of the function inputs.
  53450. **
  53451. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  53452. ** function was determined to be constant at compile time. If the first
  53453. ** argument was constant then bit 0 of P1 is set. This is used to determine
  53454. ** whether meta data associated with a user function argument using the
  53455. ** sqlite3_set_auxdata() API may be safely retained until the next
  53456. ** invocation of this opcode.
  53457. **
  53458. ** See also: AggStep and AggFinal
  53459. */
  53460. case OP_Function: {
  53461. #if 0 /* local variables moved into u.ai */
  53462. int i;
  53463. Mem *pArg;
  53464. sqlite3_context ctx;
  53465. sqlite3_value **apVal;
  53466. int n;
  53467. #endif /* local variables moved into u.ai */
  53468. u.ai.n = pOp->p5;
  53469. u.ai.apVal = p->apArg;
  53470. assert( u.ai.apVal || u.ai.n==0 );
  53471. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  53472. pOut = &aMem[pOp->p3];
  53473. memAboutToChange(p, pOut);
  53474. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) );
  53475. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  53476. u.ai.pArg = &aMem[pOp->p2];
  53477. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  53478. assert( memIsValid(u.ai.pArg) );
  53479. u.ai.apVal[u.ai.i] = u.ai.pArg;
  53480. Deephemeralize(u.ai.pArg);
  53481. sqlite3VdbeMemStoreType(u.ai.pArg);
  53482. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  53483. }
  53484. assert( pOp->p4type==P4_FUNCDEF );
  53485. u.ai.ctx.pFunc = pOp->p4.pFunc;
  53486. u.ai.ctx.s.flags = MEM_Null;
  53487. u.ai.ctx.s.db = db;
  53488. u.ai.ctx.s.xDel = 0;
  53489. u.ai.ctx.s.zMalloc = 0;
  53490. u.ai.ctx.iOp = pc;
  53491. u.ai.ctx.pVdbe = p;
  53492. /* The output cell may already have a buffer allocated. Move
  53493. ** the pointer to u.ai.ctx.s so in case the user-function can use
  53494. ** the already allocated buffer instead of allocating a new one.
  53495. */
  53496. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  53497. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  53498. u.ai.ctx.fErrorOrAux = 0;
  53499. if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  53500. assert( pOp>aOp );
  53501. assert( pOp[-1].p4type==P4_COLLSEQ );
  53502. assert( pOp[-1].opcode==OP_CollSeq );
  53503. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  53504. }
  53505. db->lastRowid = lastRowid;
  53506. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  53507. lastRowid = db->lastRowid;
  53508. if( db->mallocFailed ){
  53509. /* Even though a malloc() has failed, the implementation of the
  53510. ** user function may have called an sqlite3_result_XXX() function
  53511. ** to return a value. The following call releases any resources
  53512. ** associated with such a value.
  53513. */
  53514. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  53515. goto no_mem;
  53516. }
  53517. /* If the function returned an error, throw an exception */
  53518. if( u.ai.ctx.fErrorOrAux ){
  53519. if( u.ai.ctx.isError ){
  53520. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  53521. rc = u.ai.ctx.isError;
  53522. }
  53523. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  53524. }
  53525. /* Copy the result of the function into register P3 */
  53526. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  53527. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  53528. if( sqlite3VdbeMemTooBig(pOut) ){
  53529. goto too_big;
  53530. }
  53531. #if 0
  53532. /* The app-defined function has done something that as caused this
  53533. ** statement to expire. (Perhaps the function called sqlite3_exec()
  53534. ** with a CREATE TABLE statement.)
  53535. */
  53536. if( p->expired ) rc = SQLITE_ABORT;
  53537. #endif
  53538. REGISTER_TRACE(pOp->p3, pOut);
  53539. UPDATE_MAX_BLOBSIZE(pOut);
  53540. break;
  53541. }
  53542. /* Opcode: BitAnd P1 P2 P3 * *
  53543. **
  53544. ** Take the bit-wise AND of the values in register P1 and P2 and
  53545. ** store the result in register P3.
  53546. ** If either input is NULL, the result is NULL.
  53547. */
  53548. /* Opcode: BitOr P1 P2 P3 * *
  53549. **
  53550. ** Take the bit-wise OR of the values in register P1 and P2 and
  53551. ** store the result in register P3.
  53552. ** If either input is NULL, the result is NULL.
  53553. */
  53554. /* Opcode: ShiftLeft P1 P2 P3 * *
  53555. **
  53556. ** Shift the integer value in register P2 to the left by the
  53557. ** number of bits specified by the integer in register P1.
  53558. ** Store the result in register P3.
  53559. ** If either input is NULL, the result is NULL.
  53560. */
  53561. /* Opcode: ShiftRight P1 P2 P3 * *
  53562. **
  53563. ** Shift the integer value in register P2 to the right by the
  53564. ** number of bits specified by the integer in register P1.
  53565. ** Store the result in register P3.
  53566. ** If either input is NULL, the result is NULL.
  53567. */
  53568. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  53569. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  53570. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  53571. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  53572. #if 0 /* local variables moved into u.aj */
  53573. i64 iA;
  53574. u64 uA;
  53575. i64 iB;
  53576. u8 op;
  53577. #endif /* local variables moved into u.aj */
  53578. pIn1 = &aMem[pOp->p1];
  53579. pIn2 = &aMem[pOp->p2];
  53580. pOut = &aMem[pOp->p3];
  53581. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  53582. sqlite3VdbeMemSetNull(pOut);
  53583. break;
  53584. }
  53585. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  53586. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  53587. u.aj.op = pOp->opcode;
  53588. if( u.aj.op==OP_BitAnd ){
  53589. u.aj.iA &= u.aj.iB;
  53590. }else if( u.aj.op==OP_BitOr ){
  53591. u.aj.iA |= u.aj.iB;
  53592. }else if( u.aj.iB!=0 ){
  53593. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  53594. /* If shifting by a negative amount, shift in the other direction */
  53595. if( u.aj.iB<0 ){
  53596. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  53597. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  53598. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  53599. }
  53600. if( u.aj.iB>=64 ){
  53601. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  53602. }else{
  53603. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  53604. if( u.aj.op==OP_ShiftLeft ){
  53605. u.aj.uA <<= u.aj.iB;
  53606. }else{
  53607. u.aj.uA >>= u.aj.iB;
  53608. /* Sign-extend on a right shift of a negative number */
  53609. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  53610. }
  53611. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  53612. }
  53613. }
  53614. pOut->u.i = u.aj.iA;
  53615. MemSetTypeFlag(pOut, MEM_Int);
  53616. break;
  53617. }
  53618. /* Opcode: AddImm P1 P2 * * *
  53619. **
  53620. ** Add the constant P2 to the value in register P1.
  53621. ** The result is always an integer.
  53622. **
  53623. ** To force any register to be an integer, just add 0.
  53624. */
  53625. case OP_AddImm: { /* in1 */
  53626. pIn1 = &aMem[pOp->p1];
  53627. memAboutToChange(p, pIn1);
  53628. sqlite3VdbeMemIntegerify(pIn1);
  53629. pIn1->u.i += pOp->p2;
  53630. break;
  53631. }
  53632. /* Opcode: MustBeInt P1 P2 * * *
  53633. **
  53634. ** Force the value in register P1 to be an integer. If the value
  53635. ** in P1 is not an integer and cannot be converted into an integer
  53636. ** without data loss, then jump immediately to P2, or if P2==0
  53637. ** raise an SQLITE_MISMATCH exception.
  53638. */
  53639. case OP_MustBeInt: { /* jump, in1 */
  53640. pIn1 = &aMem[pOp->p1];
  53641. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  53642. if( (pIn1->flags & MEM_Int)==0 ){
  53643. if( pOp->p2==0 ){
  53644. rc = SQLITE_MISMATCH;
  53645. goto abort_due_to_error;
  53646. }else{
  53647. pc = pOp->p2 - 1;
  53648. }
  53649. }else{
  53650. MemSetTypeFlag(pIn1, MEM_Int);
  53651. }
  53652. break;
  53653. }
  53654. #ifndef SQLITE_OMIT_FLOATING_POINT
  53655. /* Opcode: RealAffinity P1 * * * *
  53656. **
  53657. ** If register P1 holds an integer convert it to a real value.
  53658. **
  53659. ** This opcode is used when extracting information from a column that
  53660. ** has REAL affinity. Such column values may still be stored as
  53661. ** integers, for space efficiency, but after extraction we want them
  53662. ** to have only a real value.
  53663. */
  53664. case OP_RealAffinity: { /* in1 */
  53665. pIn1 = &aMem[pOp->p1];
  53666. if( pIn1->flags & MEM_Int ){
  53667. sqlite3VdbeMemRealify(pIn1);
  53668. }
  53669. break;
  53670. }
  53671. #endif
  53672. #ifndef SQLITE_OMIT_CAST
  53673. /* Opcode: ToText P1 * * * *
  53674. **
  53675. ** Force the value in register P1 to be text.
  53676. ** If the value is numeric, convert it to a string using the
  53677. ** equivalent of printf(). Blob values are unchanged and
  53678. ** are afterwards simply interpreted as text.
  53679. **
  53680. ** A NULL value is not changed by this routine. It remains NULL.
  53681. */
  53682. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  53683. pIn1 = &aMem[pOp->p1];
  53684. memAboutToChange(p, pIn1);
  53685. if( pIn1->flags & MEM_Null ) break;
  53686. assert( MEM_Str==(MEM_Blob>>3) );
  53687. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  53688. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  53689. rc = ExpandBlob(pIn1);
  53690. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  53691. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  53692. UPDATE_MAX_BLOBSIZE(pIn1);
  53693. break;
  53694. }
  53695. /* Opcode: ToBlob P1 * * * *
  53696. **
  53697. ** Force the value in register P1 to be a BLOB.
  53698. ** If the value is numeric, convert it to a string first.
  53699. ** Strings are simply reinterpreted as blobs with no change
  53700. ** to the underlying data.
  53701. **
  53702. ** A NULL value is not changed by this routine. It remains NULL.
  53703. */
  53704. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  53705. pIn1 = &aMem[pOp->p1];
  53706. if( pIn1->flags & MEM_Null ) break;
  53707. if( (pIn1->flags & MEM_Blob)==0 ){
  53708. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  53709. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  53710. MemSetTypeFlag(pIn1, MEM_Blob);
  53711. }else{
  53712. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  53713. }
  53714. UPDATE_MAX_BLOBSIZE(pIn1);
  53715. break;
  53716. }
  53717. /* Opcode: ToNumeric P1 * * * *
  53718. **
  53719. ** Force the value in register P1 to be numeric (either an
  53720. ** integer or a floating-point number.)
  53721. ** If the value is text or blob, try to convert it to an using the
  53722. ** equivalent of atoi() or atof() and store 0 if no such conversion
  53723. ** is possible.
  53724. **
  53725. ** A NULL value is not changed by this routine. It remains NULL.
  53726. */
  53727. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  53728. pIn1 = &aMem[pOp->p1];
  53729. sqlite3VdbeMemNumerify(pIn1);
  53730. break;
  53731. }
  53732. #endif /* SQLITE_OMIT_CAST */
  53733. /* Opcode: ToInt P1 * * * *
  53734. **
  53735. ** Force the value in register P1 to be an integer. If
  53736. ** The value is currently a real number, drop its fractional part.
  53737. ** If the value is text or blob, try to convert it to an integer using the
  53738. ** equivalent of atoi() and store 0 if no such conversion is possible.
  53739. **
  53740. ** A NULL value is not changed by this routine. It remains NULL.
  53741. */
  53742. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  53743. pIn1 = &aMem[pOp->p1];
  53744. if( (pIn1->flags & MEM_Null)==0 ){
  53745. sqlite3VdbeMemIntegerify(pIn1);
  53746. }
  53747. break;
  53748. }
  53749. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  53750. /* Opcode: ToReal P1 * * * *
  53751. **
  53752. ** Force the value in register P1 to be a floating point number.
  53753. ** If The value is currently an integer, convert it.
  53754. ** If the value is text or blob, try to convert it to an integer using the
  53755. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  53756. **
  53757. ** A NULL value is not changed by this routine. It remains NULL.
  53758. */
  53759. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  53760. pIn1 = &aMem[pOp->p1];
  53761. memAboutToChange(p, pIn1);
  53762. if( (pIn1->flags & MEM_Null)==0 ){
  53763. sqlite3VdbeMemRealify(pIn1);
  53764. }
  53765. break;
  53766. }
  53767. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  53768. /* Opcode: Lt P1 P2 P3 P4 P5
  53769. **
  53770. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  53771. ** jump to address P2.
  53772. **
  53773. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  53774. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  53775. ** bit is clear then fall through if either operand is NULL.
  53776. **
  53777. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  53778. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  53779. ** to coerce both inputs according to this affinity before the
  53780. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  53781. ** affinity is used. Note that the affinity conversions are stored
  53782. ** back into the input registers P1 and P3. So this opcode can cause
  53783. ** persistent changes to registers P1 and P3.
  53784. **
  53785. ** Once any conversions have taken place, and neither value is NULL,
  53786. ** the values are compared. If both values are blobs then memcmp() is
  53787. ** used to determine the results of the comparison. If both values
  53788. ** are text, then the appropriate collating function specified in
  53789. ** P4 is used to do the comparison. If P4 is not specified then
  53790. ** memcmp() is used to compare text string. If both values are
  53791. ** numeric, then a numeric comparison is used. If the two values
  53792. ** are of different types, then numbers are considered less than
  53793. ** strings and strings are considered less than blobs.
  53794. **
  53795. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  53796. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  53797. **
  53798. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  53799. ** equal to one another, provided that they do not have their MEM_Cleared
  53800. ** bit set.
  53801. */
  53802. /* Opcode: Ne P1 P2 P3 P4 P5
  53803. **
  53804. ** This works just like the Lt opcode except that the jump is taken if
  53805. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  53806. ** additional information.
  53807. **
  53808. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  53809. ** true or false and is never NULL. If both operands are NULL then the result
  53810. ** of comparison is false. If either operand is NULL then the result is true.
  53811. ** If neither operand is NULL the result is the same as it would be if
  53812. ** the SQLITE_NULLEQ flag were omitted from P5.
  53813. */
  53814. /* Opcode: Eq P1 P2 P3 P4 P5
  53815. **
  53816. ** This works just like the Lt opcode except that the jump is taken if
  53817. ** the operands in registers P1 and P3 are equal.
  53818. ** See the Lt opcode for additional information.
  53819. **
  53820. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  53821. ** true or false and is never NULL. If both operands are NULL then the result
  53822. ** of comparison is true. If either operand is NULL then the result is false.
  53823. ** If neither operand is NULL the result is the same as it would be if
  53824. ** the SQLITE_NULLEQ flag were omitted from P5.
  53825. */
  53826. /* Opcode: Le P1 P2 P3 P4 P5
  53827. **
  53828. ** This works just like the Lt opcode except that the jump is taken if
  53829. ** the content of register P3 is less than or equal to the content of
  53830. ** register P1. See the Lt opcode for additional information.
  53831. */
  53832. /* Opcode: Gt P1 P2 P3 P4 P5
  53833. **
  53834. ** This works just like the Lt opcode except that the jump is taken if
  53835. ** the content of register P3 is greater than the content of
  53836. ** register P1. See the Lt opcode for additional information.
  53837. */
  53838. /* Opcode: Ge P1 P2 P3 P4 P5
  53839. **
  53840. ** This works just like the Lt opcode except that the jump is taken if
  53841. ** the content of register P3 is greater than or equal to the content of
  53842. ** register P1. See the Lt opcode for additional information.
  53843. */
  53844. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  53845. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  53846. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  53847. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  53848. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  53849. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  53850. #if 0 /* local variables moved into u.ak */
  53851. int res; /* Result of the comparison of pIn1 against pIn3 */
  53852. char affinity; /* Affinity to use for comparison */
  53853. u16 flags1; /* Copy of initial value of pIn1->flags */
  53854. u16 flags3; /* Copy of initial value of pIn3->flags */
  53855. #endif /* local variables moved into u.ak */
  53856. pIn1 = &aMem[pOp->p1];
  53857. pIn3 = &aMem[pOp->p3];
  53858. u.ak.flags1 = pIn1->flags;
  53859. u.ak.flags3 = pIn3->flags;
  53860. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  53861. /* One or both operands are NULL */
  53862. if( pOp->p5 & SQLITE_NULLEQ ){
  53863. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  53864. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  53865. ** or not both operands are null.
  53866. */
  53867. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  53868. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  53869. if( (u.ak.flags1&MEM_Null)!=0
  53870. && (u.ak.flags3&MEM_Null)!=0
  53871. && (u.ak.flags3&MEM_Cleared)==0
  53872. ){
  53873. u.ak.res = 0; /* Results are equal */
  53874. }else{
  53875. u.ak.res = 1; /* Results are not equal */
  53876. }
  53877. }else{
  53878. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  53879. ** then the result is always NULL.
  53880. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  53881. */
  53882. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  53883. pc = pOp->p2-1;
  53884. }else if( pOp->p5 & SQLITE_STOREP2 ){
  53885. pOut = &aMem[pOp->p2];
  53886. MemSetTypeFlag(pOut, MEM_Null);
  53887. REGISTER_TRACE(pOp->p2, pOut);
  53888. }
  53889. break;
  53890. }
  53891. }else{
  53892. /* Neither operand is NULL. Do a comparison. */
  53893. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  53894. if( u.ak.affinity ){
  53895. applyAffinity(pIn1, u.ak.affinity, encoding);
  53896. applyAffinity(pIn3, u.ak.affinity, encoding);
  53897. if( db->mallocFailed ) goto no_mem;
  53898. }
  53899. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  53900. ExpandBlob(pIn1);
  53901. ExpandBlob(pIn3);
  53902. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  53903. }
  53904. switch( pOp->opcode ){
  53905. case OP_Eq: u.ak.res = u.ak.res==0; break;
  53906. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  53907. case OP_Lt: u.ak.res = u.ak.res<0; break;
  53908. case OP_Le: u.ak.res = u.ak.res<=0; break;
  53909. case OP_Gt: u.ak.res = u.ak.res>0; break;
  53910. default: u.ak.res = u.ak.res>=0; break;
  53911. }
  53912. if( pOp->p5 & SQLITE_STOREP2 ){
  53913. pOut = &aMem[pOp->p2];
  53914. memAboutToChange(p, pOut);
  53915. MemSetTypeFlag(pOut, MEM_Int);
  53916. pOut->u.i = u.ak.res;
  53917. REGISTER_TRACE(pOp->p2, pOut);
  53918. }else if( u.ak.res ){
  53919. pc = pOp->p2-1;
  53920. }
  53921. /* Undo any changes made by applyAffinity() to the input registers. */
  53922. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  53923. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  53924. break;
  53925. }
  53926. /* Opcode: Permutation * * * P4 *
  53927. **
  53928. ** Set the permutation used by the OP_Compare operator to be the array
  53929. ** of integers in P4.
  53930. **
  53931. ** The permutation is only valid until the next OP_Compare that has
  53932. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  53933. ** occur immediately prior to the OP_Compare.
  53934. */
  53935. case OP_Permutation: {
  53936. assert( pOp->p4type==P4_INTARRAY );
  53937. assert( pOp->p4.ai );
  53938. aPermute = pOp->p4.ai;
  53939. break;
  53940. }
  53941. /* Opcode: Compare P1 P2 P3 P4 P5
  53942. **
  53943. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  53944. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  53945. ** the comparison for use by the next OP_Jump instruct.
  53946. **
  53947. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  53948. ** determined by the most recent OP_Permutation operator. If the
  53949. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  53950. ** order.
  53951. **
  53952. ** P4 is a KeyInfo structure that defines collating sequences and sort
  53953. ** orders for the comparison. The permutation applies to registers
  53954. ** only. The KeyInfo elements are used sequentially.
  53955. **
  53956. ** The comparison is a sort comparison, so NULLs compare equal,
  53957. ** NULLs are less than numbers, numbers are less than strings,
  53958. ** and strings are less than blobs.
  53959. */
  53960. case OP_Compare: {
  53961. #if 0 /* local variables moved into u.al */
  53962. int n;
  53963. int i;
  53964. int p1;
  53965. int p2;
  53966. const KeyInfo *pKeyInfo;
  53967. int idx;
  53968. CollSeq *pColl; /* Collating sequence to use on this term */
  53969. int bRev; /* True for DESCENDING sort order */
  53970. #endif /* local variables moved into u.al */
  53971. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  53972. u.al.n = pOp->p3;
  53973. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  53974. assert( u.al.n>0 );
  53975. assert( u.al.pKeyInfo!=0 );
  53976. u.al.p1 = pOp->p1;
  53977. u.al.p2 = pOp->p2;
  53978. #if SQLITE_DEBUG
  53979. if( aPermute ){
  53980. int k, mx = 0;
  53981. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  53982. assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 );
  53983. assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 );
  53984. }else{
  53985. assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 );
  53986. assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 );
  53987. }
  53988. #endif /* SQLITE_DEBUG */
  53989. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  53990. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  53991. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  53992. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  53993. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  53994. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  53995. assert( u.al.i<u.al.pKeyInfo->nField );
  53996. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  53997. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  53998. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  53999. if( iCompare ){
  54000. if( u.al.bRev ) iCompare = -iCompare;
  54001. break;
  54002. }
  54003. }
  54004. aPermute = 0;
  54005. break;
  54006. }
  54007. /* Opcode: Jump P1 P2 P3 * *
  54008. **
  54009. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  54010. ** in the most recent OP_Compare instruction the P1 vector was less than
  54011. ** equal to, or greater than the P2 vector, respectively.
  54012. */
  54013. case OP_Jump: { /* jump */
  54014. if( iCompare<0 ){
  54015. pc = pOp->p1 - 1;
  54016. }else if( iCompare==0 ){
  54017. pc = pOp->p2 - 1;
  54018. }else{
  54019. pc = pOp->p3 - 1;
  54020. }
  54021. break;
  54022. }
  54023. /* Opcode: And P1 P2 P3 * *
  54024. **
  54025. ** Take the logical AND of the values in registers P1 and P2 and
  54026. ** write the result into register P3.
  54027. **
  54028. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  54029. ** the other input is NULL. A NULL and true or two NULLs give
  54030. ** a NULL output.
  54031. */
  54032. /* Opcode: Or P1 P2 P3 * *
  54033. **
  54034. ** Take the logical OR of the values in register P1 and P2 and
  54035. ** store the answer in register P3.
  54036. **
  54037. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  54038. ** even if the other input is NULL. A NULL and false or two NULLs
  54039. ** give a NULL output.
  54040. */
  54041. case OP_And: /* same as TK_AND, in1, in2, out3 */
  54042. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  54043. #if 0 /* local variables moved into u.am */
  54044. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  54045. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  54046. #endif /* local variables moved into u.am */
  54047. pIn1 = &aMem[pOp->p1];
  54048. if( pIn1->flags & MEM_Null ){
  54049. u.am.v1 = 2;
  54050. }else{
  54051. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  54052. }
  54053. pIn2 = &aMem[pOp->p2];
  54054. if( pIn2->flags & MEM_Null ){
  54055. u.am.v2 = 2;
  54056. }else{
  54057. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  54058. }
  54059. if( pOp->opcode==OP_And ){
  54060. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  54061. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  54062. }else{
  54063. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  54064. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  54065. }
  54066. pOut = &aMem[pOp->p3];
  54067. if( u.am.v1==2 ){
  54068. MemSetTypeFlag(pOut, MEM_Null);
  54069. }else{
  54070. pOut->u.i = u.am.v1;
  54071. MemSetTypeFlag(pOut, MEM_Int);
  54072. }
  54073. break;
  54074. }
  54075. /* Opcode: Not P1 P2 * * *
  54076. **
  54077. ** Interpret the value in register P1 as a boolean value. Store the
  54078. ** boolean complement in register P2. If the value in register P1 is
  54079. ** NULL, then a NULL is stored in P2.
  54080. */
  54081. case OP_Not: { /* same as TK_NOT, in1, out2 */
  54082. pIn1 = &aMem[pOp->p1];
  54083. pOut = &aMem[pOp->p2];
  54084. if( pIn1->flags & MEM_Null ){
  54085. sqlite3VdbeMemSetNull(pOut);
  54086. }else{
  54087. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  54088. }
  54089. break;
  54090. }
  54091. /* Opcode: BitNot P1 P2 * * *
  54092. **
  54093. ** Interpret the content of register P1 as an integer. Store the
  54094. ** ones-complement of the P1 value into register P2. If P1 holds
  54095. ** a NULL then store a NULL in P2.
  54096. */
  54097. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  54098. pIn1 = &aMem[pOp->p1];
  54099. pOut = &aMem[pOp->p2];
  54100. if( pIn1->flags & MEM_Null ){
  54101. sqlite3VdbeMemSetNull(pOut);
  54102. }else{
  54103. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  54104. }
  54105. break;
  54106. }
  54107. /* Opcode: Once P1 P2 * * *
  54108. **
  54109. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  54110. ** set the flag and fall through to the next instruction.
  54111. */
  54112. case OP_Once: { /* jump */
  54113. assert( pOp->p1<p->nOnceFlag );
  54114. if( p->aOnceFlag[pOp->p1] ){
  54115. pc = pOp->p2-1;
  54116. }else{
  54117. p->aOnceFlag[pOp->p1] = 1;
  54118. }
  54119. break;
  54120. }
  54121. /* Opcode: If P1 P2 P3 * *
  54122. **
  54123. ** Jump to P2 if the value in register P1 is true. The value
  54124. ** is considered true if it is numeric and non-zero. If the value
  54125. ** in P1 is NULL then take the jump if P3 is non-zero.
  54126. */
  54127. /* Opcode: IfNot P1 P2 P3 * *
  54128. **
  54129. ** Jump to P2 if the value in register P1 is False. The value
  54130. ** is considered false if it has a numeric value of zero. If the value
  54131. ** in P1 is NULL then take the jump if P3 is zero.
  54132. */
  54133. case OP_If: /* jump, in1 */
  54134. case OP_IfNot: { /* jump, in1 */
  54135. #if 0 /* local variables moved into u.an */
  54136. int c;
  54137. #endif /* local variables moved into u.an */
  54138. pIn1 = &aMem[pOp->p1];
  54139. if( pIn1->flags & MEM_Null ){
  54140. u.an.c = pOp->p3;
  54141. }else{
  54142. #ifdef SQLITE_OMIT_FLOATING_POINT
  54143. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  54144. #else
  54145. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  54146. #endif
  54147. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  54148. }
  54149. if( u.an.c ){
  54150. pc = pOp->p2-1;
  54151. }
  54152. break;
  54153. }
  54154. /* Opcode: IsNull P1 P2 * * *
  54155. **
  54156. ** Jump to P2 if the value in register P1 is NULL.
  54157. */
  54158. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  54159. pIn1 = &aMem[pOp->p1];
  54160. if( (pIn1->flags & MEM_Null)!=0 ){
  54161. pc = pOp->p2 - 1;
  54162. }
  54163. break;
  54164. }
  54165. /* Opcode: NotNull P1 P2 * * *
  54166. **
  54167. ** Jump to P2 if the value in register P1 is not NULL.
  54168. */
  54169. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  54170. pIn1 = &aMem[pOp->p1];
  54171. if( (pIn1->flags & MEM_Null)==0 ){
  54172. pc = pOp->p2 - 1;
  54173. }
  54174. break;
  54175. }
  54176. /* Opcode: Column P1 P2 P3 P4 P5
  54177. **
  54178. ** Interpret the data that cursor P1 points to as a structure built using
  54179. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  54180. ** information about the format of the data.) Extract the P2-th column
  54181. ** from this record. If there are less that (P2+1)
  54182. ** values in the record, extract a NULL.
  54183. **
  54184. ** The value extracted is stored in register P3.
  54185. **
  54186. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  54187. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  54188. ** the result.
  54189. **
  54190. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  54191. ** then the cache of the cursor is reset prior to extracting the column.
  54192. ** The first OP_Column against a pseudo-table after the value of the content
  54193. ** register has changed should have this bit set.
  54194. **
  54195. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  54196. ** the result is guaranteed to only be used as the argument of a length()
  54197. ** or typeof() function, respectively. The loading of large blobs can be
  54198. ** skipped for length() and all content loading can be skipped for typeof().
  54199. */
  54200. case OP_Column: {
  54201. #if 0 /* local variables moved into u.ao */
  54202. u32 payloadSize; /* Number of bytes in the record */
  54203. i64 payloadSize64; /* Number of bytes in the record */
  54204. int p1; /* P1 value of the opcode */
  54205. int p2; /* column number to retrieve */
  54206. VdbeCursor *pC; /* The VDBE cursor */
  54207. char *zRec; /* Pointer to complete record-data */
  54208. BtCursor *pCrsr; /* The BTree cursor */
  54209. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  54210. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  54211. int nField; /* number of fields in the record */
  54212. int len; /* The length of the serialized data for the column */
  54213. int i; /* Loop counter */
  54214. char *zData; /* Part of the record being decoded */
  54215. Mem *pDest; /* Where to write the extracted value */
  54216. Mem sMem; /* For storing the record being decoded */
  54217. u8 *zIdx; /* Index into header */
  54218. u8 *zEndHdr; /* Pointer to first byte after the header */
  54219. u32 offset; /* Offset into the data */
  54220. u32 szField; /* Number of bytes in the content of a field */
  54221. int szHdr; /* Size of the header size field at start of record */
  54222. int avail; /* Number of bytes of available data */
  54223. u32 t; /* A type code from the record header */
  54224. Mem *pReg; /* PseudoTable input register */
  54225. #endif /* local variables moved into u.ao */
  54226. u.ao.p1 = pOp->p1;
  54227. u.ao.p2 = pOp->p2;
  54228. u.ao.pC = 0;
  54229. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  54230. assert( u.ao.p1<p->nCursor );
  54231. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  54232. u.ao.pDest = &aMem[pOp->p3];
  54233. memAboutToChange(p, u.ao.pDest);
  54234. u.ao.zRec = 0;
  54235. /* This block sets the variable u.ao.payloadSize to be the total number of
  54236. ** bytes in the record.
  54237. **
  54238. ** u.ao.zRec is set to be the complete text of the record if it is available.
  54239. ** The complete record text is always available for pseudo-tables
  54240. ** If the record is stored in a cursor, the complete record text
  54241. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  54242. ** If the data is unavailable, u.ao.zRec is set to NULL.
  54243. **
  54244. ** We also compute the number of columns in the record. For cursors,
  54245. ** the number of columns is stored in the VdbeCursor.nField element.
  54246. */
  54247. u.ao.pC = p->apCsr[u.ao.p1];
  54248. assert( u.ao.pC!=0 );
  54249. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54250. assert( u.ao.pC->pVtabCursor==0 );
  54251. #endif
  54252. u.ao.pCrsr = u.ao.pC->pCursor;
  54253. if( u.ao.pCrsr!=0 ){
  54254. /* The record is stored in a B-Tree */
  54255. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  54256. if( rc ) goto abort_due_to_error;
  54257. if( u.ao.pC->nullRow ){
  54258. u.ao.payloadSize = 0;
  54259. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  54260. u.ao.payloadSize = u.ao.pC->payloadSize;
  54261. u.ao.zRec = (char*)u.ao.pC->aRow;
  54262. }else if( u.ao.pC->isIndex ){
  54263. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  54264. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  54265. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  54266. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  54267. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  54268. ** larger than 32 bits. */
  54269. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  54270. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  54271. }else{
  54272. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  54273. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  54274. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  54275. }
  54276. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  54277. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  54278. if( u.ao.pC->multiPseudo ){
  54279. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  54280. Deephemeralize(u.ao.pDest);
  54281. goto op_column_out;
  54282. }
  54283. assert( u.ao.pReg->flags & MEM_Blob );
  54284. assert( memIsValid(u.ao.pReg) );
  54285. u.ao.payloadSize = u.ao.pReg->n;
  54286. u.ao.zRec = u.ao.pReg->z;
  54287. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  54288. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  54289. }else{
  54290. /* Consider the row to be NULL */
  54291. u.ao.payloadSize = 0;
  54292. }
  54293. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  54294. ** nullRow or because of a corrupt database. */
  54295. if( u.ao.payloadSize==0 ){
  54296. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  54297. goto op_column_out;
  54298. }
  54299. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  54300. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  54301. goto too_big;
  54302. }
  54303. u.ao.nField = u.ao.pC->nField;
  54304. assert( u.ao.p2<u.ao.nField );
  54305. /* Read and parse the table header. Store the results of the parse
  54306. ** into the record header cache fields of the cursor.
  54307. */
  54308. u.ao.aType = u.ao.pC->aType;
  54309. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  54310. u.ao.aOffset = u.ao.pC->aOffset;
  54311. }else{
  54312. assert(u.ao.aType);
  54313. u.ao.avail = 0;
  54314. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  54315. u.ao.pC->payloadSize = u.ao.payloadSize;
  54316. u.ao.pC->cacheStatus = p->cacheCtr;
  54317. /* Figure out how many bytes are in the header */
  54318. if( u.ao.zRec ){
  54319. u.ao.zData = u.ao.zRec;
  54320. }else{
  54321. if( u.ao.pC->isIndex ){
  54322. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  54323. }else{
  54324. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  54325. }
  54326. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  54327. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  54328. ** having to make additional calls to fetch the content portion of
  54329. ** the record.
  54330. */
  54331. assert( u.ao.avail>=0 );
  54332. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  54333. u.ao.zRec = u.ao.zData;
  54334. u.ao.pC->aRow = (u8*)u.ao.zData;
  54335. }else{
  54336. u.ao.pC->aRow = 0;
  54337. }
  54338. }
  54339. /* The following assert is true in all cases except when
  54340. ** the database file has been corrupted externally.
  54341. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  54342. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  54343. /* Make sure a corrupt database has not given us an oversize header.
  54344. ** Do this now to avoid an oversize memory allocation.
  54345. **
  54346. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  54347. ** types use so much data space that there can only be 4096 and 32 of
  54348. ** them, respectively. So the maximum header length results from a
  54349. ** 3-byte type for each of the maximum of 32768 columns plus three
  54350. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  54351. */
  54352. if( u.ao.offset > 98307 ){
  54353. rc = SQLITE_CORRUPT_BKPT;
  54354. goto op_column_out;
  54355. }
  54356. /* Compute in u.ao.len the number of bytes of data we need to read in order
  54357. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  54358. ** u.ao.nField might be significantly less than the true number of columns
  54359. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  54360. ** We want to minimize u.ao.len in order to limit the size of the memory
  54361. ** allocation, especially if a corrupt database file has caused u.ao.offset
  54362. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  54363. ** still exceed Robson memory allocation limits on some configurations.
  54364. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  54365. ** will likely be much smaller since u.ao.nField will likely be less than
  54366. ** 20 or so. This insures that Robson memory allocation limits are
  54367. ** not exceeded even for corrupt database files.
  54368. */
  54369. u.ao.len = u.ao.nField*5 + 3;
  54370. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  54371. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  54372. ** record header in most cases. But they will fail to get the complete
  54373. ** record header if the record header does not fit on a single page
  54374. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  54375. ** acquire the complete header text.
  54376. */
  54377. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  54378. u.ao.sMem.flags = 0;
  54379. u.ao.sMem.db = 0;
  54380. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  54381. if( rc!=SQLITE_OK ){
  54382. goto op_column_out;
  54383. }
  54384. u.ao.zData = u.ao.sMem.z;
  54385. }
  54386. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  54387. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  54388. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  54389. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  54390. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  54391. ** of the record to the start of the data for the u.ao.i-th column
  54392. */
  54393. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  54394. if( u.ao.zIdx<u.ao.zEndHdr ){
  54395. u.ao.aOffset[u.ao.i] = u.ao.offset;
  54396. if( u.ao.zIdx[0]<0x80 ){
  54397. u.ao.t = u.ao.zIdx[0];
  54398. u.ao.zIdx++;
  54399. }else{
  54400. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  54401. }
  54402. u.ao.aType[u.ao.i] = u.ao.t;
  54403. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  54404. u.ao.offset += u.ao.szField;
  54405. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  54406. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  54407. break;
  54408. }
  54409. }else{
  54410. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  54411. ** record than SetNumColumns indicated there are columns in the
  54412. ** table. Set the u.ao.offset for any extra columns not present in
  54413. ** the record to 0. This tells code below to store the default value
  54414. ** for the column instead of deserializing a value from the record.
  54415. */
  54416. u.ao.aOffset[u.ao.i] = 0;
  54417. }
  54418. }
  54419. sqlite3VdbeMemRelease(&u.ao.sMem);
  54420. u.ao.sMem.flags = MEM_Null;
  54421. /* If we have read more header data than was contained in the header,
  54422. ** or if the end of the last field appears to be past the end of the
  54423. ** record, or if the end of the last field appears to be before the end
  54424. ** of the record (when all fields present), then we must be dealing
  54425. ** with a corrupt database.
  54426. */
  54427. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  54428. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  54429. rc = SQLITE_CORRUPT_BKPT;
  54430. goto op_column_out;
  54431. }
  54432. }
  54433. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  54434. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  54435. ** then there are not enough fields in the record to satisfy the
  54436. ** request. In this case, set the value NULL or to P4 if P4 is
  54437. ** a pointer to a Mem object.
  54438. */
  54439. if( u.ao.aOffset[u.ao.p2] ){
  54440. assert( rc==SQLITE_OK );
  54441. if( u.ao.zRec ){
  54442. /* This is the common case where the whole row fits on a single page */
  54443. VdbeMemRelease(u.ao.pDest);
  54444. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  54445. }else{
  54446. /* This branch happens only when the row overflows onto multiple pages */
  54447. u.ao.t = u.ao.aType[u.ao.p2];
  54448. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  54449. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  54450. ){
  54451. /* Content is irrelevant for the typeof() function and for
  54452. ** the length(X) function if X is a blob. So we might as well use
  54453. ** bogus content rather than reading content from disk. NULL works
  54454. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  54455. ** will work for everything else. */
  54456. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  54457. }else{
  54458. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  54459. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  54460. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  54461. &u.ao.sMem);
  54462. if( rc!=SQLITE_OK ){
  54463. goto op_column_out;
  54464. }
  54465. u.ao.zData = u.ao.sMem.z;
  54466. }
  54467. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  54468. }
  54469. u.ao.pDest->enc = encoding;
  54470. }else{
  54471. if( pOp->p4type==P4_MEM ){
  54472. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  54473. }else{
  54474. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  54475. }
  54476. }
  54477. /* If we dynamically allocated space to hold the data (in the
  54478. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  54479. ** dynamically allocated space over to the u.ao.pDest structure.
  54480. ** This prevents a memory copy.
  54481. */
  54482. if( u.ao.sMem.zMalloc ){
  54483. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  54484. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  54485. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  54486. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  54487. u.ao.pDest->flags |= MEM_Term;
  54488. u.ao.pDest->z = u.ao.sMem.z;
  54489. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  54490. }
  54491. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  54492. op_column_out:
  54493. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  54494. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  54495. break;
  54496. }
  54497. /* Opcode: Affinity P1 P2 * P4 *
  54498. **
  54499. ** Apply affinities to a range of P2 registers starting with P1.
  54500. **
  54501. ** P4 is a string that is P2 characters long. The nth character of the
  54502. ** string indicates the column affinity that should be used for the nth
  54503. ** memory cell in the range.
  54504. */
  54505. case OP_Affinity: {
  54506. #if 0 /* local variables moved into u.ap */
  54507. const char *zAffinity; /* The affinity to be applied */
  54508. char cAff; /* A single character of affinity */
  54509. #endif /* local variables moved into u.ap */
  54510. u.ap.zAffinity = pOp->p4.z;
  54511. assert( u.ap.zAffinity!=0 );
  54512. assert( u.ap.zAffinity[pOp->p2]==0 );
  54513. pIn1 = &aMem[pOp->p1];
  54514. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  54515. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  54516. assert( memIsValid(pIn1) );
  54517. ExpandBlob(pIn1);
  54518. applyAffinity(pIn1, u.ap.cAff, encoding);
  54519. pIn1++;
  54520. }
  54521. break;
  54522. }
  54523. /* Opcode: MakeRecord P1 P2 P3 P4 *
  54524. **
  54525. ** Convert P2 registers beginning with P1 into the [record format]
  54526. ** use as a data record in a database table or as a key
  54527. ** in an index. The OP_Column opcode can decode the record later.
  54528. **
  54529. ** P4 may be a string that is P2 characters long. The nth character of the
  54530. ** string indicates the column affinity that should be used for the nth
  54531. ** field of the index key.
  54532. **
  54533. ** The mapping from character to affinity is given by the SQLITE_AFF_
  54534. ** macros defined in sqliteInt.h.
  54535. **
  54536. ** If P4 is NULL then all index fields have the affinity NONE.
  54537. */
  54538. case OP_MakeRecord: {
  54539. #if 0 /* local variables moved into u.aq */
  54540. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  54541. Mem *pRec; /* The new record */
  54542. u64 nData; /* Number of bytes of data space */
  54543. int nHdr; /* Number of bytes of header space */
  54544. i64 nByte; /* Data space required for this record */
  54545. int nZero; /* Number of zero bytes at the end of the record */
  54546. int nVarint; /* Number of bytes in a varint */
  54547. u32 serial_type; /* Type field */
  54548. Mem *pData0; /* First field to be combined into the record */
  54549. Mem *pLast; /* Last field of the record */
  54550. int nField; /* Number of fields in the record */
  54551. char *zAffinity; /* The affinity string for the record */
  54552. int file_format; /* File format to use for encoding */
  54553. int i; /* Space used in zNewRecord[] */
  54554. int len; /* Length of a field */
  54555. #endif /* local variables moved into u.aq */
  54556. /* Assuming the record contains N fields, the record format looks
  54557. ** like this:
  54558. **
  54559. ** ------------------------------------------------------------------------
  54560. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  54561. ** ------------------------------------------------------------------------
  54562. **
  54563. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  54564. ** and so froth.
  54565. **
  54566. ** Each type field is a varint representing the serial type of the
  54567. ** corresponding data element (see sqlite3VdbeSerialType()). The
  54568. ** hdr-size field is also a varint which is the offset from the beginning
  54569. ** of the record to data0.
  54570. */
  54571. u.aq.nData = 0; /* Number of bytes of data space */
  54572. u.aq.nHdr = 0; /* Number of bytes of header space */
  54573. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  54574. u.aq.nField = pOp->p1;
  54575. u.aq.zAffinity = pOp->p4.z;
  54576. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 );
  54577. u.aq.pData0 = &aMem[u.aq.nField];
  54578. u.aq.nField = pOp->p2;
  54579. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  54580. u.aq.file_format = p->minWriteFileFormat;
  54581. /* Identify the output register */
  54582. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  54583. pOut = &aMem[pOp->p3];
  54584. memAboutToChange(p, pOut);
  54585. /* Loop through the elements that will make up the record to figure
  54586. ** out how much space is required for the new record.
  54587. */
  54588. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  54589. assert( memIsValid(u.aq.pRec) );
  54590. if( u.aq.zAffinity ){
  54591. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  54592. }
  54593. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  54594. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  54595. }
  54596. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  54597. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  54598. u.aq.nData += u.aq.len;
  54599. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  54600. if( u.aq.pRec->flags & MEM_Zero ){
  54601. /* Only pure zero-filled BLOBs can be input to this Opcode.
  54602. ** We do not allow blobs with a prefix and a zero-filled tail. */
  54603. u.aq.nZero += u.aq.pRec->u.nZero;
  54604. }else if( u.aq.len ){
  54605. u.aq.nZero = 0;
  54606. }
  54607. }
  54608. /* Add the initial header varint and total the size */
  54609. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  54610. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  54611. u.aq.nHdr++;
  54612. }
  54613. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  54614. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  54615. goto too_big;
  54616. }
  54617. /* Make sure the output register has a buffer large enough to store
  54618. ** the new record. The output register (pOp->p3) is not allowed to
  54619. ** be one of the input registers (because the following call to
  54620. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  54621. */
  54622. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  54623. goto no_mem;
  54624. }
  54625. u.aq.zNewRecord = (u8 *)pOut->z;
  54626. /* Write the record */
  54627. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  54628. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  54629. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  54630. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  54631. }
  54632. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  54633. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  54634. }
  54635. assert( u.aq.i==u.aq.nByte );
  54636. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  54637. pOut->n = (int)u.aq.nByte;
  54638. pOut->flags = MEM_Blob | MEM_Dyn;
  54639. pOut->xDel = 0;
  54640. if( u.aq.nZero ){
  54641. pOut->u.nZero = u.aq.nZero;
  54642. pOut->flags |= MEM_Zero;
  54643. }
  54644. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  54645. REGISTER_TRACE(pOp->p3, pOut);
  54646. UPDATE_MAX_BLOBSIZE(pOut);
  54647. break;
  54648. }
  54649. /* Opcode: Count P1 P2 * * *
  54650. **
  54651. ** Store the number of entries (an integer value) in the table or index
  54652. ** opened by cursor P1 in register P2
  54653. */
  54654. #ifndef SQLITE_OMIT_BTREECOUNT
  54655. case OP_Count: { /* out2-prerelease */
  54656. #if 0 /* local variables moved into u.ar */
  54657. i64 nEntry;
  54658. BtCursor *pCrsr;
  54659. #endif /* local variables moved into u.ar */
  54660. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  54661. if( ALWAYS(u.ar.pCrsr) ){
  54662. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  54663. }else{
  54664. u.ar.nEntry = 0;
  54665. }
  54666. pOut->u.i = u.ar.nEntry;
  54667. break;
  54668. }
  54669. #endif
  54670. /* Opcode: Savepoint P1 * * P4 *
  54671. **
  54672. ** Open, release or rollback the savepoint named by parameter P4, depending
  54673. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  54674. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  54675. */
  54676. case OP_Savepoint: {
  54677. #if 0 /* local variables moved into u.as */
  54678. int p1; /* Value of P1 operand */
  54679. char *zName; /* Name of savepoint */
  54680. int nName;
  54681. Savepoint *pNew;
  54682. Savepoint *pSavepoint;
  54683. Savepoint *pTmp;
  54684. int iSavepoint;
  54685. int ii;
  54686. #endif /* local variables moved into u.as */
  54687. u.as.p1 = pOp->p1;
  54688. u.as.zName = pOp->p4.z;
  54689. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  54690. ** transaction, then there cannot be any savepoints.
  54691. */
  54692. assert( db->pSavepoint==0 || db->autoCommit==0 );
  54693. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  54694. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  54695. assert( checkSavepointCount(db) );
  54696. assert( p->bIsReader );
  54697. if( u.as.p1==SAVEPOINT_BEGIN ){
  54698. if( db->nVdbeWrite>0 ){
  54699. /* A new savepoint cannot be created if there are active write
  54700. ** statements (i.e. open read/write incremental blob handles).
  54701. */
  54702. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  54703. "SQL statements in progress");
  54704. rc = SQLITE_BUSY;
  54705. }else{
  54706. u.as.nName = sqlite3Strlen30(u.as.zName);
  54707. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54708. /* This call is Ok even if this savepoint is actually a transaction
  54709. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  54710. ** If this is a transaction savepoint being opened, it is guaranteed
  54711. ** that the db->aVTrans[] array is empty. */
  54712. assert( db->autoCommit==0 || db->nVTrans==0 );
  54713. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  54714. db->nStatement+db->nSavepoint);
  54715. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  54716. #endif
  54717. /* Create a new savepoint structure. */
  54718. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  54719. if( u.as.pNew ){
  54720. u.as.pNew->zName = (char *)&u.as.pNew[1];
  54721. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  54722. /* If there is no open transaction, then mark this as a special
  54723. ** "transaction savepoint". */
  54724. if( db->autoCommit ){
  54725. db->autoCommit = 0;
  54726. db->isTransactionSavepoint = 1;
  54727. }else{
  54728. db->nSavepoint++;
  54729. }
  54730. /* Link the new savepoint into the database handle's list. */
  54731. u.as.pNew->pNext = db->pSavepoint;
  54732. db->pSavepoint = u.as.pNew;
  54733. u.as.pNew->nDeferredCons = db->nDeferredCons;
  54734. u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
  54735. }
  54736. }
  54737. }else{
  54738. u.as.iSavepoint = 0;
  54739. /* Find the named savepoint. If there is no such savepoint, then an
  54740. ** an error is returned to the user. */
  54741. for(
  54742. u.as.pSavepoint = db->pSavepoint;
  54743. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  54744. u.as.pSavepoint = u.as.pSavepoint->pNext
  54745. ){
  54746. u.as.iSavepoint++;
  54747. }
  54748. if( !u.as.pSavepoint ){
  54749. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  54750. rc = SQLITE_ERROR;
  54751. }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
  54752. /* It is not possible to release (commit) a savepoint if there are
  54753. ** active write statements.
  54754. */
  54755. sqlite3SetString(&p->zErrMsg, db,
  54756. "cannot release savepoint - SQL statements in progress"
  54757. );
  54758. rc = SQLITE_BUSY;
  54759. }else{
  54760. /* Determine whether or not this is a transaction savepoint. If so,
  54761. ** and this is a RELEASE command, then the current transaction
  54762. ** is committed.
  54763. */
  54764. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  54765. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  54766. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  54767. goto vdbe_return;
  54768. }
  54769. db->autoCommit = 1;
  54770. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  54771. p->pc = pc;
  54772. db->autoCommit = 0;
  54773. p->rc = rc = SQLITE_BUSY;
  54774. goto vdbe_return;
  54775. }
  54776. db->isTransactionSavepoint = 0;
  54777. rc = p->rc;
  54778. }else{
  54779. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  54780. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  54781. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  54782. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  54783. }
  54784. }
  54785. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  54786. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  54787. if( rc!=SQLITE_OK ){
  54788. goto abort_due_to_error;
  54789. }
  54790. }
  54791. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  54792. sqlite3ExpirePreparedStatements(db);
  54793. sqlite3ResetAllSchemasOfConnection(db);
  54794. db->flags = (db->flags | SQLITE_InternChanges);
  54795. }
  54796. }
  54797. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  54798. ** savepoints nested inside of the savepoint being operated on. */
  54799. while( db->pSavepoint!=u.as.pSavepoint ){
  54800. u.as.pTmp = db->pSavepoint;
  54801. db->pSavepoint = u.as.pTmp->pNext;
  54802. sqlite3DbFree(db, u.as.pTmp);
  54803. db->nSavepoint--;
  54804. }
  54805. /* If it is a RELEASE, then destroy the savepoint being operated on
  54806. ** too. If it is a ROLLBACK TO, then set the number of deferred
  54807. ** constraint violations present in the database to the value stored
  54808. ** when the savepoint was created. */
  54809. if( u.as.p1==SAVEPOINT_RELEASE ){
  54810. assert( u.as.pSavepoint==db->pSavepoint );
  54811. db->pSavepoint = u.as.pSavepoint->pNext;
  54812. sqlite3DbFree(db, u.as.pSavepoint);
  54813. if( !isTransaction ){
  54814. db->nSavepoint--;
  54815. }
  54816. }else{
  54817. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  54818. db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
  54819. }
  54820. if( !isTransaction ){
  54821. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  54822. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  54823. }
  54824. }
  54825. }
  54826. break;
  54827. }
  54828. /* Opcode: AutoCommit P1 P2 * * *
  54829. **
  54830. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  54831. ** back any currently active btree transactions. If there are any active
  54832. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  54833. ** there are active writing VMs or active VMs that use shared cache.
  54834. **
  54835. ** This instruction causes the VM to halt.
  54836. */
  54837. case OP_AutoCommit: {
  54838. #if 0 /* local variables moved into u.at */
  54839. int desiredAutoCommit;
  54840. int iRollback;
  54841. int turnOnAC;
  54842. #endif /* local variables moved into u.at */
  54843. u.at.desiredAutoCommit = pOp->p1;
  54844. u.at.iRollback = pOp->p2;
  54845. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  54846. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  54847. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  54848. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  54849. assert( p->bIsReader );
  54850. #if 0
  54851. if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
  54852. /* If this instruction implements a ROLLBACK and other VMs are
  54853. ** still running, and a transaction is active, return an error indicating
  54854. ** that the other VMs must complete first.
  54855. */
  54856. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  54857. "SQL statements in progress");
  54858. rc = SQLITE_BUSY;
  54859. }else
  54860. #endif
  54861. if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
  54862. /* If this instruction implements a COMMIT and other VMs are writing
  54863. ** return an error indicating that the other VMs must complete first.
  54864. */
  54865. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  54866. "SQL statements in progress");
  54867. rc = SQLITE_BUSY;
  54868. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  54869. if( u.at.iRollback ){
  54870. assert( u.at.desiredAutoCommit==1 );
  54871. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  54872. db->autoCommit = 1;
  54873. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  54874. goto vdbe_return;
  54875. }else{
  54876. db->autoCommit = (u8)u.at.desiredAutoCommit;
  54877. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  54878. p->pc = pc;
  54879. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  54880. p->rc = rc = SQLITE_BUSY;
  54881. goto vdbe_return;
  54882. }
  54883. }
  54884. assert( db->nStatement==0 );
  54885. sqlite3CloseSavepoints(db);
  54886. if( p->rc==SQLITE_OK ){
  54887. rc = SQLITE_DONE;
  54888. }else{
  54889. rc = SQLITE_ERROR;
  54890. }
  54891. goto vdbe_return;
  54892. }else{
  54893. sqlite3SetString(&p->zErrMsg, db,
  54894. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  54895. (u.at.iRollback)?"cannot rollback - no transaction is active":
  54896. "cannot commit - no transaction is active"));
  54897. rc = SQLITE_ERROR;
  54898. }
  54899. break;
  54900. }
  54901. /* Opcode: Transaction P1 P2 * * *
  54902. **
  54903. ** Begin a transaction. The transaction ends when a Commit or Rollback
  54904. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  54905. ** transaction might also be rolled back if an error is encountered.
  54906. **
  54907. ** P1 is the index of the database file on which the transaction is
  54908. ** started. Index 0 is the main database file and index 1 is the
  54909. ** file used for temporary tables. Indices of 2 or more are used for
  54910. ** attached databases.
  54911. **
  54912. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  54913. ** obtained on the database file when a write-transaction is started. No
  54914. ** other process can start another write transaction while this transaction is
  54915. ** underway. Starting a write transaction also creates a rollback journal. A
  54916. ** write transaction must be started before any changes can be made to the
  54917. ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  54918. ** also obtained on the file.
  54919. **
  54920. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  54921. ** true (this flag is set if the Vdbe may modify more than one row and may
  54922. ** throw an ABORT exception), a statement transaction may also be opened.
  54923. ** More specifically, a statement transaction is opened iff the database
  54924. ** connection is currently not in autocommit mode, or if there are other
  54925. ** active statements. A statement transaction allows the changes made by this
  54926. ** VDBE to be rolled back after an error without having to roll back the
  54927. ** entire transaction. If no error is encountered, the statement transaction
  54928. ** will automatically commit when the VDBE halts.
  54929. **
  54930. ** If P2 is zero, then a read-lock is obtained on the database file.
  54931. */
  54932. case OP_Transaction: {
  54933. #if 0 /* local variables moved into u.au */
  54934. Btree *pBt;
  54935. #endif /* local variables moved into u.au */
  54936. assert( p->bIsReader );
  54937. assert( p->readOnly==0 || pOp->p2==0 );
  54938. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  54939. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  54940. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  54941. rc = SQLITE_READONLY;
  54942. goto abort_due_to_error;
  54943. }
  54944. u.au.pBt = db->aDb[pOp->p1].pBt;
  54945. if( u.au.pBt ){
  54946. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  54947. if( rc==SQLITE_BUSY ){
  54948. p->pc = pc;
  54949. p->rc = rc = SQLITE_BUSY;
  54950. goto vdbe_return;
  54951. }
  54952. if( rc!=SQLITE_OK ){
  54953. goto abort_due_to_error;
  54954. }
  54955. if( pOp->p2 && p->usesStmtJournal
  54956. && (db->autoCommit==0 || db->nVdbeRead>1)
  54957. ){
  54958. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  54959. if( p->iStatement==0 ){
  54960. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  54961. db->nStatement++;
  54962. p->iStatement = db->nSavepoint + db->nStatement;
  54963. }
  54964. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  54965. if( rc==SQLITE_OK ){
  54966. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  54967. }
  54968. /* Store the current value of the database handles deferred constraint
  54969. ** counter. If the statement transaction needs to be rolled back,
  54970. ** the value of this counter needs to be restored too. */
  54971. p->nStmtDefCons = db->nDeferredCons;
  54972. p->nStmtDefImmCons = db->nDeferredImmCons;
  54973. }
  54974. }
  54975. break;
  54976. }
  54977. /* Opcode: ReadCookie P1 P2 P3 * *
  54978. **
  54979. ** Read cookie number P3 from database P1 and write it into register P2.
  54980. ** P3==1 is the schema version. P3==2 is the database format.
  54981. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  54982. ** the main database file and P1==1 is the database file used to store
  54983. ** temporary tables.
  54984. **
  54985. ** There must be a read-lock on the database (either a transaction
  54986. ** must be started or there must be an open cursor) before
  54987. ** executing this instruction.
  54988. */
  54989. case OP_ReadCookie: { /* out2-prerelease */
  54990. #if 0 /* local variables moved into u.av */
  54991. int iMeta;
  54992. int iDb;
  54993. int iCookie;
  54994. #endif /* local variables moved into u.av */
  54995. assert( p->bIsReader );
  54996. u.av.iDb = pOp->p1;
  54997. u.av.iCookie = pOp->p3;
  54998. assert( pOp->p3<SQLITE_N_BTREE_META );
  54999. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  55000. assert( db->aDb[u.av.iDb].pBt!=0 );
  55001. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  55002. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  55003. pOut->u.i = u.av.iMeta;
  55004. break;
  55005. }
  55006. /* Opcode: SetCookie P1 P2 P3 * *
  55007. **
  55008. ** Write the content of register P3 (interpreted as an integer)
  55009. ** into cookie number P2 of database P1. P2==1 is the schema version.
  55010. ** P2==2 is the database format. P2==3 is the recommended pager cache
  55011. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  55012. ** database file used to store temporary tables.
  55013. **
  55014. ** A transaction must be started before executing this opcode.
  55015. */
  55016. case OP_SetCookie: { /* in3 */
  55017. #if 0 /* local variables moved into u.aw */
  55018. Db *pDb;
  55019. #endif /* local variables moved into u.aw */
  55020. assert( pOp->p2<SQLITE_N_BTREE_META );
  55021. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  55022. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  55023. assert( p->readOnly==0 );
  55024. u.aw.pDb = &db->aDb[pOp->p1];
  55025. assert( u.aw.pDb->pBt!=0 );
  55026. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  55027. pIn3 = &aMem[pOp->p3];
  55028. sqlite3VdbeMemIntegerify(pIn3);
  55029. /* See note about index shifting on OP_ReadCookie */
  55030. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  55031. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  55032. /* When the schema cookie changes, record the new cookie internally */
  55033. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  55034. db->flags |= SQLITE_InternChanges;
  55035. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  55036. /* Record changes in the file format */
  55037. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  55038. }
  55039. if( pOp->p1==1 ){
  55040. /* Invalidate all prepared statements whenever the TEMP database
  55041. ** schema is changed. Ticket #1644 */
  55042. sqlite3ExpirePreparedStatements(db);
  55043. p->expired = 0;
  55044. }
  55045. break;
  55046. }
  55047. /* Opcode: VerifyCookie P1 P2 P3 * *
  55048. **
  55049. ** Check the value of global database parameter number 0 (the
  55050. ** schema version) and make sure it is equal to P2 and that the
  55051. ** generation counter on the local schema parse equals P3.
  55052. **
  55053. ** P1 is the database number which is 0 for the main database file
  55054. ** and 1 for the file holding temporary tables and some higher number
  55055. ** for auxiliary databases.
  55056. **
  55057. ** The cookie changes its value whenever the database schema changes.
  55058. ** This operation is used to detect when that the cookie has changed
  55059. ** and that the current process needs to reread the schema.
  55060. **
  55061. ** Either a transaction needs to have been started or an OP_Open needs
  55062. ** to be executed (to establish a read lock) before this opcode is
  55063. ** invoked.
  55064. */
  55065. case OP_VerifyCookie: {
  55066. #if 0 /* local variables moved into u.ax */
  55067. int iMeta;
  55068. int iGen;
  55069. Btree *pBt;
  55070. #endif /* local variables moved into u.ax */
  55071. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  55072. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  55073. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  55074. assert( p->bIsReader );
  55075. u.ax.pBt = db->aDb[pOp->p1].pBt;
  55076. if( u.ax.pBt ){
  55077. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  55078. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  55079. }else{
  55080. u.ax.iGen = u.ax.iMeta = 0;
  55081. }
  55082. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  55083. sqlite3DbFree(db, p->zErrMsg);
  55084. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  55085. /* If the schema-cookie from the database file matches the cookie
  55086. ** stored with the in-memory representation of the schema, do
  55087. ** not reload the schema from the database file.
  55088. **
  55089. ** If virtual-tables are in use, this is not just an optimization.
  55090. ** Often, v-tables store their data in other SQLite tables, which
  55091. ** are queried from within xNext() and other v-table methods using
  55092. ** prepared queries. If such a query is out-of-date, we do not want to
  55093. ** discard the database schema, as the user code implementing the
  55094. ** v-table would have to be ready for the sqlite3_vtab structure itself
  55095. ** to be invalidated whenever sqlite3_step() is called from within
  55096. ** a v-table method.
  55097. */
  55098. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  55099. sqlite3ResetOneSchema(db, pOp->p1);
  55100. }
  55101. p->expired = 1;
  55102. rc = SQLITE_SCHEMA;
  55103. }
  55104. break;
  55105. }
  55106. /* Opcode: OpenRead P1 P2 P3 P4 P5
  55107. **
  55108. ** Open a read-only cursor for the database table whose root page is
  55109. ** P2 in a database file. The database file is determined by P3.
  55110. ** P3==0 means the main database, P3==1 means the database used for
  55111. ** temporary tables, and P3>1 means used the corresponding attached
  55112. ** database. Give the new cursor an identifier of P1. The P1
  55113. ** values need not be contiguous but all P1 values should be small integers.
  55114. ** It is an error for P1 to be negative.
  55115. **
  55116. ** If P5!=0 then use the content of register P2 as the root page, not
  55117. ** the value of P2 itself.
  55118. **
  55119. ** There will be a read lock on the database whenever there is an
  55120. ** open cursor. If the database was unlocked prior to this instruction
  55121. ** then a read lock is acquired as part of this instruction. A read
  55122. ** lock allows other processes to read the database but prohibits
  55123. ** any other process from modifying the database. The read lock is
  55124. ** released when all cursors are closed. If this instruction attempts
  55125. ** to get a read lock but fails, the script terminates with an
  55126. ** SQLITE_BUSY error code.
  55127. **
  55128. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  55129. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  55130. ** structure, then said structure defines the content and collating
  55131. ** sequence of the index being opened. Otherwise, if P4 is an integer
  55132. ** value, it is set to the number of columns in the table.
  55133. **
  55134. ** See also OpenWrite.
  55135. */
  55136. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  55137. **
  55138. ** Open a read/write cursor named P1 on the table or index whose root
  55139. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  55140. ** root page.
  55141. **
  55142. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  55143. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  55144. ** structure, then said structure defines the content and collating
  55145. ** sequence of the index being opened. Otherwise, if P4 is an integer
  55146. ** value, it is set to the number of columns in the table, or to the
  55147. ** largest index of any column of the table that is actually used.
  55148. **
  55149. ** This instruction works just like OpenRead except that it opens the cursor
  55150. ** in read/write mode. For a given table, there can be one or more read-only
  55151. ** cursors or a single read/write cursor but not both.
  55152. **
  55153. ** See also OpenRead.
  55154. */
  55155. case OP_OpenRead:
  55156. case OP_OpenWrite: {
  55157. #if 0 /* local variables moved into u.ay */
  55158. int nField;
  55159. KeyInfo *pKeyInfo;
  55160. int p2;
  55161. int iDb;
  55162. int wrFlag;
  55163. Btree *pX;
  55164. VdbeCursor *pCur;
  55165. Db *pDb;
  55166. #endif /* local variables moved into u.ay */
  55167. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  55168. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  55169. assert( p->bIsReader );
  55170. assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
  55171. if( p->expired ){
  55172. rc = SQLITE_ABORT;
  55173. break;
  55174. }
  55175. u.ay.nField = 0;
  55176. u.ay.pKeyInfo = 0;
  55177. u.ay.p2 = pOp->p2;
  55178. u.ay.iDb = pOp->p3;
  55179. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  55180. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  55181. u.ay.pDb = &db->aDb[u.ay.iDb];
  55182. u.ay.pX = u.ay.pDb->pBt;
  55183. assert( u.ay.pX!=0 );
  55184. if( pOp->opcode==OP_OpenWrite ){
  55185. u.ay.wrFlag = 1;
  55186. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  55187. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  55188. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  55189. }
  55190. }else{
  55191. u.ay.wrFlag = 0;
  55192. }
  55193. if( pOp->p5 & OPFLAG_P2ISREG ){
  55194. assert( u.ay.p2>0 );
  55195. assert( u.ay.p2<=(p->nMem-p->nCursor) );
  55196. pIn2 = &aMem[u.ay.p2];
  55197. assert( memIsValid(pIn2) );
  55198. assert( (pIn2->flags & MEM_Int)!=0 );
  55199. sqlite3VdbeMemIntegerify(pIn2);
  55200. u.ay.p2 = (int)pIn2->u.i;
  55201. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  55202. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  55203. ** If there were a failure, the prepared statement would have halted
  55204. ** before reaching this instruction. */
  55205. if( NEVER(u.ay.p2<2) ) {
  55206. rc = SQLITE_CORRUPT_BKPT;
  55207. goto abort_due_to_error;
  55208. }
  55209. }
  55210. if( pOp->p4type==P4_KEYINFO ){
  55211. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  55212. u.ay.pKeyInfo->enc = ENC(p->db);
  55213. u.ay.nField = u.ay.pKeyInfo->nField+1;
  55214. }else if( pOp->p4type==P4_INT32 ){
  55215. u.ay.nField = pOp->p4.i;
  55216. }
  55217. assert( pOp->p1>=0 );
  55218. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  55219. if( u.ay.pCur==0 ) goto no_mem;
  55220. u.ay.pCur->nullRow = 1;
  55221. u.ay.pCur->isOrdered = 1;
  55222. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  55223. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  55224. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  55225. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  55226. /* Since it performs no memory allocation or IO, the only value that
  55227. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  55228. assert( rc==SQLITE_OK );
  55229. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  55230. ** SQLite used to check if the root-page flags were sane at this point
  55231. ** and report database corruption if they were not, but this check has
  55232. ** since moved into the btree layer. */
  55233. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  55234. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  55235. break;
  55236. }
  55237. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  55238. **
  55239. ** Open a new cursor P1 to a transient table.
  55240. ** The cursor is always opened read/write even if
  55241. ** the main database is read-only. The ephemeral
  55242. ** table is deleted automatically when the cursor is closed.
  55243. **
  55244. ** P2 is the number of columns in the ephemeral table.
  55245. ** The cursor points to a BTree table if P4==0 and to a BTree index
  55246. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  55247. ** that defines the format of keys in the index.
  55248. **
  55249. ** This opcode was once called OpenTemp. But that created
  55250. ** confusion because the term "temp table", might refer either
  55251. ** to a TEMP table at the SQL level, or to a table opened by
  55252. ** this opcode. Then this opcode was call OpenVirtual. But
  55253. ** that created confusion with the whole virtual-table idea.
  55254. **
  55255. ** The P5 parameter can be a mask of the BTREE_* flags defined
  55256. ** in btree.h. These flags control aspects of the operation of
  55257. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  55258. ** added automatically.
  55259. */
  55260. /* Opcode: OpenAutoindex P1 P2 * P4 *
  55261. **
  55262. ** This opcode works the same as OP_OpenEphemeral. It has a
  55263. ** different name to distinguish its use. Tables created using
  55264. ** by this opcode will be used for automatically created transient
  55265. ** indices in joins.
  55266. */
  55267. case OP_OpenAutoindex:
  55268. case OP_OpenEphemeral: {
  55269. #if 0 /* local variables moved into u.az */
  55270. VdbeCursor *pCx;
  55271. #endif /* local variables moved into u.az */
  55272. static const int vfsFlags =
  55273. SQLITE_OPEN_READWRITE |
  55274. SQLITE_OPEN_CREATE |
  55275. SQLITE_OPEN_EXCLUSIVE |
  55276. SQLITE_OPEN_DELETEONCLOSE |
  55277. SQLITE_OPEN_TRANSIENT_DB;
  55278. assert( pOp->p1>=0 );
  55279. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  55280. if( u.az.pCx==0 ) goto no_mem;
  55281. u.az.pCx->nullRow = 1;
  55282. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  55283. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  55284. if( rc==SQLITE_OK ){
  55285. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  55286. }
  55287. if( rc==SQLITE_OK ){
  55288. /* If a transient index is required, create it by calling
  55289. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  55290. ** opening it. If a transient table is required, just use the
  55291. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  55292. */
  55293. if( pOp->p4.pKeyInfo ){
  55294. int pgno;
  55295. assert( pOp->p4type==P4_KEYINFO );
  55296. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  55297. if( rc==SQLITE_OK ){
  55298. assert( pgno==MASTER_ROOT+1 );
  55299. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  55300. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  55301. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  55302. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  55303. }
  55304. u.az.pCx->isTable = 0;
  55305. }else{
  55306. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  55307. u.az.pCx->isTable = 1;
  55308. }
  55309. }
  55310. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  55311. u.az.pCx->isIndex = !u.az.pCx->isTable;
  55312. break;
  55313. }
  55314. /* Opcode: SorterOpen P1 P2 * P4 *
  55315. **
  55316. ** This opcode works like OP_OpenEphemeral except that it opens
  55317. ** a transient index that is specifically designed to sort large
  55318. ** tables using an external merge-sort algorithm.
  55319. */
  55320. case OP_SorterOpen: {
  55321. #if 0 /* local variables moved into u.ba */
  55322. VdbeCursor *pCx;
  55323. #endif /* local variables moved into u.ba */
  55324. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  55325. if( u.ba.pCx==0 ) goto no_mem;
  55326. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  55327. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  55328. u.ba.pCx->isSorter = 1;
  55329. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  55330. break;
  55331. }
  55332. /* Opcode: OpenPseudo P1 P2 P3 * P5
  55333. **
  55334. ** Open a new cursor that points to a fake table that contains a single
  55335. ** row of data. The content of that one row in the content of memory
  55336. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  55337. ** MEM_Blob content contained in register P2. When P5==1, then the
  55338. ** row is represented by P3 consecutive registers beginning with P2.
  55339. **
  55340. ** A pseudo-table created by this opcode is used to hold a single
  55341. ** row output from the sorter so that the row can be decomposed into
  55342. ** individual columns using the OP_Column opcode. The OP_Column opcode
  55343. ** is the only cursor opcode that works with a pseudo-table.
  55344. **
  55345. ** P3 is the number of fields in the records that will be stored by
  55346. ** the pseudo-table.
  55347. */
  55348. case OP_OpenPseudo: {
  55349. #if 0 /* local variables moved into u.bb */
  55350. VdbeCursor *pCx;
  55351. #endif /* local variables moved into u.bb */
  55352. assert( pOp->p1>=0 );
  55353. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  55354. if( u.bb.pCx==0 ) goto no_mem;
  55355. u.bb.pCx->nullRow = 1;
  55356. u.bb.pCx->pseudoTableReg = pOp->p2;
  55357. u.bb.pCx->isTable = 1;
  55358. u.bb.pCx->isIndex = 0;
  55359. u.bb.pCx->multiPseudo = pOp->p5;
  55360. break;
  55361. }
  55362. /* Opcode: Close P1 * * * *
  55363. **
  55364. ** Close a cursor previously opened as P1. If P1 is not
  55365. ** currently open, this instruction is a no-op.
  55366. */
  55367. case OP_Close: {
  55368. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55369. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  55370. p->apCsr[pOp->p1] = 0;
  55371. break;
  55372. }
  55373. /* Opcode: SeekGe P1 P2 P3 P4 *
  55374. **
  55375. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55376. ** use the value in register P3 as the key. If cursor P1 refers
  55377. ** to an SQL index, then P3 is the first in an array of P4 registers
  55378. ** that are used as an unpacked index key.
  55379. **
  55380. ** Reposition cursor P1 so that it points to the smallest entry that
  55381. ** is greater than or equal to the key value. If there are no records
  55382. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  55383. **
  55384. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  55385. */
  55386. /* Opcode: SeekGt P1 P2 P3 P4 *
  55387. **
  55388. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55389. ** use the value in register P3 as a key. If cursor P1 refers
  55390. ** to an SQL index, then P3 is the first in an array of P4 registers
  55391. ** that are used as an unpacked index key.
  55392. **
  55393. ** Reposition cursor P1 so that it points to the smallest entry that
  55394. ** is greater than the key value. If there are no records greater than
  55395. ** the key and P2 is not zero, then jump to P2.
  55396. **
  55397. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  55398. */
  55399. /* Opcode: SeekLt P1 P2 P3 P4 *
  55400. **
  55401. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55402. ** use the value in register P3 as a key. If cursor P1 refers
  55403. ** to an SQL index, then P3 is the first in an array of P4 registers
  55404. ** that are used as an unpacked index key.
  55405. **
  55406. ** Reposition cursor P1 so that it points to the largest entry that
  55407. ** is less than the key value. If there are no records less than
  55408. ** the key and P2 is not zero, then jump to P2.
  55409. **
  55410. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  55411. */
  55412. /* Opcode: SeekLe P1 P2 P3 P4 *
  55413. **
  55414. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55415. ** use the value in register P3 as a key. If cursor P1 refers
  55416. ** to an SQL index, then P3 is the first in an array of P4 registers
  55417. ** that are used as an unpacked index key.
  55418. **
  55419. ** Reposition cursor P1 so that it points to the largest entry that
  55420. ** is less than or equal to the key value. If there are no records
  55421. ** less than or equal to the key and P2 is not zero, then jump to P2.
  55422. **
  55423. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  55424. */
  55425. case OP_SeekLt: /* jump, in3 */
  55426. case OP_SeekLe: /* jump, in3 */
  55427. case OP_SeekGe: /* jump, in3 */
  55428. case OP_SeekGt: { /* jump, in3 */
  55429. #if 0 /* local variables moved into u.bc */
  55430. int res;
  55431. int oc;
  55432. VdbeCursor *pC;
  55433. UnpackedRecord r;
  55434. int nField;
  55435. i64 iKey; /* The rowid we are to seek to */
  55436. #endif /* local variables moved into u.bc */
  55437. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55438. assert( pOp->p2!=0 );
  55439. u.bc.pC = p->apCsr[pOp->p1];
  55440. assert( u.bc.pC!=0 );
  55441. assert( u.bc.pC->pseudoTableReg==0 );
  55442. assert( OP_SeekLe == OP_SeekLt+1 );
  55443. assert( OP_SeekGe == OP_SeekLt+2 );
  55444. assert( OP_SeekGt == OP_SeekLt+3 );
  55445. assert( u.bc.pC->isOrdered );
  55446. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  55447. u.bc.oc = pOp->opcode;
  55448. u.bc.pC->nullRow = 0;
  55449. if( u.bc.pC->isTable ){
  55450. /* The input value in P3 might be of any type: integer, real, string,
  55451. ** blob, or NULL. But it needs to be an integer before we can do
  55452. ** the seek, so covert it. */
  55453. pIn3 = &aMem[pOp->p3];
  55454. applyNumericAffinity(pIn3);
  55455. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  55456. u.bc.pC->rowidIsValid = 0;
  55457. /* If the P3 value could not be converted into an integer without
  55458. ** loss of information, then special processing is required... */
  55459. if( (pIn3->flags & MEM_Int)==0 ){
  55460. if( (pIn3->flags & MEM_Real)==0 ){
  55461. /* If the P3 value cannot be converted into any kind of a number,
  55462. ** then the seek is not possible, so jump to P2 */
  55463. pc = pOp->p2 - 1;
  55464. break;
  55465. }
  55466. /* If we reach this point, then the P3 value must be a floating
  55467. ** point number. */
  55468. assert( (pIn3->flags & MEM_Real)!=0 );
  55469. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  55470. /* The P3 value is too large in magnitude to be expressed as an
  55471. ** integer. */
  55472. u.bc.res = 1;
  55473. if( pIn3->r<0 ){
  55474. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  55475. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  55476. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55477. }
  55478. }else{
  55479. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  55480. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  55481. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55482. }
  55483. }
  55484. if( u.bc.res ){
  55485. pc = pOp->p2 - 1;
  55486. }
  55487. break;
  55488. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  55489. /* Use the ceiling() function to convert real->int */
  55490. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  55491. }else{
  55492. /* Use the floor() function to convert real->int */
  55493. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  55494. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  55495. }
  55496. }
  55497. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  55498. if( rc!=SQLITE_OK ){
  55499. goto abort_due_to_error;
  55500. }
  55501. if( u.bc.res==0 ){
  55502. u.bc.pC->rowidIsValid = 1;
  55503. u.bc.pC->lastRowid = u.bc.iKey;
  55504. }
  55505. }else{
  55506. u.bc.nField = pOp->p4.i;
  55507. assert( pOp->p4type==P4_INT32 );
  55508. assert( u.bc.nField>0 );
  55509. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  55510. u.bc.r.nField = (u16)u.bc.nField;
  55511. /* The next line of code computes as follows, only faster:
  55512. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  55513. ** u.bc.r.flags = UNPACKED_INCRKEY;
  55514. ** }else{
  55515. ** u.bc.r.flags = 0;
  55516. ** }
  55517. */
  55518. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  55519. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  55520. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  55521. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  55522. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  55523. u.bc.r.aMem = &aMem[pOp->p3];
  55524. #ifdef SQLITE_DEBUG
  55525. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  55526. #endif
  55527. ExpandBlob(u.bc.r.aMem);
  55528. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  55529. if( rc!=SQLITE_OK ){
  55530. goto abort_due_to_error;
  55531. }
  55532. u.bc.pC->rowidIsValid = 0;
  55533. }
  55534. u.bc.pC->deferredMoveto = 0;
  55535. u.bc.pC->cacheStatus = CACHE_STALE;
  55536. #ifdef SQLITE_TEST
  55537. sqlite3_search_count++;
  55538. #endif
  55539. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  55540. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  55541. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  55542. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55543. u.bc.pC->rowidIsValid = 0;
  55544. }else{
  55545. u.bc.res = 0;
  55546. }
  55547. }else{
  55548. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  55549. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  55550. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  55551. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55552. u.bc.pC->rowidIsValid = 0;
  55553. }else{
  55554. /* u.bc.res might be negative because the table is empty. Check to
  55555. ** see if this is the case.
  55556. */
  55557. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  55558. }
  55559. }
  55560. assert( pOp->p2>0 );
  55561. if( u.bc.res ){
  55562. pc = pOp->p2 - 1;
  55563. }
  55564. }else{
  55565. /* This happens when attempting to open the sqlite3_master table
  55566. ** for read access returns SQLITE_EMPTY. In this case always
  55567. ** take the jump (since there are no records in the table).
  55568. */
  55569. pc = pOp->p2 - 1;
  55570. }
  55571. break;
  55572. }
  55573. /* Opcode: Seek P1 P2 * * *
  55574. **
  55575. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  55576. ** for P1 to move so that it points to the rowid given by P2.
  55577. **
  55578. ** This is actually a deferred seek. Nothing actually happens until
  55579. ** the cursor is used to read a record. That way, if no reads
  55580. ** occur, no unnecessary I/O happens.
  55581. */
  55582. case OP_Seek: { /* in2 */
  55583. #if 0 /* local variables moved into u.bd */
  55584. VdbeCursor *pC;
  55585. #endif /* local variables moved into u.bd */
  55586. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55587. u.bd.pC = p->apCsr[pOp->p1];
  55588. assert( u.bd.pC!=0 );
  55589. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  55590. assert( u.bd.pC->isTable );
  55591. u.bd.pC->nullRow = 0;
  55592. pIn2 = &aMem[pOp->p2];
  55593. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  55594. u.bd.pC->rowidIsValid = 0;
  55595. u.bd.pC->deferredMoveto = 1;
  55596. }
  55597. break;
  55598. }
  55599. /* Opcode: Found P1 P2 P3 P4 *
  55600. **
  55601. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  55602. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  55603. ** record.
  55604. **
  55605. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  55606. ** is a prefix of any entry in P1 then a jump is made to P2 and
  55607. ** P1 is left pointing at the matching entry.
  55608. */
  55609. /* Opcode: NotFound P1 P2 P3 P4 *
  55610. **
  55611. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  55612. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  55613. ** record.
  55614. **
  55615. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  55616. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  55617. ** does contain an entry whose prefix matches the P3/P4 record then control
  55618. ** falls through to the next instruction and P1 is left pointing at the
  55619. ** matching entry.
  55620. **
  55621. ** See also: Found, NotExists, IsUnique
  55622. */
  55623. case OP_NotFound: /* jump, in3 */
  55624. case OP_Found: { /* jump, in3 */
  55625. #if 0 /* local variables moved into u.be */
  55626. int alreadyExists;
  55627. VdbeCursor *pC;
  55628. int res;
  55629. char *pFree;
  55630. UnpackedRecord *pIdxKey;
  55631. UnpackedRecord r;
  55632. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  55633. #endif /* local variables moved into u.be */
  55634. #ifdef SQLITE_TEST
  55635. sqlite3_found_count++;
  55636. #endif
  55637. u.be.alreadyExists = 0;
  55638. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55639. assert( pOp->p4type==P4_INT32 );
  55640. u.be.pC = p->apCsr[pOp->p1];
  55641. assert( u.be.pC!=0 );
  55642. pIn3 = &aMem[pOp->p3];
  55643. if( ALWAYS(u.be.pC->pCursor!=0) ){
  55644. assert( u.be.pC->isTable==0 );
  55645. if( pOp->p4.i>0 ){
  55646. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  55647. u.be.r.nField = (u16)pOp->p4.i;
  55648. u.be.r.aMem = pIn3;
  55649. #ifdef SQLITE_DEBUG
  55650. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  55651. #endif
  55652. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  55653. u.be.pIdxKey = &u.be.r;
  55654. }else{
  55655. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  55656. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  55657. );
  55658. if( u.be.pIdxKey==0 ) goto no_mem;
  55659. assert( pIn3->flags & MEM_Blob );
  55660. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  55661. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  55662. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  55663. }
  55664. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  55665. if( pOp->p4.i==0 ){
  55666. sqlite3DbFree(db, u.be.pFree);
  55667. }
  55668. if( rc!=SQLITE_OK ){
  55669. break;
  55670. }
  55671. u.be.alreadyExists = (u.be.res==0);
  55672. u.be.pC->deferredMoveto = 0;
  55673. u.be.pC->cacheStatus = CACHE_STALE;
  55674. }
  55675. if( pOp->opcode==OP_Found ){
  55676. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  55677. }else{
  55678. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  55679. }
  55680. break;
  55681. }
  55682. /* Opcode: IsUnique P1 P2 P3 P4 *
  55683. **
  55684. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  55685. ** no data and where the key are records generated by OP_MakeRecord with
  55686. ** the list field being the integer ROWID of the entry that the index
  55687. ** entry refers to.
  55688. **
  55689. ** The P3 register contains an integer record number. Call this record
  55690. ** number R. Register P4 is the first in a set of N contiguous registers
  55691. ** that make up an unpacked index key that can be used with cursor P1.
  55692. ** The value of N can be inferred from the cursor. N includes the rowid
  55693. ** value appended to the end of the index record. This rowid value may
  55694. ** or may not be the same as R.
  55695. **
  55696. ** If any of the N registers beginning with register P4 contains a NULL
  55697. ** value, jump immediately to P2.
  55698. **
  55699. ** Otherwise, this instruction checks if cursor P1 contains an entry
  55700. ** where the first (N-1) fields match but the rowid value at the end
  55701. ** of the index entry is not R. If there is no such entry, control jumps
  55702. ** to instruction P2. Otherwise, the rowid of the conflicting index
  55703. ** entry is copied to register P3 and control falls through to the next
  55704. ** instruction.
  55705. **
  55706. ** See also: NotFound, NotExists, Found
  55707. */
  55708. case OP_IsUnique: { /* jump, in3 */
  55709. #if 0 /* local variables moved into u.bf */
  55710. u16 ii;
  55711. VdbeCursor *pCx;
  55712. BtCursor *pCrsr;
  55713. u16 nField;
  55714. Mem *aMx;
  55715. UnpackedRecord r; /* B-Tree index search key */
  55716. i64 R; /* Rowid stored in register P3 */
  55717. #endif /* local variables moved into u.bf */
  55718. pIn3 = &aMem[pOp->p3];
  55719. u.bf.aMx = &aMem[pOp->p4.i];
  55720. /* Assert that the values of parameters P1 and P4 are in range. */
  55721. assert( pOp->p4type==P4_INT32 );
  55722. assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) );
  55723. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55724. /* Find the index cursor. */
  55725. u.bf.pCx = p->apCsr[pOp->p1];
  55726. assert( u.bf.pCx->deferredMoveto==0 );
  55727. u.bf.pCx->seekResult = 0;
  55728. u.bf.pCx->cacheStatus = CACHE_STALE;
  55729. u.bf.pCrsr = u.bf.pCx->pCursor;
  55730. /* If any of the values are NULL, take the jump. */
  55731. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  55732. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  55733. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  55734. pc = pOp->p2 - 1;
  55735. u.bf.pCrsr = 0;
  55736. break;
  55737. }
  55738. }
  55739. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  55740. if( u.bf.pCrsr!=0 ){
  55741. /* Populate the index search key. */
  55742. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  55743. u.bf.r.nField = u.bf.nField + 1;
  55744. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  55745. u.bf.r.aMem = u.bf.aMx;
  55746. #ifdef SQLITE_DEBUG
  55747. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  55748. #endif
  55749. /* Extract the value of u.bf.R from register P3. */
  55750. sqlite3VdbeMemIntegerify(pIn3);
  55751. u.bf.R = pIn3->u.i;
  55752. /* Search the B-Tree index. If no conflicting record is found, jump
  55753. ** to P2. Otherwise, copy the rowid of the conflicting record to
  55754. ** register P3 and fall through to the next instruction. */
  55755. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  55756. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  55757. pc = pOp->p2 - 1;
  55758. }else{
  55759. pIn3->u.i = u.bf.r.rowid;
  55760. }
  55761. }
  55762. break;
  55763. }
  55764. /* Opcode: NotExists P1 P2 P3 * *
  55765. **
  55766. ** Use the content of register P3 as an integer key. If a record
  55767. ** with that key does not exist in table of P1, then jump to P2.
  55768. ** If the record does exist, then fall through. The cursor is left
  55769. ** pointing to the record if it exists.
  55770. **
  55771. ** The difference between this operation and NotFound is that this
  55772. ** operation assumes the key is an integer and that P1 is a table whereas
  55773. ** NotFound assumes key is a blob constructed from MakeRecord and
  55774. ** P1 is an index.
  55775. **
  55776. ** See also: Found, NotFound, IsUnique
  55777. */
  55778. case OP_NotExists: { /* jump, in3 */
  55779. #if 0 /* local variables moved into u.bg */
  55780. VdbeCursor *pC;
  55781. BtCursor *pCrsr;
  55782. int res;
  55783. u64 iKey;
  55784. #endif /* local variables moved into u.bg */
  55785. pIn3 = &aMem[pOp->p3];
  55786. assert( pIn3->flags & MEM_Int );
  55787. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55788. u.bg.pC = p->apCsr[pOp->p1];
  55789. assert( u.bg.pC!=0 );
  55790. assert( u.bg.pC->isTable );
  55791. assert( u.bg.pC->pseudoTableReg==0 );
  55792. u.bg.pCrsr = u.bg.pC->pCursor;
  55793. if( ALWAYS(u.bg.pCrsr!=0) ){
  55794. u.bg.res = 0;
  55795. u.bg.iKey = pIn3->u.i;
  55796. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  55797. u.bg.pC->lastRowid = pIn3->u.i;
  55798. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  55799. u.bg.pC->nullRow = 0;
  55800. u.bg.pC->cacheStatus = CACHE_STALE;
  55801. u.bg.pC->deferredMoveto = 0;
  55802. if( u.bg.res!=0 ){
  55803. pc = pOp->p2 - 1;
  55804. assert( u.bg.pC->rowidIsValid==0 );
  55805. }
  55806. u.bg.pC->seekResult = u.bg.res;
  55807. }else{
  55808. /* This happens when an attempt to open a read cursor on the
  55809. ** sqlite_master table returns SQLITE_EMPTY.
  55810. */
  55811. pc = pOp->p2 - 1;
  55812. assert( u.bg.pC->rowidIsValid==0 );
  55813. u.bg.pC->seekResult = 0;
  55814. }
  55815. break;
  55816. }
  55817. /* Opcode: Sequence P1 P2 * * *
  55818. **
  55819. ** Find the next available sequence number for cursor P1.
  55820. ** Write the sequence number into register P2.
  55821. ** The sequence number on the cursor is incremented after this
  55822. ** instruction.
  55823. */
  55824. case OP_Sequence: { /* out2-prerelease */
  55825. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55826. assert( p->apCsr[pOp->p1]!=0 );
  55827. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  55828. break;
  55829. }
  55830. /* Opcode: NewRowid P1 P2 P3 * *
  55831. **
  55832. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  55833. ** The record number is not previously used as a key in the database
  55834. ** table that cursor P1 points to. The new record number is written
  55835. ** written to register P2.
  55836. **
  55837. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  55838. ** the largest previously generated record number. No new record numbers are
  55839. ** allowed to be less than this value. When this value reaches its maximum,
  55840. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  55841. ** generated record number. This P3 mechanism is used to help implement the
  55842. ** AUTOINCREMENT feature.
  55843. */
  55844. case OP_NewRowid: { /* out2-prerelease */
  55845. #if 0 /* local variables moved into u.bh */
  55846. i64 v; /* The new rowid */
  55847. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  55848. int res; /* Result of an sqlite3BtreeLast() */
  55849. int cnt; /* Counter to limit the number of searches */
  55850. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  55851. VdbeFrame *pFrame; /* Root frame of VDBE */
  55852. #endif /* local variables moved into u.bh */
  55853. u.bh.v = 0;
  55854. u.bh.res = 0;
  55855. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55856. u.bh.pC = p->apCsr[pOp->p1];
  55857. assert( u.bh.pC!=0 );
  55858. if( NEVER(u.bh.pC->pCursor==0) ){
  55859. /* The zero initialization above is all that is needed */
  55860. }else{
  55861. /* The next rowid or record number (different terms for the same
  55862. ** thing) is obtained in a two-step algorithm.
  55863. **
  55864. ** First we attempt to find the largest existing rowid and add one
  55865. ** to that. But if the largest existing rowid is already the maximum
  55866. ** positive integer, we have to fall through to the second
  55867. ** probabilistic algorithm
  55868. **
  55869. ** The second algorithm is to select a rowid at random and see if
  55870. ** it already exists in the table. If it does not exist, we have
  55871. ** succeeded. If the random rowid does exist, we select a new one
  55872. ** and try again, up to 100 times.
  55873. */
  55874. assert( u.bh.pC->isTable );
  55875. #ifdef SQLITE_32BIT_ROWID
  55876. # define MAX_ROWID 0x7fffffff
  55877. #else
  55878. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  55879. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  55880. ** to provide the constant while making all compilers happy.
  55881. */
  55882. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  55883. #endif
  55884. if( !u.bh.pC->useRandomRowid ){
  55885. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  55886. if( u.bh.v==0 ){
  55887. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  55888. if( rc!=SQLITE_OK ){
  55889. goto abort_due_to_error;
  55890. }
  55891. if( u.bh.res ){
  55892. u.bh.v = 1; /* IMP: R-61914-48074 */
  55893. }else{
  55894. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  55895. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  55896. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  55897. if( u.bh.v>=MAX_ROWID ){
  55898. u.bh.pC->useRandomRowid = 1;
  55899. }else{
  55900. u.bh.v++; /* IMP: R-29538-34987 */
  55901. }
  55902. }
  55903. }
  55904. #ifndef SQLITE_OMIT_AUTOINCREMENT
  55905. if( pOp->p3 ){
  55906. /* Assert that P3 is a valid memory cell. */
  55907. assert( pOp->p3>0 );
  55908. if( p->pFrame ){
  55909. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  55910. /* Assert that P3 is a valid memory cell. */
  55911. assert( pOp->p3<=u.bh.pFrame->nMem );
  55912. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  55913. }else{
  55914. /* Assert that P3 is a valid memory cell. */
  55915. assert( pOp->p3<=(p->nMem-p->nCursor) );
  55916. u.bh.pMem = &aMem[pOp->p3];
  55917. memAboutToChange(p, u.bh.pMem);
  55918. }
  55919. assert( memIsValid(u.bh.pMem) );
  55920. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  55921. sqlite3VdbeMemIntegerify(u.bh.pMem);
  55922. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  55923. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  55924. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  55925. goto abort_due_to_error;
  55926. }
  55927. if( u.bh.v<u.bh.pMem->u.i+1 ){
  55928. u.bh.v = u.bh.pMem->u.i + 1;
  55929. }
  55930. u.bh.pMem->u.i = u.bh.v;
  55931. }
  55932. #endif
  55933. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  55934. }
  55935. if( u.bh.pC->useRandomRowid ){
  55936. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  55937. ** largest possible integer (9223372036854775807) then the database
  55938. ** engine starts picking positive candidate ROWIDs at random until
  55939. ** it finds one that is not previously used. */
  55940. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  55941. ** an AUTOINCREMENT table. */
  55942. /* on the first attempt, simply do one more than previous */
  55943. u.bh.v = lastRowid;
  55944. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  55945. u.bh.v++; /* ensure non-zero */
  55946. u.bh.cnt = 0;
  55947. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  55948. 0, &u.bh.res))==SQLITE_OK)
  55949. && (u.bh.res==0)
  55950. && (++u.bh.cnt<100)){
  55951. /* collision - try another random rowid */
  55952. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  55953. if( u.bh.cnt<5 ){
  55954. /* try "small" random rowids for the initial attempts */
  55955. u.bh.v &= 0xffffff;
  55956. }else{
  55957. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  55958. }
  55959. u.bh.v++; /* ensure non-zero */
  55960. }
  55961. if( rc==SQLITE_OK && u.bh.res==0 ){
  55962. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  55963. goto abort_due_to_error;
  55964. }
  55965. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  55966. }
  55967. u.bh.pC->rowidIsValid = 0;
  55968. u.bh.pC->deferredMoveto = 0;
  55969. u.bh.pC->cacheStatus = CACHE_STALE;
  55970. }
  55971. pOut->u.i = u.bh.v;
  55972. break;
  55973. }
  55974. /* Opcode: Insert P1 P2 P3 P4 P5
  55975. **
  55976. ** Write an entry into the table of cursor P1. A new entry is
  55977. ** created if it doesn't already exist or the data for an existing
  55978. ** entry is overwritten. The data is the value MEM_Blob stored in register
  55979. ** number P2. The key is stored in register P3. The key must
  55980. ** be a MEM_Int.
  55981. **
  55982. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  55983. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  55984. ** then rowid is stored for subsequent return by the
  55985. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  55986. **
  55987. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  55988. ** the last seek operation (OP_NotExists) was a success, then this
  55989. ** operation will not attempt to find the appropriate row before doing
  55990. ** the insert but will instead overwrite the row that the cursor is
  55991. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  55992. ** has already positioned the cursor correctly. This is an optimization
  55993. ** that boosts performance by avoiding redundant seeks.
  55994. **
  55995. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  55996. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  55997. ** is part of an INSERT operation. The difference is only important to
  55998. ** the update hook.
  55999. **
  56000. ** Parameter P4 may point to a string containing the table-name, or
  56001. ** may be NULL. If it is not NULL, then the update-hook
  56002. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  56003. **
  56004. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  56005. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  56006. ** and register P2 becomes ephemeral. If the cursor is changed, the
  56007. ** value of register P2 will then change. Make sure this does not
  56008. ** cause any problems.)
  56009. **
  56010. ** This instruction only works on tables. The equivalent instruction
  56011. ** for indices is OP_IdxInsert.
  56012. */
  56013. /* Opcode: InsertInt P1 P2 P3 P4 P5
  56014. **
  56015. ** This works exactly like OP_Insert except that the key is the
  56016. ** integer value P3, not the value of the integer stored in register P3.
  56017. */
  56018. case OP_Insert:
  56019. case OP_InsertInt: {
  56020. #if 0 /* local variables moved into u.bi */
  56021. Mem *pData; /* MEM cell holding data for the record to be inserted */
  56022. Mem *pKey; /* MEM cell holding key for the record */
  56023. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  56024. VdbeCursor *pC; /* Cursor to table into which insert is written */
  56025. int nZero; /* Number of zero-bytes to append */
  56026. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  56027. const char *zDb; /* database name - used by the update hook */
  56028. const char *zTbl; /* Table name - used by the opdate hook */
  56029. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  56030. #endif /* local variables moved into u.bi */
  56031. u.bi.pData = &aMem[pOp->p2];
  56032. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56033. assert( memIsValid(u.bi.pData) );
  56034. u.bi.pC = p->apCsr[pOp->p1];
  56035. assert( u.bi.pC!=0 );
  56036. assert( u.bi.pC->pCursor!=0 );
  56037. assert( u.bi.pC->pseudoTableReg==0 );
  56038. assert( u.bi.pC->isTable );
  56039. REGISTER_TRACE(pOp->p2, u.bi.pData);
  56040. if( pOp->opcode==OP_Insert ){
  56041. u.bi.pKey = &aMem[pOp->p3];
  56042. assert( u.bi.pKey->flags & MEM_Int );
  56043. assert( memIsValid(u.bi.pKey) );
  56044. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  56045. u.bi.iKey = u.bi.pKey->u.i;
  56046. }else{
  56047. assert( pOp->opcode==OP_InsertInt );
  56048. u.bi.iKey = pOp->p3;
  56049. }
  56050. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  56051. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  56052. if( u.bi.pData->flags & MEM_Null ){
  56053. u.bi.pData->z = 0;
  56054. u.bi.pData->n = 0;
  56055. }else{
  56056. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  56057. }
  56058. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  56059. if( u.bi.pData->flags & MEM_Zero ){
  56060. u.bi.nZero = u.bi.pData->u.nZero;
  56061. }else{
  56062. u.bi.nZero = 0;
  56063. }
  56064. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  56065. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  56066. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  56067. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  56068. );
  56069. u.bi.pC->rowidIsValid = 0;
  56070. u.bi.pC->deferredMoveto = 0;
  56071. u.bi.pC->cacheStatus = CACHE_STALE;
  56072. /* Invoke the update-hook if required. */
  56073. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  56074. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  56075. u.bi.zTbl = pOp->p4.z;
  56076. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  56077. assert( u.bi.pC->isTable );
  56078. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  56079. assert( u.bi.pC->iDb>=0 );
  56080. }
  56081. break;
  56082. }
  56083. /* Opcode: Delete P1 P2 * P4 *
  56084. **
  56085. ** Delete the record at which the P1 cursor is currently pointing.
  56086. **
  56087. ** The cursor will be left pointing at either the next or the previous
  56088. ** record in the table. If it is left pointing at the next record, then
  56089. ** the next Next instruction will be a no-op. Hence it is OK to delete
  56090. ** a record from within an Next loop.
  56091. **
  56092. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  56093. ** incremented (otherwise not).
  56094. **
  56095. ** P1 must not be pseudo-table. It has to be a real table with
  56096. ** multiple rows.
  56097. **
  56098. ** If P4 is not NULL, then it is the name of the table that P1 is
  56099. ** pointing to. The update hook will be invoked, if it exists.
  56100. ** If P4 is not NULL then the P1 cursor must have been positioned
  56101. ** using OP_NotFound prior to invoking this opcode.
  56102. */
  56103. case OP_Delete: {
  56104. #if 0 /* local variables moved into u.bj */
  56105. i64 iKey;
  56106. VdbeCursor *pC;
  56107. #endif /* local variables moved into u.bj */
  56108. u.bj.iKey = 0;
  56109. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56110. u.bj.pC = p->apCsr[pOp->p1];
  56111. assert( u.bj.pC!=0 );
  56112. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  56113. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  56114. ** row being deleted.
  56115. */
  56116. if( db->xUpdateCallback && pOp->p4.z ){
  56117. assert( u.bj.pC->isTable );
  56118. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  56119. u.bj.iKey = u.bj.pC->lastRowid;
  56120. }
  56121. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  56122. ** OP_Column on the same table without any intervening operations that
  56123. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  56124. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  56125. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  56126. ** to guard against future changes to the code generator.
  56127. **/
  56128. assert( u.bj.pC->deferredMoveto==0 );
  56129. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  56130. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  56131. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  56132. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  56133. u.bj.pC->cacheStatus = CACHE_STALE;
  56134. /* Invoke the update-hook if required. */
  56135. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  56136. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  56137. const char *zTbl = pOp->p4.z;
  56138. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  56139. assert( u.bj.pC->iDb>=0 );
  56140. }
  56141. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  56142. break;
  56143. }
  56144. /* Opcode: ResetCount * * * * *
  56145. **
  56146. ** The value of the change counter is copied to the database handle
  56147. ** change counter (returned by subsequent calls to sqlite3_changes()).
  56148. ** Then the VMs internal change counter resets to 0.
  56149. ** This is used by trigger programs.
  56150. */
  56151. case OP_ResetCount: {
  56152. sqlite3VdbeSetChanges(db, p->nChange);
  56153. p->nChange = 0;
  56154. break;
  56155. }
  56156. /* Opcode: SorterCompare P1 P2 P3
  56157. **
  56158. ** P1 is a sorter cursor. This instruction compares the record blob in
  56159. ** register P3 with the entry that the sorter cursor currently points to.
  56160. ** If, excluding the rowid fields at the end, the two records are a match,
  56161. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  56162. */
  56163. case OP_SorterCompare: {
  56164. #if 0 /* local variables moved into u.bk */
  56165. VdbeCursor *pC;
  56166. int res;
  56167. #endif /* local variables moved into u.bk */
  56168. u.bk.pC = p->apCsr[pOp->p1];
  56169. assert( isSorter(u.bk.pC) );
  56170. pIn3 = &aMem[pOp->p3];
  56171. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  56172. if( u.bk.res ){
  56173. pc = pOp->p2-1;
  56174. }
  56175. break;
  56176. };
  56177. /* Opcode: SorterData P1 P2 * * *
  56178. **
  56179. ** Write into register P2 the current sorter data for sorter cursor P1.
  56180. */
  56181. case OP_SorterData: {
  56182. #if 0 /* local variables moved into u.bl */
  56183. VdbeCursor *pC;
  56184. #endif /* local variables moved into u.bl */
  56185. pOut = &aMem[pOp->p2];
  56186. u.bl.pC = p->apCsr[pOp->p1];
  56187. assert( u.bl.pC->isSorter );
  56188. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  56189. break;
  56190. }
  56191. /* Opcode: RowData P1 P2 * * *
  56192. **
  56193. ** Write into register P2 the complete row data for cursor P1.
  56194. ** There is no interpretation of the data.
  56195. ** It is just copied onto the P2 register exactly as
  56196. ** it is found in the database file.
  56197. **
  56198. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  56199. ** of a real table, not a pseudo-table.
  56200. */
  56201. /* Opcode: RowKey P1 P2 * * *
  56202. **
  56203. ** Write into register P2 the complete row key for cursor P1.
  56204. ** There is no interpretation of the data.
  56205. ** The key is copied onto the P3 register exactly as
  56206. ** it is found in the database file.
  56207. **
  56208. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  56209. ** of a real table, not a pseudo-table.
  56210. */
  56211. case OP_RowKey:
  56212. case OP_RowData: {
  56213. #if 0 /* local variables moved into u.bm */
  56214. VdbeCursor *pC;
  56215. BtCursor *pCrsr;
  56216. u32 n;
  56217. i64 n64;
  56218. #endif /* local variables moved into u.bm */
  56219. pOut = &aMem[pOp->p2];
  56220. memAboutToChange(p, pOut);
  56221. /* Note that RowKey and RowData are really exactly the same instruction */
  56222. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56223. u.bm.pC = p->apCsr[pOp->p1];
  56224. assert( u.bm.pC->isSorter==0 );
  56225. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  56226. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  56227. assert( u.bm.pC!=0 );
  56228. assert( u.bm.pC->nullRow==0 );
  56229. assert( u.bm.pC->pseudoTableReg==0 );
  56230. assert( u.bm.pC->pCursor!=0 );
  56231. u.bm.pCrsr = u.bm.pC->pCursor;
  56232. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  56233. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  56234. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  56235. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  56236. ** a no-op and can never fail. But we leave it in place as a safety.
  56237. */
  56238. assert( u.bm.pC->deferredMoveto==0 );
  56239. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  56240. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  56241. if( u.bm.pC->isIndex ){
  56242. assert( !u.bm.pC->isTable );
  56243. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  56244. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  56245. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  56246. goto too_big;
  56247. }
  56248. u.bm.n = (u32)u.bm.n64;
  56249. }else{
  56250. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  56251. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  56252. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  56253. goto too_big;
  56254. }
  56255. }
  56256. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  56257. goto no_mem;
  56258. }
  56259. pOut->n = u.bm.n;
  56260. MemSetTypeFlag(pOut, MEM_Blob);
  56261. if( u.bm.pC->isIndex ){
  56262. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  56263. }else{
  56264. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  56265. }
  56266. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  56267. UPDATE_MAX_BLOBSIZE(pOut);
  56268. break;
  56269. }
  56270. /* Opcode: Rowid P1 P2 * * *
  56271. **
  56272. ** Store in register P2 an integer which is the key of the table entry that
  56273. ** P1 is currently point to.
  56274. **
  56275. ** P1 can be either an ordinary table or a virtual table. There used to
  56276. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  56277. ** one opcode now works for both table types.
  56278. */
  56279. case OP_Rowid: { /* out2-prerelease */
  56280. #if 0 /* local variables moved into u.bn */
  56281. VdbeCursor *pC;
  56282. i64 v;
  56283. sqlite3_vtab *pVtab;
  56284. const sqlite3_module *pModule;
  56285. #endif /* local variables moved into u.bn */
  56286. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56287. u.bn.pC = p->apCsr[pOp->p1];
  56288. assert( u.bn.pC!=0 );
  56289. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  56290. if( u.bn.pC->nullRow ){
  56291. pOut->flags = MEM_Null;
  56292. break;
  56293. }else if( u.bn.pC->deferredMoveto ){
  56294. u.bn.v = u.bn.pC->movetoTarget;
  56295. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56296. }else if( u.bn.pC->pVtabCursor ){
  56297. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  56298. u.bn.pModule = u.bn.pVtab->pModule;
  56299. assert( u.bn.pModule->xRowid );
  56300. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  56301. sqlite3VtabImportErrmsg(p, u.bn.pVtab);
  56302. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  56303. }else{
  56304. assert( u.bn.pC->pCursor!=0 );
  56305. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  56306. if( rc ) goto abort_due_to_error;
  56307. if( u.bn.pC->rowidIsValid ){
  56308. u.bn.v = u.bn.pC->lastRowid;
  56309. }else{
  56310. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  56311. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  56312. }
  56313. }
  56314. pOut->u.i = u.bn.v;
  56315. break;
  56316. }
  56317. /* Opcode: NullRow P1 * * * *
  56318. **
  56319. ** Move the cursor P1 to a null row. Any OP_Column operations
  56320. ** that occur while the cursor is on the null row will always
  56321. ** write a NULL.
  56322. */
  56323. case OP_NullRow: {
  56324. #if 0 /* local variables moved into u.bo */
  56325. VdbeCursor *pC;
  56326. #endif /* local variables moved into u.bo */
  56327. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56328. u.bo.pC = p->apCsr[pOp->p1];
  56329. assert( u.bo.pC!=0 );
  56330. u.bo.pC->nullRow = 1;
  56331. u.bo.pC->rowidIsValid = 0;
  56332. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  56333. if( u.bo.pC->pCursor ){
  56334. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  56335. }
  56336. break;
  56337. }
  56338. /* Opcode: Last P1 P2 * * *
  56339. **
  56340. ** The next use of the Rowid or Column or Next instruction for P1
  56341. ** will refer to the last entry in the database table or index.
  56342. ** If the table or index is empty and P2>0, then jump immediately to P2.
  56343. ** If P2 is 0 or if the table or index is not empty, fall through
  56344. ** to the following instruction.
  56345. */
  56346. case OP_Last: { /* jump */
  56347. #if 0 /* local variables moved into u.bp */
  56348. VdbeCursor *pC;
  56349. BtCursor *pCrsr;
  56350. int res;
  56351. #endif /* local variables moved into u.bp */
  56352. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56353. u.bp.pC = p->apCsr[pOp->p1];
  56354. assert( u.bp.pC!=0 );
  56355. u.bp.pCrsr = u.bp.pC->pCursor;
  56356. u.bp.res = 0;
  56357. if( ALWAYS(u.bp.pCrsr!=0) ){
  56358. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  56359. }
  56360. u.bp.pC->nullRow = (u8)u.bp.res;
  56361. u.bp.pC->deferredMoveto = 0;
  56362. u.bp.pC->rowidIsValid = 0;
  56363. u.bp.pC->cacheStatus = CACHE_STALE;
  56364. if( pOp->p2>0 && u.bp.res ){
  56365. pc = pOp->p2 - 1;
  56366. }
  56367. break;
  56368. }
  56369. /* Opcode: Sort P1 P2 * * *
  56370. **
  56371. ** This opcode does exactly the same thing as OP_Rewind except that
  56372. ** it increments an undocumented global variable used for testing.
  56373. **
  56374. ** Sorting is accomplished by writing records into a sorting index,
  56375. ** then rewinding that index and playing it back from beginning to
  56376. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  56377. ** rewinding so that the global variable will be incremented and
  56378. ** regression tests can determine whether or not the optimizer is
  56379. ** correctly optimizing out sorts.
  56380. */
  56381. case OP_SorterSort: /* jump */
  56382. case OP_Sort: { /* jump */
  56383. #ifdef SQLITE_TEST
  56384. sqlite3_sort_count++;
  56385. sqlite3_search_count--;
  56386. #endif
  56387. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  56388. /* Fall through into OP_Rewind */
  56389. }
  56390. /* Opcode: Rewind P1 P2 * * *
  56391. **
  56392. ** The next use of the Rowid or Column or Next instruction for P1
  56393. ** will refer to the first entry in the database table or index.
  56394. ** If the table or index is empty and P2>0, then jump immediately to P2.
  56395. ** If P2 is 0 or if the table or index is not empty, fall through
  56396. ** to the following instruction.
  56397. */
  56398. case OP_Rewind: { /* jump */
  56399. #if 0 /* local variables moved into u.bq */
  56400. VdbeCursor *pC;
  56401. BtCursor *pCrsr;
  56402. int res;
  56403. #endif /* local variables moved into u.bq */
  56404. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56405. u.bq.pC = p->apCsr[pOp->p1];
  56406. assert( u.bq.pC!=0 );
  56407. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  56408. u.bq.res = 1;
  56409. if( isSorter(u.bq.pC) ){
  56410. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  56411. }else{
  56412. u.bq.pCrsr = u.bq.pC->pCursor;
  56413. assert( u.bq.pCrsr );
  56414. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  56415. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  56416. u.bq.pC->deferredMoveto = 0;
  56417. u.bq.pC->cacheStatus = CACHE_STALE;
  56418. u.bq.pC->rowidIsValid = 0;
  56419. }
  56420. u.bq.pC->nullRow = (u8)u.bq.res;
  56421. assert( pOp->p2>0 && pOp->p2<p->nOp );
  56422. if( u.bq.res ){
  56423. pc = pOp->p2 - 1;
  56424. }
  56425. break;
  56426. }
  56427. /* Opcode: Next P1 P2 * P4 P5
  56428. **
  56429. ** Advance cursor P1 so that it points to the next key/data pair in its
  56430. ** table or index. If there are no more key/value pairs then fall through
  56431. ** to the following instruction. But if the cursor advance was successful,
  56432. ** jump immediately to P2.
  56433. **
  56434. ** The P1 cursor must be for a real table, not a pseudo-table.
  56435. **
  56436. ** P4 is always of type P4_ADVANCE. The function pointer points to
  56437. ** sqlite3BtreeNext().
  56438. **
  56439. ** If P5 is positive and the jump is taken, then event counter
  56440. ** number P5-1 in the prepared statement is incremented.
  56441. **
  56442. ** See also: Prev
  56443. */
  56444. /* Opcode: Prev P1 P2 * * P5
  56445. **
  56446. ** Back up cursor P1 so that it points to the previous key/data pair in its
  56447. ** table or index. If there is no previous key/value pairs then fall through
  56448. ** to the following instruction. But if the cursor backup was successful,
  56449. ** jump immediately to P2.
  56450. **
  56451. ** The P1 cursor must be for a real table, not a pseudo-table.
  56452. **
  56453. ** P4 is always of type P4_ADVANCE. The function pointer points to
  56454. ** sqlite3BtreePrevious().
  56455. **
  56456. ** If P5 is positive and the jump is taken, then event counter
  56457. ** number P5-1 in the prepared statement is incremented.
  56458. */
  56459. case OP_SorterNext: /* jump */
  56460. case OP_Prev: /* jump */
  56461. case OP_Next: { /* jump */
  56462. #if 0 /* local variables moved into u.br */
  56463. VdbeCursor *pC;
  56464. int res;
  56465. #endif /* local variables moved into u.br */
  56466. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56467. assert( pOp->p5<ArraySize(p->aCounter) );
  56468. u.br.pC = p->apCsr[pOp->p1];
  56469. if( u.br.pC==0 ){
  56470. break; /* See ticket #2273 */
  56471. }
  56472. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  56473. if( isSorter(u.br.pC) ){
  56474. assert( pOp->opcode==OP_SorterNext );
  56475. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  56476. }else{
  56477. /* u.br.res = 1; // Always initialized by the xAdvance() call */
  56478. assert( u.br.pC->deferredMoveto==0 );
  56479. assert( u.br.pC->pCursor );
  56480. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  56481. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  56482. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  56483. }
  56484. u.br.pC->nullRow = (u8)u.br.res;
  56485. u.br.pC->cacheStatus = CACHE_STALE;
  56486. if( u.br.res==0 ){
  56487. pc = pOp->p2 - 1;
  56488. p->aCounter[pOp->p5]++;
  56489. #ifdef SQLITE_TEST
  56490. sqlite3_search_count++;
  56491. #endif
  56492. }
  56493. u.br.pC->rowidIsValid = 0;
  56494. goto check_for_interrupt;
  56495. }
  56496. /* Opcode: IdxInsert P1 P2 P3 * P5
  56497. **
  56498. ** Register P2 holds an SQL index key made using the
  56499. ** MakeRecord instructions. This opcode writes that key
  56500. ** into the index P1. Data for the entry is nil.
  56501. **
  56502. ** P3 is a flag that provides a hint to the b-tree layer that this
  56503. ** insert is likely to be an append.
  56504. **
  56505. ** This instruction only works for indices. The equivalent instruction
  56506. ** for tables is OP_Insert.
  56507. */
  56508. case OP_SorterInsert: /* in2 */
  56509. case OP_IdxInsert: { /* in2 */
  56510. #if 0 /* local variables moved into u.bs */
  56511. VdbeCursor *pC;
  56512. BtCursor *pCrsr;
  56513. int nKey;
  56514. const char *zKey;
  56515. #endif /* local variables moved into u.bs */
  56516. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56517. u.bs.pC = p->apCsr[pOp->p1];
  56518. assert( u.bs.pC!=0 );
  56519. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  56520. pIn2 = &aMem[pOp->p2];
  56521. assert( pIn2->flags & MEM_Blob );
  56522. u.bs.pCrsr = u.bs.pC->pCursor;
  56523. if( ALWAYS(u.bs.pCrsr!=0) ){
  56524. assert( u.bs.pC->isTable==0 );
  56525. rc = ExpandBlob(pIn2);
  56526. if( rc==SQLITE_OK ){
  56527. if( isSorter(u.bs.pC) ){
  56528. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  56529. }else{
  56530. u.bs.nKey = pIn2->n;
  56531. u.bs.zKey = pIn2->z;
  56532. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  56533. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  56534. );
  56535. assert( u.bs.pC->deferredMoveto==0 );
  56536. u.bs.pC->cacheStatus = CACHE_STALE;
  56537. }
  56538. }
  56539. }
  56540. break;
  56541. }
  56542. /* Opcode: IdxDelete P1 P2 P3 * *
  56543. **
  56544. ** The content of P3 registers starting at register P2 form
  56545. ** an unpacked index key. This opcode removes that entry from the
  56546. ** index opened by cursor P1.
  56547. */
  56548. case OP_IdxDelete: {
  56549. #if 0 /* local variables moved into u.bt */
  56550. VdbeCursor *pC;
  56551. BtCursor *pCrsr;
  56552. int res;
  56553. UnpackedRecord r;
  56554. #endif /* local variables moved into u.bt */
  56555. assert( pOp->p3>0 );
  56556. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  56557. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56558. u.bt.pC = p->apCsr[pOp->p1];
  56559. assert( u.bt.pC!=0 );
  56560. u.bt.pCrsr = u.bt.pC->pCursor;
  56561. if( ALWAYS(u.bt.pCrsr!=0) ){
  56562. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  56563. u.bt.r.nField = (u16)pOp->p3;
  56564. u.bt.r.flags = 0;
  56565. u.bt.r.aMem = &aMem[pOp->p2];
  56566. #ifdef SQLITE_DEBUG
  56567. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  56568. #endif
  56569. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  56570. if( rc==SQLITE_OK && u.bt.res==0 ){
  56571. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  56572. }
  56573. assert( u.bt.pC->deferredMoveto==0 );
  56574. u.bt.pC->cacheStatus = CACHE_STALE;
  56575. }
  56576. break;
  56577. }
  56578. /* Opcode: IdxRowid P1 P2 * * *
  56579. **
  56580. ** Write into register P2 an integer which is the last entry in the record at
  56581. ** the end of the index key pointed to by cursor P1. This integer should be
  56582. ** the rowid of the table entry to which this index entry points.
  56583. **
  56584. ** See also: Rowid, MakeRecord.
  56585. */
  56586. case OP_IdxRowid: { /* out2-prerelease */
  56587. #if 0 /* local variables moved into u.bu */
  56588. BtCursor *pCrsr;
  56589. VdbeCursor *pC;
  56590. i64 rowid;
  56591. #endif /* local variables moved into u.bu */
  56592. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56593. u.bu.pC = p->apCsr[pOp->p1];
  56594. assert( u.bu.pC!=0 );
  56595. u.bu.pCrsr = u.bu.pC->pCursor;
  56596. pOut->flags = MEM_Null;
  56597. if( ALWAYS(u.bu.pCrsr!=0) ){
  56598. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  56599. if( NEVER(rc) ) goto abort_due_to_error;
  56600. assert( u.bu.pC->deferredMoveto==0 );
  56601. assert( u.bu.pC->isTable==0 );
  56602. if( !u.bu.pC->nullRow ){
  56603. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  56604. if( rc!=SQLITE_OK ){
  56605. goto abort_due_to_error;
  56606. }
  56607. pOut->u.i = u.bu.rowid;
  56608. pOut->flags = MEM_Int;
  56609. }
  56610. }
  56611. break;
  56612. }
  56613. /* Opcode: IdxGE P1 P2 P3 P4 P5
  56614. **
  56615. ** The P4 register values beginning with P3 form an unpacked index
  56616. ** key that omits the ROWID. Compare this key value against the index
  56617. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  56618. **
  56619. ** If the P1 index entry is greater than or equal to the key value
  56620. ** then jump to P2. Otherwise fall through to the next instruction.
  56621. **
  56622. ** If P5 is non-zero then the key value is increased by an epsilon
  56623. ** prior to the comparison. This make the opcode work like IdxGT except
  56624. ** that if the key from register P3 is a prefix of the key in the cursor,
  56625. ** the result is false whereas it would be true with IdxGT.
  56626. */
  56627. /* Opcode: IdxLT P1 P2 P3 P4 P5
  56628. **
  56629. ** The P4 register values beginning with P3 form an unpacked index
  56630. ** key that omits the ROWID. Compare this key value against the index
  56631. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  56632. **
  56633. ** If the P1 index entry is less than the key value then jump to P2.
  56634. ** Otherwise fall through to the next instruction.
  56635. **
  56636. ** If P5 is non-zero then the key value is increased by an epsilon prior
  56637. ** to the comparison. This makes the opcode work like IdxLE.
  56638. */
  56639. case OP_IdxLT: /* jump */
  56640. case OP_IdxGE: { /* jump */
  56641. #if 0 /* local variables moved into u.bv */
  56642. VdbeCursor *pC;
  56643. int res;
  56644. UnpackedRecord r;
  56645. #endif /* local variables moved into u.bv */
  56646. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56647. u.bv.pC = p->apCsr[pOp->p1];
  56648. assert( u.bv.pC!=0 );
  56649. assert( u.bv.pC->isOrdered );
  56650. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  56651. assert( u.bv.pC->deferredMoveto==0 );
  56652. assert( pOp->p5==0 || pOp->p5==1 );
  56653. assert( pOp->p4type==P4_INT32 );
  56654. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  56655. u.bv.r.nField = (u16)pOp->p4.i;
  56656. if( pOp->p5 ){
  56657. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  56658. }else{
  56659. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  56660. }
  56661. u.bv.r.aMem = &aMem[pOp->p3];
  56662. #ifdef SQLITE_DEBUG
  56663. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  56664. #endif
  56665. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  56666. if( pOp->opcode==OP_IdxLT ){
  56667. u.bv.res = -u.bv.res;
  56668. }else{
  56669. assert( pOp->opcode==OP_IdxGE );
  56670. u.bv.res++;
  56671. }
  56672. if( u.bv.res>0 ){
  56673. pc = pOp->p2 - 1 ;
  56674. }
  56675. }
  56676. break;
  56677. }
  56678. /* Opcode: Destroy P1 P2 P3 * *
  56679. **
  56680. ** Delete an entire database table or index whose root page in the database
  56681. ** file is given by P1.
  56682. **
  56683. ** The table being destroyed is in the main database file if P3==0. If
  56684. ** P3==1 then the table to be clear is in the auxiliary database file
  56685. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  56686. **
  56687. ** If AUTOVACUUM is enabled then it is possible that another root page
  56688. ** might be moved into the newly deleted root page in order to keep all
  56689. ** root pages contiguous at the beginning of the database. The former
  56690. ** value of the root page that moved - its value before the move occurred -
  56691. ** is stored in register P2. If no page
  56692. ** movement was required (because the table being dropped was already
  56693. ** the last one in the database) then a zero is stored in register P2.
  56694. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  56695. **
  56696. ** See also: Clear
  56697. */
  56698. case OP_Destroy: { /* out2-prerelease */
  56699. #if 0 /* local variables moved into u.bw */
  56700. int iMoved;
  56701. int iCnt;
  56702. Vdbe *pVdbe;
  56703. int iDb;
  56704. #endif /* local variables moved into u.bw */
  56705. assert( p->readOnly==0 );
  56706. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56707. u.bw.iCnt = 0;
  56708. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  56709. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
  56710. && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
  56711. ){
  56712. u.bw.iCnt++;
  56713. }
  56714. }
  56715. #else
  56716. u.bw.iCnt = db->nVdbeRead;
  56717. #endif
  56718. pOut->flags = MEM_Null;
  56719. if( u.bw.iCnt>1 ){
  56720. rc = SQLITE_LOCKED;
  56721. p->errorAction = OE_Abort;
  56722. }else{
  56723. u.bw.iDb = pOp->p3;
  56724. assert( u.bw.iCnt==1 );
  56725. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  56726. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  56727. pOut->flags = MEM_Int;
  56728. pOut->u.i = u.bw.iMoved;
  56729. #ifndef SQLITE_OMIT_AUTOVACUUM
  56730. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  56731. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  56732. /* All OP_Destroy operations occur on the same btree */
  56733. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  56734. resetSchemaOnFault = u.bw.iDb+1;
  56735. }
  56736. #endif
  56737. }
  56738. break;
  56739. }
  56740. /* Opcode: Clear P1 P2 P3
  56741. **
  56742. ** Delete all contents of the database table or index whose root page
  56743. ** in the database file is given by P1. But, unlike Destroy, do not
  56744. ** remove the table or index from the database file.
  56745. **
  56746. ** The table being clear is in the main database file if P2==0. If
  56747. ** P2==1 then the table to be clear is in the auxiliary database file
  56748. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  56749. **
  56750. ** If the P3 value is non-zero, then the table referred to must be an
  56751. ** intkey table (an SQL table, not an index). In this case the row change
  56752. ** count is incremented by the number of rows in the table being cleared.
  56753. ** If P3 is greater than zero, then the value stored in register P3 is
  56754. ** also incremented by the number of rows in the table being cleared.
  56755. **
  56756. ** See also: Destroy
  56757. */
  56758. case OP_Clear: {
  56759. #if 0 /* local variables moved into u.bx */
  56760. int nChange;
  56761. #endif /* local variables moved into u.bx */
  56762. u.bx.nChange = 0;
  56763. assert( p->readOnly==0 );
  56764. assert( pOp->p1!=1 );
  56765. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  56766. rc = sqlite3BtreeClearTable(
  56767. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  56768. );
  56769. if( pOp->p3 ){
  56770. p->nChange += u.bx.nChange;
  56771. if( pOp->p3>0 ){
  56772. assert( memIsValid(&aMem[pOp->p3]) );
  56773. memAboutToChange(p, &aMem[pOp->p3]);
  56774. aMem[pOp->p3].u.i += u.bx.nChange;
  56775. }
  56776. }
  56777. break;
  56778. }
  56779. /* Opcode: CreateTable P1 P2 * * *
  56780. **
  56781. ** Allocate a new table in the main database file if P1==0 or in the
  56782. ** auxiliary database file if P1==1 or in an attached database if
  56783. ** P1>1. Write the root page number of the new table into
  56784. ** register P2
  56785. **
  56786. ** The difference between a table and an index is this: A table must
  56787. ** have a 4-byte integer key and can have arbitrary data. An index
  56788. ** has an arbitrary key but no data.
  56789. **
  56790. ** See also: CreateIndex
  56791. */
  56792. /* Opcode: CreateIndex P1 P2 * * *
  56793. **
  56794. ** Allocate a new index in the main database file if P1==0 or in the
  56795. ** auxiliary database file if P1==1 or in an attached database if
  56796. ** P1>1. Write the root page number of the new table into
  56797. ** register P2.
  56798. **
  56799. ** See documentation on OP_CreateTable for additional information.
  56800. */
  56801. case OP_CreateIndex: /* out2-prerelease */
  56802. case OP_CreateTable: { /* out2-prerelease */
  56803. #if 0 /* local variables moved into u.by */
  56804. int pgno;
  56805. int flags;
  56806. Db *pDb;
  56807. #endif /* local variables moved into u.by */
  56808. u.by.pgno = 0;
  56809. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  56810. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  56811. assert( p->readOnly==0 );
  56812. u.by.pDb = &db->aDb[pOp->p1];
  56813. assert( u.by.pDb->pBt!=0 );
  56814. if( pOp->opcode==OP_CreateTable ){
  56815. /* u.by.flags = BTREE_INTKEY; */
  56816. u.by.flags = BTREE_INTKEY;
  56817. }else{
  56818. u.by.flags = BTREE_BLOBKEY;
  56819. }
  56820. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  56821. pOut->u.i = u.by.pgno;
  56822. break;
  56823. }
  56824. /* Opcode: ParseSchema P1 * * P4 *
  56825. **
  56826. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  56827. ** that match the WHERE clause P4.
  56828. **
  56829. ** This opcode invokes the parser to create a new virtual machine,
  56830. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  56831. */
  56832. case OP_ParseSchema: {
  56833. #if 0 /* local variables moved into u.bz */
  56834. int iDb;
  56835. const char *zMaster;
  56836. char *zSql;
  56837. InitData initData;
  56838. #endif /* local variables moved into u.bz */
  56839. /* Any prepared statement that invokes this opcode will hold mutexes
  56840. ** on every btree. This is a prerequisite for invoking
  56841. ** sqlite3InitCallback().
  56842. */
  56843. #ifdef SQLITE_DEBUG
  56844. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  56845. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  56846. }
  56847. #endif
  56848. u.bz.iDb = pOp->p1;
  56849. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  56850. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  56851. /* Used to be a conditional */ {
  56852. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  56853. u.bz.initData.db = db;
  56854. u.bz.initData.iDb = pOp->p1;
  56855. u.bz.initData.pzErrMsg = &p->zErrMsg;
  56856. u.bz.zSql = sqlite3MPrintf(db,
  56857. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  56858. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  56859. if( u.bz.zSql==0 ){
  56860. rc = SQLITE_NOMEM;
  56861. }else{
  56862. assert( db->init.busy==0 );
  56863. db->init.busy = 1;
  56864. u.bz.initData.rc = SQLITE_OK;
  56865. assert( !db->mallocFailed );
  56866. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  56867. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  56868. sqlite3DbFree(db, u.bz.zSql);
  56869. db->init.busy = 0;
  56870. }
  56871. }
  56872. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  56873. if( rc==SQLITE_NOMEM ){
  56874. goto no_mem;
  56875. }
  56876. break;
  56877. }
  56878. #if !defined(SQLITE_OMIT_ANALYZE)
  56879. /* Opcode: LoadAnalysis P1 * * * *
  56880. **
  56881. ** Read the sqlite_stat1 table for database P1 and load the content
  56882. ** of that table into the internal index hash table. This will cause
  56883. ** the analysis to be used when preparing all subsequent queries.
  56884. */
  56885. case OP_LoadAnalysis: {
  56886. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  56887. rc = sqlite3AnalysisLoad(db, pOp->p1);
  56888. break;
  56889. }
  56890. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  56891. /* Opcode: DropTable P1 * * P4 *
  56892. **
  56893. ** Remove the internal (in-memory) data structures that describe
  56894. ** the table named P4 in database P1. This is called after a table
  56895. ** is dropped in order to keep the internal representation of the
  56896. ** schema consistent with what is on disk.
  56897. */
  56898. case OP_DropTable: {
  56899. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  56900. break;
  56901. }
  56902. /* Opcode: DropIndex P1 * * P4 *
  56903. **
  56904. ** Remove the internal (in-memory) data structures that describe
  56905. ** the index named P4 in database P1. This is called after an index
  56906. ** is dropped in order to keep the internal representation of the
  56907. ** schema consistent with what is on disk.
  56908. */
  56909. case OP_DropIndex: {
  56910. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  56911. break;
  56912. }
  56913. /* Opcode: DropTrigger P1 * * P4 *
  56914. **
  56915. ** Remove the internal (in-memory) data structures that describe
  56916. ** the trigger named P4 in database P1. This is called after a trigger
  56917. ** is dropped in order to keep the internal representation of the
  56918. ** schema consistent with what is on disk.
  56919. */
  56920. case OP_DropTrigger: {
  56921. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  56922. break;
  56923. }
  56924. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56925. /* Opcode: IntegrityCk P1 P2 P3 * P5
  56926. **
  56927. ** Do an analysis of the currently open database. Store in
  56928. ** register P1 the text of an error message describing any problems.
  56929. ** If no problems are found, store a NULL in register P1.
  56930. **
  56931. ** The register P3 contains the maximum number of allowed errors.
  56932. ** At most reg(P3) errors will be reported.
  56933. ** In other words, the analysis stops as soon as reg(P1) errors are
  56934. ** seen. Reg(P1) is updated with the number of errors remaining.
  56935. **
  56936. ** The root page numbers of all tables in the database are integer
  56937. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  56938. ** total.
  56939. **
  56940. ** If P5 is not zero, the check is done on the auxiliary database
  56941. ** file, not the main database file.
  56942. **
  56943. ** This opcode is used to implement the integrity_check pragma.
  56944. */
  56945. case OP_IntegrityCk: {
  56946. #if 0 /* local variables moved into u.ca */
  56947. int nRoot; /* Number of tables to check. (Number of root pages.) */
  56948. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  56949. int j; /* Loop counter */
  56950. int nErr; /* Number of errors reported */
  56951. char *z; /* Text of the error report */
  56952. Mem *pnErr; /* Register keeping track of errors remaining */
  56953. #endif /* local variables moved into u.ca */
  56954. assert( p->bIsReader );
  56955. u.ca.nRoot = pOp->p2;
  56956. assert( u.ca.nRoot>0 );
  56957. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  56958. if( u.ca.aRoot==0 ) goto no_mem;
  56959. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  56960. u.ca.pnErr = &aMem[pOp->p3];
  56961. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  56962. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  56963. pIn1 = &aMem[pOp->p1];
  56964. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  56965. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  56966. }
  56967. u.ca.aRoot[u.ca.j] = 0;
  56968. assert( pOp->p5<db->nDb );
  56969. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  56970. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  56971. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  56972. sqlite3DbFree(db, u.ca.aRoot);
  56973. u.ca.pnErr->u.i -= u.ca.nErr;
  56974. sqlite3VdbeMemSetNull(pIn1);
  56975. if( u.ca.nErr==0 ){
  56976. assert( u.ca.z==0 );
  56977. }else if( u.ca.z==0 ){
  56978. goto no_mem;
  56979. }else{
  56980. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  56981. }
  56982. UPDATE_MAX_BLOBSIZE(pIn1);
  56983. sqlite3VdbeChangeEncoding(pIn1, encoding);
  56984. break;
  56985. }
  56986. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56987. /* Opcode: RowSetAdd P1 P2 * * *
  56988. **
  56989. ** Insert the integer value held by register P2 into a boolean index
  56990. ** held in register P1.
  56991. **
  56992. ** An assertion fails if P2 is not an integer.
  56993. */
  56994. case OP_RowSetAdd: { /* in1, in2 */
  56995. pIn1 = &aMem[pOp->p1];
  56996. pIn2 = &aMem[pOp->p2];
  56997. assert( (pIn2->flags & MEM_Int)!=0 );
  56998. if( (pIn1->flags & MEM_RowSet)==0 ){
  56999. sqlite3VdbeMemSetRowSet(pIn1);
  57000. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  57001. }
  57002. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  57003. break;
  57004. }
  57005. /* Opcode: RowSetRead P1 P2 P3 * *
  57006. **
  57007. ** Extract the smallest value from boolean index P1 and put that value into
  57008. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  57009. ** unchanged and jump to instruction P2.
  57010. */
  57011. case OP_RowSetRead: { /* jump, in1, out3 */
  57012. #if 0 /* local variables moved into u.cb */
  57013. i64 val;
  57014. #endif /* local variables moved into u.cb */
  57015. pIn1 = &aMem[pOp->p1];
  57016. if( (pIn1->flags & MEM_RowSet)==0
  57017. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  57018. ){
  57019. /* The boolean index is empty */
  57020. sqlite3VdbeMemSetNull(pIn1);
  57021. pc = pOp->p2 - 1;
  57022. }else{
  57023. /* A value was pulled from the index */
  57024. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  57025. }
  57026. goto check_for_interrupt;
  57027. }
  57028. /* Opcode: RowSetTest P1 P2 P3 P4
  57029. **
  57030. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  57031. ** contains a RowSet object and that RowSet object contains
  57032. ** the value held in P3, jump to register P2. Otherwise, insert the
  57033. ** integer in P3 into the RowSet and continue on to the
  57034. ** next opcode.
  57035. **
  57036. ** The RowSet object is optimized for the case where successive sets
  57037. ** of integers, where each set contains no duplicates. Each set
  57038. ** of values is identified by a unique P4 value. The first set
  57039. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  57040. ** non-negative. For non-negative values of P4 only the lower 4
  57041. ** bits are significant.
  57042. **
  57043. ** This allows optimizations: (a) when P4==0 there is no need to test
  57044. ** the rowset object for P3, as it is guaranteed not to contain it,
  57045. ** (b) when P4==-1 there is no need to insert the value, as it will
  57046. ** never be tested for, and (c) when a value that is part of set X is
  57047. ** inserted, there is no need to search to see if the same value was
  57048. ** previously inserted as part of set X (only if it was previously
  57049. ** inserted as part of some other set).
  57050. */
  57051. case OP_RowSetTest: { /* jump, in1, in3 */
  57052. #if 0 /* local variables moved into u.cc */
  57053. int iSet;
  57054. int exists;
  57055. #endif /* local variables moved into u.cc */
  57056. pIn1 = &aMem[pOp->p1];
  57057. pIn3 = &aMem[pOp->p3];
  57058. u.cc.iSet = pOp->p4.i;
  57059. assert( pIn3->flags&MEM_Int );
  57060. /* If there is anything other than a rowset object in memory cell P1,
  57061. ** delete it now and initialize P1 with an empty rowset
  57062. */
  57063. if( (pIn1->flags & MEM_RowSet)==0 ){
  57064. sqlite3VdbeMemSetRowSet(pIn1);
  57065. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  57066. }
  57067. assert( pOp->p4type==P4_INT32 );
  57068. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  57069. if( u.cc.iSet ){
  57070. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  57071. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  57072. pIn3->u.i);
  57073. if( u.cc.exists ){
  57074. pc = pOp->p2 - 1;
  57075. break;
  57076. }
  57077. }
  57078. if( u.cc.iSet>=0 ){
  57079. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  57080. }
  57081. break;
  57082. }
  57083. #ifndef SQLITE_OMIT_TRIGGER
  57084. /* Opcode: Program P1 P2 P3 P4 *
  57085. **
  57086. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  57087. **
  57088. ** P1 contains the address of the memory cell that contains the first memory
  57089. ** cell in an array of values used as arguments to the sub-program. P2
  57090. ** contains the address to jump to if the sub-program throws an IGNORE
  57091. ** exception using the RAISE() function. Register P3 contains the address
  57092. ** of a memory cell in this (the parent) VM that is used to allocate the
  57093. ** memory required by the sub-vdbe at runtime.
  57094. **
  57095. ** P4 is a pointer to the VM containing the trigger program.
  57096. */
  57097. case OP_Program: { /* jump */
  57098. #if 0 /* local variables moved into u.cd */
  57099. int nMem; /* Number of memory registers for sub-program */
  57100. int nByte; /* Bytes of runtime space required for sub-program */
  57101. Mem *pRt; /* Register to allocate runtime space */
  57102. Mem *pMem; /* Used to iterate through memory cells */
  57103. Mem *pEnd; /* Last memory cell in new array */
  57104. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  57105. SubProgram *pProgram; /* Sub-program to execute */
  57106. void *t; /* Token identifying trigger */
  57107. #endif /* local variables moved into u.cd */
  57108. u.cd.pProgram = pOp->p4.pProgram;
  57109. u.cd.pRt = &aMem[pOp->p3];
  57110. assert( u.cd.pProgram->nOp>0 );
  57111. /* If the p5 flag is clear, then recursive invocation of triggers is
  57112. ** disabled for backwards compatibility (p5 is set if this sub-program
  57113. ** is really a trigger, not a foreign key action, and the flag set
  57114. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  57115. **
  57116. ** It is recursive invocation of triggers, at the SQL level, that is
  57117. ** disabled. In some cases a single trigger may generate more than one
  57118. ** SubProgram (if the trigger may be executed with more than one different
  57119. ** ON CONFLICT algorithm). SubProgram structures associated with a
  57120. ** single trigger all have the same value for the SubProgram.token
  57121. ** variable. */
  57122. if( pOp->p5 ){
  57123. u.cd.t = u.cd.pProgram->token;
  57124. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  57125. if( u.cd.pFrame ) break;
  57126. }
  57127. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  57128. rc = SQLITE_ERROR;
  57129. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  57130. break;
  57131. }
  57132. /* Register u.cd.pRt is used to store the memory required to save the state
  57133. ** of the current program, and the memory required at runtime to execute
  57134. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  57135. ** is already allocated. Otherwise, it must be initialized. */
  57136. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  57137. /* SubProgram.nMem is set to the number of memory cells used by the
  57138. ** program stored in SubProgram.aOp. As well as these, one memory
  57139. ** cell is required for each cursor used by the program. Set local
  57140. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  57141. */
  57142. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  57143. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  57144. + u.cd.nMem * sizeof(Mem)
  57145. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  57146. + u.cd.pProgram->nOnce * sizeof(u8);
  57147. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  57148. if( !u.cd.pFrame ){
  57149. goto no_mem;
  57150. }
  57151. sqlite3VdbeMemRelease(u.cd.pRt);
  57152. u.cd.pRt->flags = MEM_Frame;
  57153. u.cd.pRt->u.pFrame = u.cd.pFrame;
  57154. u.cd.pFrame->v = p;
  57155. u.cd.pFrame->nChildMem = u.cd.nMem;
  57156. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  57157. u.cd.pFrame->pc = pc;
  57158. u.cd.pFrame->aMem = p->aMem;
  57159. u.cd.pFrame->nMem = p->nMem;
  57160. u.cd.pFrame->apCsr = p->apCsr;
  57161. u.cd.pFrame->nCursor = p->nCursor;
  57162. u.cd.pFrame->aOp = p->aOp;
  57163. u.cd.pFrame->nOp = p->nOp;
  57164. u.cd.pFrame->token = u.cd.pProgram->token;
  57165. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  57166. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  57167. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  57168. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  57169. u.cd.pMem->flags = MEM_Invalid;
  57170. u.cd.pMem->db = db;
  57171. }
  57172. }else{
  57173. u.cd.pFrame = u.cd.pRt->u.pFrame;
  57174. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  57175. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  57176. assert( pc==u.cd.pFrame->pc );
  57177. }
  57178. p->nFrame++;
  57179. u.cd.pFrame->pParent = p->pFrame;
  57180. u.cd.pFrame->lastRowid = lastRowid;
  57181. u.cd.pFrame->nChange = p->nChange;
  57182. p->nChange = 0;
  57183. p->pFrame = u.cd.pFrame;
  57184. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  57185. p->nMem = u.cd.pFrame->nChildMem;
  57186. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  57187. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  57188. p->aOp = aOp = u.cd.pProgram->aOp;
  57189. p->nOp = u.cd.pProgram->nOp;
  57190. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  57191. p->nOnceFlag = u.cd.pProgram->nOnce;
  57192. pc = -1;
  57193. memset(p->aOnceFlag, 0, p->nOnceFlag);
  57194. break;
  57195. }
  57196. /* Opcode: Param P1 P2 * * *
  57197. **
  57198. ** This opcode is only ever present in sub-programs called via the
  57199. ** OP_Program instruction. Copy a value currently stored in a memory
  57200. ** cell of the calling (parent) frame to cell P2 in the current frames
  57201. ** address space. This is used by trigger programs to access the new.*
  57202. ** and old.* values.
  57203. **
  57204. ** The address of the cell in the parent frame is determined by adding
  57205. ** the value of the P1 argument to the value of the P1 argument to the
  57206. ** calling OP_Program instruction.
  57207. */
  57208. case OP_Param: { /* out2-prerelease */
  57209. #if 0 /* local variables moved into u.ce */
  57210. VdbeFrame *pFrame;
  57211. Mem *pIn;
  57212. #endif /* local variables moved into u.ce */
  57213. u.ce.pFrame = p->pFrame;
  57214. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  57215. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  57216. break;
  57217. }
  57218. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  57219. #ifndef SQLITE_OMIT_FOREIGN_KEY
  57220. /* Opcode: FkCounter P1 P2 * * *
  57221. **
  57222. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  57223. ** If P1 is non-zero, the database constraint counter is incremented
  57224. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  57225. ** statement counter is incremented (immediate foreign key constraints).
  57226. */
  57227. case OP_FkCounter: {
  57228. if( db->flags & SQLITE_DeferFKs ){
  57229. db->nDeferredImmCons += pOp->p2;
  57230. }else if( pOp->p1 ){
  57231. db->nDeferredCons += pOp->p2;
  57232. }else{
  57233. p->nFkConstraint += pOp->p2;
  57234. }
  57235. break;
  57236. }
  57237. /* Opcode: FkIfZero P1 P2 * * *
  57238. **
  57239. ** This opcode tests if a foreign key constraint-counter is currently zero.
  57240. ** If so, jump to instruction P2. Otherwise, fall through to the next
  57241. ** instruction.
  57242. **
  57243. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  57244. ** is zero (the one that counts deferred constraint violations). If P1 is
  57245. ** zero, the jump is taken if the statement constraint-counter is zero
  57246. ** (immediate foreign key constraint violations).
  57247. */
  57248. case OP_FkIfZero: { /* jump */
  57249. if( pOp->p1 ){
  57250. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  57251. }else{
  57252. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  57253. }
  57254. break;
  57255. }
  57256. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  57257. #ifndef SQLITE_OMIT_AUTOINCREMENT
  57258. /* Opcode: MemMax P1 P2 * * *
  57259. **
  57260. ** P1 is a register in the root frame of this VM (the root frame is
  57261. ** different from the current frame if this instruction is being executed
  57262. ** within a sub-program). Set the value of register P1 to the maximum of
  57263. ** its current value and the value in register P2.
  57264. **
  57265. ** This instruction throws an error if the memory cell is not initially
  57266. ** an integer.
  57267. */
  57268. case OP_MemMax: { /* in2 */
  57269. #if 0 /* local variables moved into u.cf */
  57270. Mem *pIn1;
  57271. VdbeFrame *pFrame;
  57272. #endif /* local variables moved into u.cf */
  57273. if( p->pFrame ){
  57274. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  57275. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  57276. }else{
  57277. u.cf.pIn1 = &aMem[pOp->p1];
  57278. }
  57279. assert( memIsValid(u.cf.pIn1) );
  57280. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  57281. pIn2 = &aMem[pOp->p2];
  57282. sqlite3VdbeMemIntegerify(pIn2);
  57283. if( u.cf.pIn1->u.i<pIn2->u.i){
  57284. u.cf.pIn1->u.i = pIn2->u.i;
  57285. }
  57286. break;
  57287. }
  57288. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  57289. /* Opcode: IfPos P1 P2 * * *
  57290. **
  57291. ** If the value of register P1 is 1 or greater, jump to P2.
  57292. **
  57293. ** It is illegal to use this instruction on a register that does
  57294. ** not contain an integer. An assertion fault will result if you try.
  57295. */
  57296. case OP_IfPos: { /* jump, in1 */
  57297. pIn1 = &aMem[pOp->p1];
  57298. assert( pIn1->flags&MEM_Int );
  57299. if( pIn1->u.i>0 ){
  57300. pc = pOp->p2 - 1;
  57301. }
  57302. break;
  57303. }
  57304. /* Opcode: IfNeg P1 P2 * * *
  57305. **
  57306. ** If the value of register P1 is less than zero, jump to P2.
  57307. **
  57308. ** It is illegal to use this instruction on a register that does
  57309. ** not contain an integer. An assertion fault will result if you try.
  57310. */
  57311. case OP_IfNeg: { /* jump, in1 */
  57312. pIn1 = &aMem[pOp->p1];
  57313. assert( pIn1->flags&MEM_Int );
  57314. if( pIn1->u.i<0 ){
  57315. pc = pOp->p2 - 1;
  57316. }
  57317. break;
  57318. }
  57319. /* Opcode: IfZero P1 P2 P3 * *
  57320. **
  57321. ** The register P1 must contain an integer. Add literal P3 to the
  57322. ** value in register P1. If the result is exactly 0, jump to P2.
  57323. **
  57324. ** It is illegal to use this instruction on a register that does
  57325. ** not contain an integer. An assertion fault will result if you try.
  57326. */
  57327. case OP_IfZero: { /* jump, in1 */
  57328. pIn1 = &aMem[pOp->p1];
  57329. assert( pIn1->flags&MEM_Int );
  57330. pIn1->u.i += pOp->p3;
  57331. if( pIn1->u.i==0 ){
  57332. pc = pOp->p2 - 1;
  57333. }
  57334. break;
  57335. }
  57336. /* Opcode: AggStep * P2 P3 P4 P5
  57337. **
  57338. ** Execute the step function for an aggregate. The
  57339. ** function has P5 arguments. P4 is a pointer to the FuncDef
  57340. ** structure that specifies the function. Use register
  57341. ** P3 as the accumulator.
  57342. **
  57343. ** The P5 arguments are taken from register P2 and its
  57344. ** successors.
  57345. */
  57346. case OP_AggStep: {
  57347. #if 0 /* local variables moved into u.cg */
  57348. int n;
  57349. int i;
  57350. Mem *pMem;
  57351. Mem *pRec;
  57352. sqlite3_context ctx;
  57353. sqlite3_value **apVal;
  57354. #endif /* local variables moved into u.cg */
  57355. u.cg.n = pOp->p5;
  57356. assert( u.cg.n>=0 );
  57357. u.cg.pRec = &aMem[pOp->p2];
  57358. u.cg.apVal = p->apArg;
  57359. assert( u.cg.apVal || u.cg.n==0 );
  57360. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  57361. assert( memIsValid(u.cg.pRec) );
  57362. u.cg.apVal[u.cg.i] = u.cg.pRec;
  57363. memAboutToChange(p, u.cg.pRec);
  57364. sqlite3VdbeMemStoreType(u.cg.pRec);
  57365. }
  57366. u.cg.ctx.pFunc = pOp->p4.pFunc;
  57367. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  57368. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  57369. u.cg.pMem->n++;
  57370. u.cg.ctx.s.flags = MEM_Null;
  57371. u.cg.ctx.s.z = 0;
  57372. u.cg.ctx.s.zMalloc = 0;
  57373. u.cg.ctx.s.xDel = 0;
  57374. u.cg.ctx.s.db = db;
  57375. u.cg.ctx.isError = 0;
  57376. u.cg.ctx.pColl = 0;
  57377. u.cg.ctx.skipFlag = 0;
  57378. if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  57379. assert( pOp>p->aOp );
  57380. assert( pOp[-1].p4type==P4_COLLSEQ );
  57381. assert( pOp[-1].opcode==OP_CollSeq );
  57382. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  57383. }
  57384. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  57385. if( u.cg.ctx.isError ){
  57386. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  57387. rc = u.cg.ctx.isError;
  57388. }
  57389. if( u.cg.ctx.skipFlag ){
  57390. assert( pOp[-1].opcode==OP_CollSeq );
  57391. u.cg.i = pOp[-1].p1;
  57392. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  57393. }
  57394. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  57395. break;
  57396. }
  57397. /* Opcode: AggFinal P1 P2 * P4 *
  57398. **
  57399. ** Execute the finalizer function for an aggregate. P1 is
  57400. ** the memory location that is the accumulator for the aggregate.
  57401. **
  57402. ** P2 is the number of arguments that the step function takes and
  57403. ** P4 is a pointer to the FuncDef for this function. The P2
  57404. ** argument is not used by this opcode. It is only there to disambiguate
  57405. ** functions that can take varying numbers of arguments. The
  57406. ** P4 argument is only needed for the degenerate case where
  57407. ** the step function was not previously called.
  57408. */
  57409. case OP_AggFinal: {
  57410. #if 0 /* local variables moved into u.ch */
  57411. Mem *pMem;
  57412. #endif /* local variables moved into u.ch */
  57413. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  57414. u.ch.pMem = &aMem[pOp->p1];
  57415. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  57416. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  57417. if( rc ){
  57418. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  57419. }
  57420. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  57421. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  57422. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  57423. goto too_big;
  57424. }
  57425. break;
  57426. }
  57427. #ifndef SQLITE_OMIT_WAL
  57428. /* Opcode: Checkpoint P1 P2 P3 * *
  57429. **
  57430. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  57431. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  57432. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  57433. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  57434. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  57435. ** in the WAL that have been checkpointed after the checkpoint
  57436. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  57437. ** mem[P3+2] are initialized to -1.
  57438. */
  57439. case OP_Checkpoint: {
  57440. #if 0 /* local variables moved into u.ci */
  57441. int i; /* Loop counter */
  57442. int aRes[3]; /* Results */
  57443. Mem *pMem; /* Write results here */
  57444. #endif /* local variables moved into u.ci */
  57445. assert( p->readOnly==0 );
  57446. u.ci.aRes[0] = 0;
  57447. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  57448. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  57449. || pOp->p2==SQLITE_CHECKPOINT_FULL
  57450. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  57451. );
  57452. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  57453. if( rc==SQLITE_BUSY ){
  57454. rc = SQLITE_OK;
  57455. u.ci.aRes[0] = 1;
  57456. }
  57457. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  57458. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  57459. }
  57460. break;
  57461. };
  57462. #endif
  57463. #ifndef SQLITE_OMIT_PRAGMA
  57464. /* Opcode: JournalMode P1 P2 P3 * P5
  57465. **
  57466. ** Change the journal mode of database P1 to P3. P3 must be one of the
  57467. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  57468. ** modes (delete, truncate, persist, off and memory), this is a simple
  57469. ** operation. No IO is required.
  57470. **
  57471. ** If changing into or out of WAL mode the procedure is more complicated.
  57472. **
  57473. ** Write a string containing the final journal-mode to register P2.
  57474. */
  57475. case OP_JournalMode: { /* out2-prerelease */
  57476. #if 0 /* local variables moved into u.cj */
  57477. Btree *pBt; /* Btree to change journal mode of */
  57478. Pager *pPager; /* Pager associated with pBt */
  57479. int eNew; /* New journal mode */
  57480. int eOld; /* The old journal mode */
  57481. #ifndef SQLITE_OMIT_WAL
  57482. const char *zFilename; /* Name of database file for pPager */
  57483. #endif
  57484. #endif /* local variables moved into u.cj */
  57485. u.cj.eNew = pOp->p3;
  57486. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  57487. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  57488. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  57489. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  57490. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  57491. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  57492. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  57493. );
  57494. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  57495. assert( p->readOnly==0 );
  57496. u.cj.pBt = db->aDb[pOp->p1].pBt;
  57497. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  57498. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  57499. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  57500. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  57501. #ifndef SQLITE_OMIT_WAL
  57502. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  57503. /* Do not allow a transition to journal_mode=WAL for a database
  57504. ** in temporary storage or if the VFS does not support shared memory
  57505. */
  57506. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  57507. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  57508. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  57509. ){
  57510. u.cj.eNew = u.cj.eOld;
  57511. }
  57512. if( (u.cj.eNew!=u.cj.eOld)
  57513. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  57514. ){
  57515. if( !db->autoCommit || db->nVdbeRead>1 ){
  57516. rc = SQLITE_ERROR;
  57517. sqlite3SetString(&p->zErrMsg, db,
  57518. "cannot change %s wal mode from within a transaction",
  57519. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  57520. );
  57521. break;
  57522. }else{
  57523. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  57524. /* If leaving WAL mode, close the log file. If successful, the call
  57525. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  57526. ** file. An EXCLUSIVE lock may still be held on the database file
  57527. ** after a successful return.
  57528. */
  57529. rc = sqlite3PagerCloseWal(u.cj.pPager);
  57530. if( rc==SQLITE_OK ){
  57531. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  57532. }
  57533. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  57534. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  57535. ** as an intermediate */
  57536. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  57537. }
  57538. /* Open a transaction on the database file. Regardless of the journal
  57539. ** mode, this transaction always uses a rollback journal.
  57540. */
  57541. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  57542. if( rc==SQLITE_OK ){
  57543. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  57544. }
  57545. }
  57546. }
  57547. #endif /* ifndef SQLITE_OMIT_WAL */
  57548. if( rc ){
  57549. u.cj.eNew = u.cj.eOld;
  57550. }
  57551. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  57552. pOut = &aMem[pOp->p2];
  57553. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  57554. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  57555. pOut->n = sqlite3Strlen30(pOut->z);
  57556. pOut->enc = SQLITE_UTF8;
  57557. sqlite3VdbeChangeEncoding(pOut, encoding);
  57558. break;
  57559. };
  57560. #endif /* SQLITE_OMIT_PRAGMA */
  57561. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  57562. /* Opcode: Vacuum * * * * *
  57563. **
  57564. ** Vacuum the entire database. This opcode will cause other virtual
  57565. ** machines to be created and run. It may not be called from within
  57566. ** a transaction.
  57567. */
  57568. case OP_Vacuum: {
  57569. assert( p->readOnly==0 );
  57570. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  57571. break;
  57572. }
  57573. #endif
  57574. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  57575. /* Opcode: IncrVacuum P1 P2 * * *
  57576. **
  57577. ** Perform a single step of the incremental vacuum procedure on
  57578. ** the P1 database. If the vacuum has finished, jump to instruction
  57579. ** P2. Otherwise, fall through to the next instruction.
  57580. */
  57581. case OP_IncrVacuum: { /* jump */
  57582. #if 0 /* local variables moved into u.ck */
  57583. Btree *pBt;
  57584. #endif /* local variables moved into u.ck */
  57585. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  57586. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  57587. assert( p->readOnly==0 );
  57588. u.ck.pBt = db->aDb[pOp->p1].pBt;
  57589. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  57590. if( rc==SQLITE_DONE ){
  57591. pc = pOp->p2 - 1;
  57592. rc = SQLITE_OK;
  57593. }
  57594. break;
  57595. }
  57596. #endif
  57597. /* Opcode: Expire P1 * * * *
  57598. **
  57599. ** Cause precompiled statements to become expired. An expired statement
  57600. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  57601. ** (via sqlite3_step()).
  57602. **
  57603. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  57604. ** then only the currently executing statement is affected.
  57605. */
  57606. case OP_Expire: {
  57607. if( !pOp->p1 ){
  57608. sqlite3ExpirePreparedStatements(db);
  57609. }else{
  57610. p->expired = 1;
  57611. }
  57612. break;
  57613. }
  57614. #ifndef SQLITE_OMIT_SHARED_CACHE
  57615. /* Opcode: TableLock P1 P2 P3 P4 *
  57616. **
  57617. ** Obtain a lock on a particular table. This instruction is only used when
  57618. ** the shared-cache feature is enabled.
  57619. **
  57620. ** P1 is the index of the database in sqlite3.aDb[] of the database
  57621. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  57622. ** a write lock if P3==1.
  57623. **
  57624. ** P2 contains the root-page of the table to lock.
  57625. **
  57626. ** P4 contains a pointer to the name of the table being locked. This is only
  57627. ** used to generate an error message if the lock cannot be obtained.
  57628. */
  57629. case OP_TableLock: {
  57630. u8 isWriteLock = (u8)pOp->p3;
  57631. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  57632. int p1 = pOp->p1;
  57633. assert( p1>=0 && p1<db->nDb );
  57634. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  57635. assert( isWriteLock==0 || isWriteLock==1 );
  57636. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  57637. if( (rc&0xFF)==SQLITE_LOCKED ){
  57638. const char *z = pOp->p4.z;
  57639. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  57640. }
  57641. }
  57642. break;
  57643. }
  57644. #endif /* SQLITE_OMIT_SHARED_CACHE */
  57645. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57646. /* Opcode: VBegin * * * P4 *
  57647. **
  57648. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  57649. ** xBegin method for that table.
  57650. **
  57651. ** Also, whether or not P4 is set, check that this is not being called from
  57652. ** within a callback to a virtual table xSync() method. If it is, the error
  57653. ** code will be set to SQLITE_LOCKED.
  57654. */
  57655. case OP_VBegin: {
  57656. #if 0 /* local variables moved into u.cl */
  57657. VTable *pVTab;
  57658. #endif /* local variables moved into u.cl */
  57659. u.cl.pVTab = pOp->p4.pVtab;
  57660. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  57661. if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
  57662. break;
  57663. }
  57664. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57665. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57666. /* Opcode: VCreate P1 * * P4 *
  57667. **
  57668. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  57669. ** for that table.
  57670. */
  57671. case OP_VCreate: {
  57672. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  57673. break;
  57674. }
  57675. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57676. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57677. /* Opcode: VDestroy P1 * * P4 *
  57678. **
  57679. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  57680. ** of that table.
  57681. */
  57682. case OP_VDestroy: {
  57683. p->inVtabMethod = 2;
  57684. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  57685. p->inVtabMethod = 0;
  57686. break;
  57687. }
  57688. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57689. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57690. /* Opcode: VOpen P1 * * P4 *
  57691. **
  57692. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57693. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  57694. ** table and stores that cursor in P1.
  57695. */
  57696. case OP_VOpen: {
  57697. #if 0 /* local variables moved into u.cm */
  57698. VdbeCursor *pCur;
  57699. sqlite3_vtab_cursor *pVtabCursor;
  57700. sqlite3_vtab *pVtab;
  57701. sqlite3_module *pModule;
  57702. #endif /* local variables moved into u.cm */
  57703. assert( p->bIsReader );
  57704. u.cm.pCur = 0;
  57705. u.cm.pVtabCursor = 0;
  57706. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  57707. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  57708. assert(u.cm.pVtab && u.cm.pModule);
  57709. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  57710. sqlite3VtabImportErrmsg(p, u.cm.pVtab);
  57711. if( SQLITE_OK==rc ){
  57712. /* Initialize sqlite3_vtab_cursor base class */
  57713. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  57714. /* Initialize vdbe cursor object */
  57715. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  57716. if( u.cm.pCur ){
  57717. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  57718. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  57719. }else{
  57720. db->mallocFailed = 1;
  57721. u.cm.pModule->xClose(u.cm.pVtabCursor);
  57722. }
  57723. }
  57724. break;
  57725. }
  57726. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57727. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57728. /* Opcode: VFilter P1 P2 P3 P4 *
  57729. **
  57730. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  57731. ** the filtered result set is empty.
  57732. **
  57733. ** P4 is either NULL or a string that was generated by the xBestIndex
  57734. ** method of the module. The interpretation of the P4 string is left
  57735. ** to the module implementation.
  57736. **
  57737. ** This opcode invokes the xFilter method on the virtual table specified
  57738. ** by P1. The integer query plan parameter to xFilter is stored in register
  57739. ** P3. Register P3+1 stores the argc parameter to be passed to the
  57740. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  57741. ** additional parameters which are passed to
  57742. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  57743. **
  57744. ** A jump is made to P2 if the result set after filtering would be empty.
  57745. */
  57746. case OP_VFilter: { /* jump */
  57747. #if 0 /* local variables moved into u.cn */
  57748. int nArg;
  57749. int iQuery;
  57750. const sqlite3_module *pModule;
  57751. Mem *pQuery;
  57752. Mem *pArgc;
  57753. sqlite3_vtab_cursor *pVtabCursor;
  57754. sqlite3_vtab *pVtab;
  57755. VdbeCursor *pCur;
  57756. int res;
  57757. int i;
  57758. Mem **apArg;
  57759. #endif /* local variables moved into u.cn */
  57760. u.cn.pQuery = &aMem[pOp->p3];
  57761. u.cn.pArgc = &u.cn.pQuery[1];
  57762. u.cn.pCur = p->apCsr[pOp->p1];
  57763. assert( memIsValid(u.cn.pQuery) );
  57764. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  57765. assert( u.cn.pCur->pVtabCursor );
  57766. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  57767. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  57768. u.cn.pModule = u.cn.pVtab->pModule;
  57769. /* Grab the index number and argc parameters */
  57770. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  57771. u.cn.nArg = (int)u.cn.pArgc->u.i;
  57772. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  57773. /* Invoke the xFilter method */
  57774. {
  57775. u.cn.res = 0;
  57776. u.cn.apArg = p->apArg;
  57777. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  57778. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  57779. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  57780. }
  57781. p->inVtabMethod = 1;
  57782. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  57783. p->inVtabMethod = 0;
  57784. sqlite3VtabImportErrmsg(p, u.cn.pVtab);
  57785. if( rc==SQLITE_OK ){
  57786. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  57787. }
  57788. if( u.cn.res ){
  57789. pc = pOp->p2 - 1;
  57790. }
  57791. }
  57792. u.cn.pCur->nullRow = 0;
  57793. break;
  57794. }
  57795. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57796. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57797. /* Opcode: VColumn P1 P2 P3 * *
  57798. **
  57799. ** Store the value of the P2-th column of
  57800. ** the row of the virtual-table that the
  57801. ** P1 cursor is pointing to into register P3.
  57802. */
  57803. case OP_VColumn: {
  57804. #if 0 /* local variables moved into u.co */
  57805. sqlite3_vtab *pVtab;
  57806. const sqlite3_module *pModule;
  57807. Mem *pDest;
  57808. sqlite3_context sContext;
  57809. #endif /* local variables moved into u.co */
  57810. VdbeCursor *pCur = p->apCsr[pOp->p1];
  57811. assert( pCur->pVtabCursor );
  57812. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  57813. u.co.pDest = &aMem[pOp->p3];
  57814. memAboutToChange(p, u.co.pDest);
  57815. if( pCur->nullRow ){
  57816. sqlite3VdbeMemSetNull(u.co.pDest);
  57817. break;
  57818. }
  57819. u.co.pVtab = pCur->pVtabCursor->pVtab;
  57820. u.co.pModule = u.co.pVtab->pModule;
  57821. assert( u.co.pModule->xColumn );
  57822. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  57823. /* The output cell may already have a buffer allocated. Move
  57824. ** the current contents to u.co.sContext.s so in case the user-function
  57825. ** can use the already allocated buffer instead of allocating a
  57826. ** new one.
  57827. */
  57828. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  57829. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  57830. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  57831. sqlite3VtabImportErrmsg(p, u.co.pVtab);
  57832. if( u.co.sContext.isError ){
  57833. rc = u.co.sContext.isError;
  57834. }
  57835. /* Copy the result of the function to the P3 register. We
  57836. ** do this regardless of whether or not an error occurred to ensure any
  57837. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  57838. */
  57839. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  57840. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  57841. REGISTER_TRACE(pOp->p3, u.co.pDest);
  57842. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  57843. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  57844. goto too_big;
  57845. }
  57846. break;
  57847. }
  57848. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57849. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57850. /* Opcode: VNext P1 P2 * * *
  57851. **
  57852. ** Advance virtual table P1 to the next row in its result set and
  57853. ** jump to instruction P2. Or, if the virtual table has reached
  57854. ** the end of its result set, then fall through to the next instruction.
  57855. */
  57856. case OP_VNext: { /* jump */
  57857. #if 0 /* local variables moved into u.cp */
  57858. sqlite3_vtab *pVtab;
  57859. const sqlite3_module *pModule;
  57860. int res;
  57861. VdbeCursor *pCur;
  57862. #endif /* local variables moved into u.cp */
  57863. u.cp.res = 0;
  57864. u.cp.pCur = p->apCsr[pOp->p1];
  57865. assert( u.cp.pCur->pVtabCursor );
  57866. if( u.cp.pCur->nullRow ){
  57867. break;
  57868. }
  57869. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  57870. u.cp.pModule = u.cp.pVtab->pModule;
  57871. assert( u.cp.pModule->xNext );
  57872. /* Invoke the xNext() method of the module. There is no way for the
  57873. ** underlying implementation to return an error if one occurs during
  57874. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  57875. ** data is available) and the error code returned when xColumn or
  57876. ** some other method is next invoked on the save virtual table cursor.
  57877. */
  57878. p->inVtabMethod = 1;
  57879. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  57880. p->inVtabMethod = 0;
  57881. sqlite3VtabImportErrmsg(p, u.cp.pVtab);
  57882. if( rc==SQLITE_OK ){
  57883. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  57884. }
  57885. if( !u.cp.res ){
  57886. /* If there is data, jump to P2 */
  57887. pc = pOp->p2 - 1;
  57888. }
  57889. goto check_for_interrupt;
  57890. }
  57891. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57892. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57893. /* Opcode: VRename P1 * * P4 *
  57894. **
  57895. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57896. ** This opcode invokes the corresponding xRename method. The value
  57897. ** in register P1 is passed as the zName argument to the xRename method.
  57898. */
  57899. case OP_VRename: {
  57900. #if 0 /* local variables moved into u.cq */
  57901. sqlite3_vtab *pVtab;
  57902. Mem *pName;
  57903. #endif /* local variables moved into u.cq */
  57904. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  57905. u.cq.pName = &aMem[pOp->p1];
  57906. assert( u.cq.pVtab->pModule->xRename );
  57907. assert( memIsValid(u.cq.pName) );
  57908. assert( p->readOnly==0 );
  57909. REGISTER_TRACE(pOp->p1, u.cq.pName);
  57910. assert( u.cq.pName->flags & MEM_Str );
  57911. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  57912. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  57913. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  57914. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  57915. if( rc==SQLITE_OK ){
  57916. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  57917. sqlite3VtabImportErrmsg(p, u.cq.pVtab);
  57918. p->expired = 0;
  57919. }
  57920. break;
  57921. }
  57922. #endif
  57923. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57924. /* Opcode: VUpdate P1 P2 P3 P4 *
  57925. **
  57926. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57927. ** This opcode invokes the corresponding xUpdate method. P2 values
  57928. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  57929. ** invocation. The value in register (P3+P2-1) corresponds to the
  57930. ** p2th element of the argv array passed to xUpdate.
  57931. **
  57932. ** The xUpdate method will do a DELETE or an INSERT or both.
  57933. ** The argv[0] element (which corresponds to memory cell P3)
  57934. ** is the rowid of a row to delete. If argv[0] is NULL then no
  57935. ** deletion occurs. The argv[1] element is the rowid of the new
  57936. ** row. This can be NULL to have the virtual table select the new
  57937. ** rowid for itself. The subsequent elements in the array are
  57938. ** the values of columns in the new row.
  57939. **
  57940. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  57941. ** a row to delete.
  57942. **
  57943. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  57944. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  57945. ** is set to the value of the rowid for the row just inserted.
  57946. */
  57947. case OP_VUpdate: {
  57948. #if 0 /* local variables moved into u.cr */
  57949. sqlite3_vtab *pVtab;
  57950. sqlite3_module *pModule;
  57951. int nArg;
  57952. int i;
  57953. sqlite_int64 rowid;
  57954. Mem **apArg;
  57955. Mem *pX;
  57956. #endif /* local variables moved into u.cr */
  57957. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  57958. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  57959. );
  57960. assert( p->readOnly==0 );
  57961. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  57962. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  57963. u.cr.nArg = pOp->p2;
  57964. assert( pOp->p4type==P4_VTAB );
  57965. if( ALWAYS(u.cr.pModule->xUpdate) ){
  57966. u8 vtabOnConflict = db->vtabOnConflict;
  57967. u.cr.apArg = p->apArg;
  57968. u.cr.pX = &aMem[pOp->p3];
  57969. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  57970. assert( memIsValid(u.cr.pX) );
  57971. memAboutToChange(p, u.cr.pX);
  57972. sqlite3VdbeMemStoreType(u.cr.pX);
  57973. u.cr.apArg[u.cr.i] = u.cr.pX;
  57974. u.cr.pX++;
  57975. }
  57976. db->vtabOnConflict = pOp->p5;
  57977. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  57978. db->vtabOnConflict = vtabOnConflict;
  57979. sqlite3VtabImportErrmsg(p, u.cr.pVtab);
  57980. if( rc==SQLITE_OK && pOp->p1 ){
  57981. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  57982. db->lastRowid = lastRowid = u.cr.rowid;
  57983. }
  57984. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  57985. if( pOp->p5==OE_Ignore ){
  57986. rc = SQLITE_OK;
  57987. }else{
  57988. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  57989. }
  57990. }else{
  57991. p->nChange++;
  57992. }
  57993. }
  57994. break;
  57995. }
  57996. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57997. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  57998. /* Opcode: Pagecount P1 P2 * * *
  57999. **
  58000. ** Write the current number of pages in database P1 to memory cell P2.
  58001. */
  58002. case OP_Pagecount: { /* out2-prerelease */
  58003. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  58004. break;
  58005. }
  58006. #endif
  58007. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  58008. /* Opcode: MaxPgcnt P1 P2 P3 * *
  58009. **
  58010. ** Try to set the maximum page count for database P1 to the value in P3.
  58011. ** Do not let the maximum page count fall below the current page count and
  58012. ** do not change the maximum page count value if P3==0.
  58013. **
  58014. ** Store the maximum page count after the change in register P2.
  58015. */
  58016. case OP_MaxPgcnt: { /* out2-prerelease */
  58017. unsigned int newMax;
  58018. Btree *pBt;
  58019. pBt = db->aDb[pOp->p1].pBt;
  58020. newMax = 0;
  58021. if( pOp->p3 ){
  58022. newMax = sqlite3BtreeLastPage(pBt);
  58023. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  58024. }
  58025. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  58026. break;
  58027. }
  58028. #endif
  58029. #ifndef SQLITE_OMIT_TRACE
  58030. /* Opcode: Trace * * * P4 *
  58031. **
  58032. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  58033. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  58034. */
  58035. case OP_Trace: {
  58036. #if 0 /* local variables moved into u.cs */
  58037. char *zTrace;
  58038. char *z;
  58039. #endif /* local variables moved into u.cs */
  58040. if( db->xTrace
  58041. && !p->doingRerun
  58042. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  58043. ){
  58044. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  58045. db->xTrace(db->pTraceArg, u.cs.z);
  58046. sqlite3DbFree(db, u.cs.z);
  58047. }
  58048. #ifdef SQLITE_DEBUG
  58049. if( (db->flags & SQLITE_SqlTrace)!=0
  58050. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  58051. ){
  58052. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  58053. }
  58054. #endif /* SQLITE_DEBUG */
  58055. break;
  58056. }
  58057. #endif
  58058. /* Opcode: Noop * * * * *
  58059. **
  58060. ** Do nothing. This instruction is often useful as a jump
  58061. ** destination.
  58062. */
  58063. /*
  58064. ** The magic Explain opcode are only inserted when explain==2 (which
  58065. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  58066. ** This opcode records information from the optimizer. It is the
  58067. ** the same as a no-op. This opcodesnever appears in a real VM program.
  58068. */
  58069. default: { /* This is really OP_Noop and OP_Explain */
  58070. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  58071. break;
  58072. }
  58073. /*****************************************************************************
  58074. ** The cases of the switch statement above this line should all be indented
  58075. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  58076. ** readability. From this point on down, the normal indentation rules are
  58077. ** restored.
  58078. *****************************************************************************/
  58079. }
  58080. #ifdef VDBE_PROFILE
  58081. {
  58082. u64 elapsed = sqlite3Hwtime() - start;
  58083. pOp->cycles += elapsed;
  58084. pOp->cnt++;
  58085. #if 0
  58086. fprintf(stdout, "%10llu ", elapsed);
  58087. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  58088. #endif
  58089. }
  58090. #endif
  58091. /* The following code adds nothing to the actual functionality
  58092. ** of the program. It is only here for testing and debugging.
  58093. ** On the other hand, it does burn CPU cycles every time through
  58094. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  58095. */
  58096. #ifndef NDEBUG
  58097. assert( pc>=-1 && pc<p->nOp );
  58098. #ifdef SQLITE_DEBUG
  58099. if( p->trace ){
  58100. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  58101. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  58102. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  58103. }
  58104. if( pOp->opflags & OPFLG_OUT3 ){
  58105. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  58106. }
  58107. }
  58108. #endif /* SQLITE_DEBUG */
  58109. #endif /* NDEBUG */
  58110. } /* The end of the for(;;) loop the loops through opcodes */
  58111. /* If we reach this point, it means that execution is finished with
  58112. ** an error of some kind.
  58113. */
  58114. vdbe_error_halt:
  58115. assert( rc );
  58116. p->rc = rc;
  58117. testcase( sqlite3GlobalConfig.xLog!=0 );
  58118. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  58119. pc, p->zSql, p->zErrMsg);
  58120. sqlite3VdbeHalt(p);
  58121. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  58122. rc = SQLITE_ERROR;
  58123. if( resetSchemaOnFault>0 ){
  58124. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  58125. }
  58126. /* This is the only way out of this procedure. We have to
  58127. ** release the mutexes on btrees that were acquired at the
  58128. ** top. */
  58129. vdbe_return:
  58130. db->lastRowid = lastRowid;
  58131. testcase( nVmStep>0 );
  58132. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  58133. sqlite3VdbeLeave(p);
  58134. return rc;
  58135. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  58136. ** is encountered.
  58137. */
  58138. too_big:
  58139. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  58140. rc = SQLITE_TOOBIG;
  58141. goto vdbe_error_halt;
  58142. /* Jump to here if a malloc() fails.
  58143. */
  58144. no_mem:
  58145. db->mallocFailed = 1;
  58146. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  58147. rc = SQLITE_NOMEM;
  58148. goto vdbe_error_halt;
  58149. /* Jump to here for any other kind of fatal error. The "rc" variable
  58150. ** should hold the error number.
  58151. */
  58152. abort_due_to_error:
  58153. assert( p->zErrMsg==0 );
  58154. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  58155. if( rc!=SQLITE_IOERR_NOMEM ){
  58156. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  58157. }
  58158. goto vdbe_error_halt;
  58159. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  58160. ** flag.
  58161. */
  58162. abort_due_to_interrupt:
  58163. assert( db->u1.isInterrupted );
  58164. rc = SQLITE_INTERRUPT;
  58165. p->rc = rc;
  58166. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  58167. goto vdbe_error_halt;
  58168. }
  58169. /************** End of vdbe.c ************************************************/
  58170. /************** Begin file vdbeblob.c ****************************************/
  58171. /*
  58172. ** 2007 May 1
  58173. **
  58174. ** The author disclaims copyright to this source code. In place of
  58175. ** a legal notice, here is a blessing:
  58176. **
  58177. ** May you do good and not evil.
  58178. ** May you find forgiveness for yourself and forgive others.
  58179. ** May you share freely, never taking more than you give.
  58180. **
  58181. *************************************************************************
  58182. **
  58183. ** This file contains code used to implement incremental BLOB I/O.
  58184. */
  58185. #ifndef SQLITE_OMIT_INCRBLOB
  58186. /*
  58187. ** Valid sqlite3_blob* handles point to Incrblob structures.
  58188. */
  58189. typedef struct Incrblob Incrblob;
  58190. struct Incrblob {
  58191. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  58192. int nByte; /* Size of open blob, in bytes */
  58193. int iOffset; /* Byte offset of blob in cursor data */
  58194. int iCol; /* Table column this handle is open on */
  58195. BtCursor *pCsr; /* Cursor pointing at blob row */
  58196. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  58197. sqlite3 *db; /* The associated database */
  58198. };
  58199. /*
  58200. ** This function is used by both blob_open() and blob_reopen(). It seeks
  58201. ** the b-tree cursor associated with blob handle p to point to row iRow.
  58202. ** If successful, SQLITE_OK is returned and subsequent calls to
  58203. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  58204. **
  58205. ** If an error occurs, or if the specified row does not exist or does not
  58206. ** contain a value of type TEXT or BLOB in the column nominated when the
  58207. ** blob handle was opened, then an error code is returned and *pzErr may
  58208. ** be set to point to a buffer containing an error message. It is the
  58209. ** responsibility of the caller to free the error message buffer using
  58210. ** sqlite3DbFree().
  58211. **
  58212. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  58213. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  58214. ** immediately return SQLITE_ABORT.
  58215. */
  58216. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  58217. int rc; /* Error code */
  58218. char *zErr = 0; /* Error message */
  58219. Vdbe *v = (Vdbe *)p->pStmt;
  58220. /* Set the value of the SQL statements only variable to integer iRow.
  58221. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  58222. ** triggering asserts related to mutexes.
  58223. */
  58224. assert( v->aVar[0].flags&MEM_Int );
  58225. v->aVar[0].u.i = iRow;
  58226. rc = sqlite3_step(p->pStmt);
  58227. if( rc==SQLITE_ROW ){
  58228. u32 type = v->apCsr[0]->aType[p->iCol];
  58229. if( type<12 ){
  58230. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  58231. type==0?"null": type==7?"real": "integer"
  58232. );
  58233. rc = SQLITE_ERROR;
  58234. sqlite3_finalize(p->pStmt);
  58235. p->pStmt = 0;
  58236. }else{
  58237. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  58238. p->nByte = sqlite3VdbeSerialTypeLen(type);
  58239. p->pCsr = v->apCsr[0]->pCursor;
  58240. sqlite3BtreeEnterCursor(p->pCsr);
  58241. sqlite3BtreeCacheOverflow(p->pCsr);
  58242. sqlite3BtreeLeaveCursor(p->pCsr);
  58243. }
  58244. }
  58245. if( rc==SQLITE_ROW ){
  58246. rc = SQLITE_OK;
  58247. }else if( p->pStmt ){
  58248. rc = sqlite3_finalize(p->pStmt);
  58249. p->pStmt = 0;
  58250. if( rc==SQLITE_OK ){
  58251. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  58252. rc = SQLITE_ERROR;
  58253. }else{
  58254. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  58255. }
  58256. }
  58257. assert( rc!=SQLITE_OK || zErr==0 );
  58258. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  58259. *pzErr = zErr;
  58260. return rc;
  58261. }
  58262. /*
  58263. ** Open a blob handle.
  58264. */
  58265. SQLITE_API int sqlite3_blob_open(
  58266. sqlite3* db, /* The database connection */
  58267. const char *zDb, /* The attached database containing the blob */
  58268. const char *zTable, /* The table containing the blob */
  58269. const char *zColumn, /* The column containing the blob */
  58270. sqlite_int64 iRow, /* The row containing the glob */
  58271. int flags, /* True -> read/write access, false -> read-only */
  58272. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  58273. ){
  58274. int nAttempt = 0;
  58275. int iCol; /* Index of zColumn in row-record */
  58276. /* This VDBE program seeks a btree cursor to the identified
  58277. ** db/table/row entry. The reason for using a vdbe program instead
  58278. ** of writing code to use the b-tree layer directly is that the
  58279. ** vdbe program will take advantage of the various transaction,
  58280. ** locking and error handling infrastructure built into the vdbe.
  58281. **
  58282. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  58283. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  58284. ** uses it to implement the blob_read(), blob_write() and
  58285. ** blob_bytes() functions.
  58286. **
  58287. ** The sqlite3_blob_close() function finalizes the vdbe program,
  58288. ** which closes the b-tree cursor and (possibly) commits the
  58289. ** transaction.
  58290. */
  58291. static const VdbeOpList openBlob[] = {
  58292. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  58293. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  58294. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  58295. /* One of the following two instructions is replaced by an OP_Noop. */
  58296. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  58297. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  58298. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  58299. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  58300. {OP_Column, 0, 0, 1}, /* 7 */
  58301. {OP_ResultRow, 1, 0, 0}, /* 8 */
  58302. {OP_Goto, 0, 5, 0}, /* 9 */
  58303. {OP_Close, 0, 0, 0}, /* 10 */
  58304. {OP_Halt, 0, 0, 0}, /* 11 */
  58305. };
  58306. int rc = SQLITE_OK;
  58307. char *zErr = 0;
  58308. Table *pTab;
  58309. Parse *pParse = 0;
  58310. Incrblob *pBlob = 0;
  58311. flags = !!flags; /* flags = (flags ? 1 : 0); */
  58312. *ppBlob = 0;
  58313. sqlite3_mutex_enter(db->mutex);
  58314. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  58315. if( !pBlob ) goto blob_open_out;
  58316. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  58317. if( !pParse ) goto blob_open_out;
  58318. do {
  58319. memset(pParse, 0, sizeof(Parse));
  58320. pParse->db = db;
  58321. sqlite3DbFree(db, zErr);
  58322. zErr = 0;
  58323. sqlite3BtreeEnterAll(db);
  58324. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  58325. if( pTab && IsVirtual(pTab) ){
  58326. pTab = 0;
  58327. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  58328. }
  58329. #ifndef SQLITE_OMIT_VIEW
  58330. if( pTab && pTab->pSelect ){
  58331. pTab = 0;
  58332. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  58333. }
  58334. #endif
  58335. if( !pTab ){
  58336. if( pParse->zErrMsg ){
  58337. sqlite3DbFree(db, zErr);
  58338. zErr = pParse->zErrMsg;
  58339. pParse->zErrMsg = 0;
  58340. }
  58341. rc = SQLITE_ERROR;
  58342. sqlite3BtreeLeaveAll(db);
  58343. goto blob_open_out;
  58344. }
  58345. /* Now search pTab for the exact column. */
  58346. for(iCol=0; iCol<pTab->nCol; iCol++) {
  58347. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  58348. break;
  58349. }
  58350. }
  58351. if( iCol==pTab->nCol ){
  58352. sqlite3DbFree(db, zErr);
  58353. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  58354. rc = SQLITE_ERROR;
  58355. sqlite3BtreeLeaveAll(db);
  58356. goto blob_open_out;
  58357. }
  58358. /* If the value is being opened for writing, check that the
  58359. ** column is not indexed, and that it is not part of a foreign key.
  58360. ** It is against the rules to open a column to which either of these
  58361. ** descriptions applies for writing. */
  58362. if( flags ){
  58363. const char *zFault = 0;
  58364. Index *pIdx;
  58365. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58366. if( db->flags&SQLITE_ForeignKeys ){
  58367. /* Check that the column is not part of an FK child key definition. It
  58368. ** is not necessary to check if it is part of a parent key, as parent
  58369. ** key columns must be indexed. The check below will pick up this
  58370. ** case. */
  58371. FKey *pFKey;
  58372. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  58373. int j;
  58374. for(j=0; j<pFKey->nCol; j++){
  58375. if( pFKey->aCol[j].iFrom==iCol ){
  58376. zFault = "foreign key";
  58377. }
  58378. }
  58379. }
  58380. }
  58381. #endif
  58382. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  58383. int j;
  58384. for(j=0; j<pIdx->nColumn; j++){
  58385. if( pIdx->aiColumn[j]==iCol ){
  58386. zFault = "indexed";
  58387. }
  58388. }
  58389. }
  58390. if( zFault ){
  58391. sqlite3DbFree(db, zErr);
  58392. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  58393. rc = SQLITE_ERROR;
  58394. sqlite3BtreeLeaveAll(db);
  58395. goto blob_open_out;
  58396. }
  58397. }
  58398. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  58399. assert( pBlob->pStmt || db->mallocFailed );
  58400. if( pBlob->pStmt ){
  58401. Vdbe *v = (Vdbe *)pBlob->pStmt;
  58402. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  58403. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  58404. /* Configure the OP_Transaction */
  58405. sqlite3VdbeChangeP1(v, 0, iDb);
  58406. sqlite3VdbeChangeP2(v, 0, flags);
  58407. /* Configure the OP_VerifyCookie */
  58408. sqlite3VdbeChangeP1(v, 1, iDb);
  58409. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  58410. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  58411. /* Make sure a mutex is held on the table to be accessed */
  58412. sqlite3VdbeUsesBtree(v, iDb);
  58413. /* Configure the OP_TableLock instruction */
  58414. #ifdef SQLITE_OMIT_SHARED_CACHE
  58415. sqlite3VdbeChangeToNoop(v, 2);
  58416. #else
  58417. sqlite3VdbeChangeP1(v, 2, iDb);
  58418. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  58419. sqlite3VdbeChangeP3(v, 2, flags);
  58420. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  58421. #endif
  58422. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  58423. ** parameter of the other to pTab->tnum. */
  58424. sqlite3VdbeChangeToNoop(v, 4 - flags);
  58425. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  58426. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  58427. /* Configure the number of columns. Configure the cursor to
  58428. ** think that the table has one more column than it really
  58429. ** does. An OP_Column to retrieve this imaginary column will
  58430. ** always return an SQL NULL. This is useful because it means
  58431. ** we can invoke OP_Column to fill in the vdbe cursors type
  58432. ** and offset cache without causing any IO.
  58433. */
  58434. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  58435. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  58436. if( !db->mallocFailed ){
  58437. pParse->nVar = 1;
  58438. pParse->nMem = 1;
  58439. pParse->nTab = 1;
  58440. sqlite3VdbeMakeReady(v, pParse);
  58441. }
  58442. }
  58443. pBlob->flags = flags;
  58444. pBlob->iCol = iCol;
  58445. pBlob->db = db;
  58446. sqlite3BtreeLeaveAll(db);
  58447. if( db->mallocFailed ){
  58448. goto blob_open_out;
  58449. }
  58450. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  58451. rc = blobSeekToRow(pBlob, iRow, &zErr);
  58452. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  58453. blob_open_out:
  58454. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  58455. *ppBlob = (sqlite3_blob *)pBlob;
  58456. }else{
  58457. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  58458. sqlite3DbFree(db, pBlob);
  58459. }
  58460. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  58461. sqlite3DbFree(db, zErr);
  58462. sqlite3StackFree(db, pParse);
  58463. rc = sqlite3ApiExit(db, rc);
  58464. sqlite3_mutex_leave(db->mutex);
  58465. return rc;
  58466. }
  58467. /*
  58468. ** Close a blob handle that was previously created using
  58469. ** sqlite3_blob_open().
  58470. */
  58471. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  58472. Incrblob *p = (Incrblob *)pBlob;
  58473. int rc;
  58474. sqlite3 *db;
  58475. if( p ){
  58476. db = p->db;
  58477. sqlite3_mutex_enter(db->mutex);
  58478. rc = sqlite3_finalize(p->pStmt);
  58479. sqlite3DbFree(db, p);
  58480. sqlite3_mutex_leave(db->mutex);
  58481. }else{
  58482. rc = SQLITE_OK;
  58483. }
  58484. return rc;
  58485. }
  58486. /*
  58487. ** Perform a read or write operation on a blob
  58488. */
  58489. static int blobReadWrite(
  58490. sqlite3_blob *pBlob,
  58491. void *z,
  58492. int n,
  58493. int iOffset,
  58494. int (*xCall)(BtCursor*, u32, u32, void*)
  58495. ){
  58496. int rc;
  58497. Incrblob *p = (Incrblob *)pBlob;
  58498. Vdbe *v;
  58499. sqlite3 *db;
  58500. if( p==0 ) return SQLITE_MISUSE_BKPT;
  58501. db = p->db;
  58502. sqlite3_mutex_enter(db->mutex);
  58503. v = (Vdbe*)p->pStmt;
  58504. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  58505. /* Request is out of range. Return a transient error. */
  58506. rc = SQLITE_ERROR;
  58507. sqlite3Error(db, SQLITE_ERROR, 0);
  58508. }else if( v==0 ){
  58509. /* If there is no statement handle, then the blob-handle has
  58510. ** already been invalidated. Return SQLITE_ABORT in this case.
  58511. */
  58512. rc = SQLITE_ABORT;
  58513. }else{
  58514. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  58515. ** returned, clean-up the statement handle.
  58516. */
  58517. assert( db == v->db );
  58518. sqlite3BtreeEnterCursor(p->pCsr);
  58519. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  58520. sqlite3BtreeLeaveCursor(p->pCsr);
  58521. if( rc==SQLITE_ABORT ){
  58522. sqlite3VdbeFinalize(v);
  58523. p->pStmt = 0;
  58524. }else{
  58525. db->errCode = rc;
  58526. v->rc = rc;
  58527. }
  58528. }
  58529. rc = sqlite3ApiExit(db, rc);
  58530. sqlite3_mutex_leave(db->mutex);
  58531. return rc;
  58532. }
  58533. /*
  58534. ** Read data from a blob handle.
  58535. */
  58536. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  58537. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  58538. }
  58539. /*
  58540. ** Write data to a blob handle.
  58541. */
  58542. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  58543. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  58544. }
  58545. /*
  58546. ** Query a blob handle for the size of the data.
  58547. **
  58548. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  58549. ** so no mutex is required for access.
  58550. */
  58551. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  58552. Incrblob *p = (Incrblob *)pBlob;
  58553. return (p && p->pStmt) ? p->nByte : 0;
  58554. }
  58555. /*
  58556. ** Move an existing blob handle to point to a different row of the same
  58557. ** database table.
  58558. **
  58559. ** If an error occurs, or if the specified row does not exist or does not
  58560. ** contain a blob or text value, then an error code is returned and the
  58561. ** database handle error code and message set. If this happens, then all
  58562. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  58563. ** immediately return SQLITE_ABORT.
  58564. */
  58565. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  58566. int rc;
  58567. Incrblob *p = (Incrblob *)pBlob;
  58568. sqlite3 *db;
  58569. if( p==0 ) return SQLITE_MISUSE_BKPT;
  58570. db = p->db;
  58571. sqlite3_mutex_enter(db->mutex);
  58572. if( p->pStmt==0 ){
  58573. /* If there is no statement handle, then the blob-handle has
  58574. ** already been invalidated. Return SQLITE_ABORT in this case.
  58575. */
  58576. rc = SQLITE_ABORT;
  58577. }else{
  58578. char *zErr;
  58579. rc = blobSeekToRow(p, iRow, &zErr);
  58580. if( rc!=SQLITE_OK ){
  58581. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  58582. sqlite3DbFree(db, zErr);
  58583. }
  58584. assert( rc!=SQLITE_SCHEMA );
  58585. }
  58586. rc = sqlite3ApiExit(db, rc);
  58587. assert( rc==SQLITE_OK || p->pStmt==0 );
  58588. sqlite3_mutex_leave(db->mutex);
  58589. return rc;
  58590. }
  58591. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  58592. /************** End of vdbeblob.c ********************************************/
  58593. /************** Begin file vdbesort.c ****************************************/
  58594. /*
  58595. ** 2011 July 9
  58596. **
  58597. ** The author disclaims copyright to this source code. In place of
  58598. ** a legal notice, here is a blessing:
  58599. **
  58600. ** May you do good and not evil.
  58601. ** May you find forgiveness for yourself and forgive others.
  58602. ** May you share freely, never taking more than you give.
  58603. **
  58604. *************************************************************************
  58605. ** This file contains code for the VdbeSorter object, used in concert with
  58606. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  58607. ** example, by CREATE INDEX statements on tables too large to fit in main
  58608. ** memory).
  58609. */
  58610. typedef struct VdbeSorterIter VdbeSorterIter;
  58611. typedef struct SorterRecord SorterRecord;
  58612. typedef struct FileWriter FileWriter;
  58613. /*
  58614. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  58615. **
  58616. ** As keys are added to the sorter, they are written to disk in a series
  58617. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  58618. ** the same as the cache-size allowed for temporary databases. In order
  58619. ** to allow the caller to extract keys from the sorter in sorted order,
  58620. ** all PMAs currently stored on disk must be merged together. This comment
  58621. ** describes the data structure used to do so. The structure supports
  58622. ** merging any number of arrays in a single pass with no redundant comparison
  58623. ** operations.
  58624. **
  58625. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  58626. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  58627. ** the purposes of the paragraphs below, we assume that the array is actually
  58628. ** N elements in size, where N is the smallest power of 2 greater to or equal
  58629. ** to the number of iterators being merged. The extra aIter[] elements are
  58630. ** treated as if they are empty (always at EOF).
  58631. **
  58632. ** The aTree[] array is also N elements in size. The value of N is stored in
  58633. ** the VdbeSorter.nTree variable.
  58634. **
  58635. ** The final (N/2) elements of aTree[] contain the results of comparing
  58636. ** pairs of iterator keys together. Element i contains the result of
  58637. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  58638. ** aTree element is set to the index of it.
  58639. **
  58640. ** For the purposes of this comparison, EOF is considered greater than any
  58641. ** other key value. If the keys are equal (only possible with two EOF
  58642. ** values), it doesn't matter which index is stored.
  58643. **
  58644. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  58645. ** above contains the index of the smallest of each block of 4 iterators.
  58646. ** And so on. So that aTree[1] contains the index of the iterator that
  58647. ** currently points to the smallest key value. aTree[0] is unused.
  58648. **
  58649. ** Example:
  58650. **
  58651. ** aIter[0] -> Banana
  58652. ** aIter[1] -> Feijoa
  58653. ** aIter[2] -> Elderberry
  58654. ** aIter[3] -> Currant
  58655. ** aIter[4] -> Grapefruit
  58656. ** aIter[5] -> Apple
  58657. ** aIter[6] -> Durian
  58658. ** aIter[7] -> EOF
  58659. **
  58660. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  58661. **
  58662. ** The current element is "Apple" (the value of the key indicated by
  58663. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  58664. ** be advanced to the next key in its segment. Say the next key is
  58665. ** "Eggplant":
  58666. **
  58667. ** aIter[5] -> Eggplant
  58668. **
  58669. ** The contents of aTree[] are updated first by comparing the new iterator
  58670. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  58671. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  58672. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  58673. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  58674. ** so the value written into element 1 of the array is 0. As follows:
  58675. **
  58676. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  58677. **
  58678. ** In other words, each time we advance to the next sorter element, log2(N)
  58679. ** key comparison operations are required, where N is the number of segments
  58680. ** being merged (rounded up to the next power of 2).
  58681. */
  58682. struct VdbeSorter {
  58683. i64 iWriteOff; /* Current write offset within file pTemp1 */
  58684. i64 iReadOff; /* Current read offset within file pTemp1 */
  58685. int nInMemory; /* Current size of pRecord list as PMA */
  58686. int nTree; /* Used size of aTree/aIter (power of 2) */
  58687. int nPMA; /* Number of PMAs stored in pTemp1 */
  58688. int mnPmaSize; /* Minimum PMA size, in bytes */
  58689. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  58690. VdbeSorterIter *aIter; /* Array of iterators to merge */
  58691. int *aTree; /* Current state of incremental merge */
  58692. sqlite3_file *pTemp1; /* PMA file 1 */
  58693. SorterRecord *pRecord; /* Head of in-memory record list */
  58694. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  58695. };
  58696. /*
  58697. ** The following type is an iterator for a PMA. It caches the current key in
  58698. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  58699. */
  58700. struct VdbeSorterIter {
  58701. i64 iReadOff; /* Current read offset */
  58702. i64 iEof; /* 1 byte past EOF for this iterator */
  58703. int nAlloc; /* Bytes of space at aAlloc */
  58704. int nKey; /* Number of bytes in key */
  58705. sqlite3_file *pFile; /* File iterator is reading from */
  58706. u8 *aAlloc; /* Allocated space */
  58707. u8 *aKey; /* Pointer to current key */
  58708. u8 *aBuffer; /* Current read buffer */
  58709. int nBuffer; /* Size of read buffer in bytes */
  58710. };
  58711. /*
  58712. ** An instance of this structure is used to organize the stream of records
  58713. ** being written to files by the merge-sort code into aligned, page-sized
  58714. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  58715. ** faster on many operating systems.
  58716. */
  58717. struct FileWriter {
  58718. int eFWErr; /* Non-zero if in an error state */
  58719. u8 *aBuffer; /* Pointer to write buffer */
  58720. int nBuffer; /* Size of write buffer in bytes */
  58721. int iBufStart; /* First byte of buffer to write */
  58722. int iBufEnd; /* Last byte of buffer to write */
  58723. i64 iWriteOff; /* Offset of start of buffer in file */
  58724. sqlite3_file *pFile; /* File to write to */
  58725. };
  58726. /*
  58727. ** A structure to store a single record. All in-memory records are connected
  58728. ** together into a linked list headed at VdbeSorter.pRecord using the
  58729. ** SorterRecord.pNext pointer.
  58730. */
  58731. struct SorterRecord {
  58732. void *pVal;
  58733. int nVal;
  58734. SorterRecord *pNext;
  58735. };
  58736. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  58737. #define SORTER_MIN_WORKING 10
  58738. /* Maximum number of segments to merge in a single pass. */
  58739. #define SORTER_MAX_MERGE_COUNT 16
  58740. /*
  58741. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  58742. ** argument. All structure fields are set to zero before returning.
  58743. */
  58744. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  58745. sqlite3DbFree(db, pIter->aAlloc);
  58746. sqlite3DbFree(db, pIter->aBuffer);
  58747. memset(pIter, 0, sizeof(VdbeSorterIter));
  58748. }
  58749. /*
  58750. ** Read nByte bytes of data from the stream of data iterated by object p.
  58751. ** If successful, set *ppOut to point to a buffer containing the data
  58752. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  58753. ** error code.
  58754. **
  58755. ** The buffer indicated by *ppOut may only be considered valid until the
  58756. ** next call to this function.
  58757. */
  58758. static int vdbeSorterIterRead(
  58759. sqlite3 *db, /* Database handle (for malloc) */
  58760. VdbeSorterIter *p, /* Iterator */
  58761. int nByte, /* Bytes of data to read */
  58762. u8 **ppOut /* OUT: Pointer to buffer containing data */
  58763. ){
  58764. int iBuf; /* Offset within buffer to read from */
  58765. int nAvail; /* Bytes of data available in buffer */
  58766. assert( p->aBuffer );
  58767. /* If there is no more data to be read from the buffer, read the next
  58768. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  58769. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  58770. iBuf = p->iReadOff % p->nBuffer;
  58771. if( iBuf==0 ){
  58772. int nRead; /* Bytes to read from disk */
  58773. int rc; /* sqlite3OsRead() return code */
  58774. /* Determine how many bytes of data to read. */
  58775. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  58776. nRead = p->nBuffer;
  58777. }else{
  58778. nRead = (int)(p->iEof - p->iReadOff);
  58779. }
  58780. assert( nRead>0 );
  58781. /* Read data from the file. Return early if an error occurs. */
  58782. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  58783. assert( rc!=SQLITE_IOERR_SHORT_READ );
  58784. if( rc!=SQLITE_OK ) return rc;
  58785. }
  58786. nAvail = p->nBuffer - iBuf;
  58787. if( nByte<=nAvail ){
  58788. /* The requested data is available in the in-memory buffer. In this
  58789. ** case there is no need to make a copy of the data, just return a
  58790. ** pointer into the buffer to the caller. */
  58791. *ppOut = &p->aBuffer[iBuf];
  58792. p->iReadOff += nByte;
  58793. }else{
  58794. /* The requested data is not all available in the in-memory buffer.
  58795. ** In this case, allocate space at p->aAlloc[] to copy the requested
  58796. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  58797. int nRem; /* Bytes remaining to copy */
  58798. /* Extend the p->aAlloc[] allocation if required. */
  58799. if( p->nAlloc<nByte ){
  58800. int nNew = p->nAlloc*2;
  58801. while( nByte>nNew ) nNew = nNew*2;
  58802. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  58803. if( !p->aAlloc ) return SQLITE_NOMEM;
  58804. p->nAlloc = nNew;
  58805. }
  58806. /* Copy as much data as is available in the buffer into the start of
  58807. ** p->aAlloc[]. */
  58808. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  58809. p->iReadOff += nAvail;
  58810. nRem = nByte - nAvail;
  58811. /* The following loop copies up to p->nBuffer bytes per iteration into
  58812. ** the p->aAlloc[] buffer. */
  58813. while( nRem>0 ){
  58814. int rc; /* vdbeSorterIterRead() return code */
  58815. int nCopy; /* Number of bytes to copy */
  58816. u8 *aNext; /* Pointer to buffer to copy data from */
  58817. nCopy = nRem;
  58818. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  58819. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  58820. if( rc!=SQLITE_OK ) return rc;
  58821. assert( aNext!=p->aAlloc );
  58822. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  58823. nRem -= nCopy;
  58824. }
  58825. *ppOut = p->aAlloc;
  58826. }
  58827. return SQLITE_OK;
  58828. }
  58829. /*
  58830. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  58831. ** the value read.
  58832. */
  58833. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  58834. int iBuf;
  58835. iBuf = p->iReadOff % p->nBuffer;
  58836. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  58837. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  58838. }else{
  58839. u8 aVarint[16], *a;
  58840. int i = 0, rc;
  58841. do{
  58842. rc = vdbeSorterIterRead(db, p, 1, &a);
  58843. if( rc ) return rc;
  58844. aVarint[(i++)&0xf] = a[0];
  58845. }while( (a[0]&0x80)!=0 );
  58846. sqlite3GetVarint(aVarint, pnOut);
  58847. }
  58848. return SQLITE_OK;
  58849. }
  58850. /*
  58851. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  58852. ** no error occurs, or an SQLite error code if one does.
  58853. */
  58854. static int vdbeSorterIterNext(
  58855. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  58856. VdbeSorterIter *pIter /* Iterator to advance */
  58857. ){
  58858. int rc; /* Return Code */
  58859. u64 nRec = 0; /* Size of record in bytes */
  58860. if( pIter->iReadOff>=pIter->iEof ){
  58861. /* This is an EOF condition */
  58862. vdbeSorterIterZero(db, pIter);
  58863. return SQLITE_OK;
  58864. }
  58865. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  58866. if( rc==SQLITE_OK ){
  58867. pIter->nKey = (int)nRec;
  58868. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  58869. }
  58870. return rc;
  58871. }
  58872. /*
  58873. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  58874. ** starting at offset iStart and ending at offset iEof-1. This function
  58875. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  58876. ** PMA is empty).
  58877. */
  58878. static int vdbeSorterIterInit(
  58879. sqlite3 *db, /* Database handle */
  58880. const VdbeSorter *pSorter, /* Sorter object */
  58881. i64 iStart, /* Start offset in pFile */
  58882. VdbeSorterIter *pIter, /* Iterator to populate */
  58883. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  58884. ){
  58885. int rc = SQLITE_OK;
  58886. int nBuf;
  58887. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  58888. assert( pSorter->iWriteOff>iStart );
  58889. assert( pIter->aAlloc==0 );
  58890. assert( pIter->aBuffer==0 );
  58891. pIter->pFile = pSorter->pTemp1;
  58892. pIter->iReadOff = iStart;
  58893. pIter->nAlloc = 128;
  58894. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  58895. pIter->nBuffer = nBuf;
  58896. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  58897. if( !pIter->aBuffer ){
  58898. rc = SQLITE_NOMEM;
  58899. }else{
  58900. int iBuf;
  58901. iBuf = iStart % nBuf;
  58902. if( iBuf ){
  58903. int nRead = nBuf - iBuf;
  58904. if( (iStart + nRead) > pSorter->iWriteOff ){
  58905. nRead = (int)(pSorter->iWriteOff - iStart);
  58906. }
  58907. rc = sqlite3OsRead(
  58908. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  58909. );
  58910. assert( rc!=SQLITE_IOERR_SHORT_READ );
  58911. }
  58912. if( rc==SQLITE_OK ){
  58913. u64 nByte; /* Size of PMA in bytes */
  58914. pIter->iEof = pSorter->iWriteOff;
  58915. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  58916. pIter->iEof = pIter->iReadOff + nByte;
  58917. *pnByte += nByte;
  58918. }
  58919. }
  58920. if( rc==SQLITE_OK ){
  58921. rc = vdbeSorterIterNext(db, pIter);
  58922. }
  58923. return rc;
  58924. }
  58925. /*
  58926. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  58927. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  58928. ** used by the comparison. If an error occurs, return an SQLite error code.
  58929. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  58930. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  58931. **
  58932. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  58933. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  58934. ** is true and key1 contains even a single NULL value, it is considered to
  58935. ** be less than key2. Even if key2 also contains NULL values.
  58936. **
  58937. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  58938. ** has been allocated and contains an unpacked record that is used as key2.
  58939. */
  58940. static void vdbeSorterCompare(
  58941. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  58942. int bOmitRowid, /* Ignore rowid field at end of keys */
  58943. const void *pKey1, int nKey1, /* Left side of comparison */
  58944. const void *pKey2, int nKey2, /* Right side of comparison */
  58945. int *pRes /* OUT: Result of comparison */
  58946. ){
  58947. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  58948. VdbeSorter *pSorter = pCsr->pSorter;
  58949. UnpackedRecord *r2 = pSorter->pUnpacked;
  58950. int i;
  58951. if( pKey2 ){
  58952. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  58953. }
  58954. if( bOmitRowid ){
  58955. r2->nField = pKeyInfo->nField;
  58956. assert( r2->nField>0 );
  58957. for(i=0; i<r2->nField; i++){
  58958. if( r2->aMem[i].flags & MEM_Null ){
  58959. *pRes = -1;
  58960. return;
  58961. }
  58962. }
  58963. r2->flags |= UNPACKED_PREFIX_MATCH;
  58964. }
  58965. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  58966. }
  58967. /*
  58968. ** This function is called to compare two iterator keys when merging
  58969. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  58970. ** value to recalculate.
  58971. */
  58972. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  58973. VdbeSorter *pSorter = pCsr->pSorter;
  58974. int i1;
  58975. int i2;
  58976. int iRes;
  58977. VdbeSorterIter *p1;
  58978. VdbeSorterIter *p2;
  58979. assert( iOut<pSorter->nTree && iOut>0 );
  58980. if( iOut>=(pSorter->nTree/2) ){
  58981. i1 = (iOut - pSorter->nTree/2) * 2;
  58982. i2 = i1 + 1;
  58983. }else{
  58984. i1 = pSorter->aTree[iOut*2];
  58985. i2 = pSorter->aTree[iOut*2+1];
  58986. }
  58987. p1 = &pSorter->aIter[i1];
  58988. p2 = &pSorter->aIter[i2];
  58989. if( p1->pFile==0 ){
  58990. iRes = i2;
  58991. }else if( p2->pFile==0 ){
  58992. iRes = i1;
  58993. }else{
  58994. int res;
  58995. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  58996. vdbeSorterCompare(
  58997. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  58998. );
  58999. if( res<=0 ){
  59000. iRes = i1;
  59001. }else{
  59002. iRes = i2;
  59003. }
  59004. }
  59005. pSorter->aTree[iOut] = iRes;
  59006. return SQLITE_OK;
  59007. }
  59008. /*
  59009. ** Initialize the temporary index cursor just opened as a sorter cursor.
  59010. */
  59011. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  59012. int pgsz; /* Page size of main database */
  59013. int mxCache; /* Cache size */
  59014. VdbeSorter *pSorter; /* The new sorter */
  59015. char *d; /* Dummy */
  59016. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  59017. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  59018. if( pSorter==0 ){
  59019. return SQLITE_NOMEM;
  59020. }
  59021. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  59022. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  59023. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  59024. if( !sqlite3TempInMemory(db) ){
  59025. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  59026. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  59027. mxCache = db->aDb[0].pSchema->cache_size;
  59028. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  59029. pSorter->mxPmaSize = mxCache * pgsz;
  59030. }
  59031. return SQLITE_OK;
  59032. }
  59033. /*
  59034. ** Free the list of sorted records starting at pRecord.
  59035. */
  59036. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  59037. SorterRecord *p;
  59038. SorterRecord *pNext;
  59039. for(p=pRecord; p; p=pNext){
  59040. pNext = p->pNext;
  59041. sqlite3DbFree(db, p);
  59042. }
  59043. }
  59044. /*
  59045. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  59046. */
  59047. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  59048. VdbeSorter *pSorter = pCsr->pSorter;
  59049. if( pSorter ){
  59050. if( pSorter->aIter ){
  59051. int i;
  59052. for(i=0; i<pSorter->nTree; i++){
  59053. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  59054. }
  59055. sqlite3DbFree(db, pSorter->aIter);
  59056. }
  59057. if( pSorter->pTemp1 ){
  59058. sqlite3OsCloseFree(pSorter->pTemp1);
  59059. }
  59060. vdbeSorterRecordFree(db, pSorter->pRecord);
  59061. sqlite3DbFree(db, pSorter->pUnpacked);
  59062. sqlite3DbFree(db, pSorter);
  59063. pCsr->pSorter = 0;
  59064. }
  59065. }
  59066. /*
  59067. ** Allocate space for a file-handle and open a temporary file. If successful,
  59068. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  59069. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  59070. */
  59071. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  59072. int dummy;
  59073. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  59074. SQLITE_OPEN_TEMP_JOURNAL |
  59075. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  59076. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  59077. );
  59078. }
  59079. /*
  59080. ** Merge the two sorted lists p1 and p2 into a single list.
  59081. ** Set *ppOut to the head of the new list.
  59082. */
  59083. static void vdbeSorterMerge(
  59084. const VdbeCursor *pCsr, /* For pKeyInfo */
  59085. SorterRecord *p1, /* First list to merge */
  59086. SorterRecord *p2, /* Second list to merge */
  59087. SorterRecord **ppOut /* OUT: Head of merged list */
  59088. ){
  59089. SorterRecord *pFinal = 0;
  59090. SorterRecord **pp = &pFinal;
  59091. void *pVal2 = p2 ? p2->pVal : 0;
  59092. while( p1 && p2 ){
  59093. int res;
  59094. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  59095. if( res<=0 ){
  59096. *pp = p1;
  59097. pp = &p1->pNext;
  59098. p1 = p1->pNext;
  59099. pVal2 = 0;
  59100. }else{
  59101. *pp = p2;
  59102. pp = &p2->pNext;
  59103. p2 = p2->pNext;
  59104. if( p2==0 ) break;
  59105. pVal2 = p2->pVal;
  59106. }
  59107. }
  59108. *pp = p1 ? p1 : p2;
  59109. *ppOut = pFinal;
  59110. }
  59111. /*
  59112. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  59113. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  59114. ** occurs.
  59115. */
  59116. static int vdbeSorterSort(const VdbeCursor *pCsr){
  59117. int i;
  59118. SorterRecord **aSlot;
  59119. SorterRecord *p;
  59120. VdbeSorter *pSorter = pCsr->pSorter;
  59121. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  59122. if( !aSlot ){
  59123. return SQLITE_NOMEM;
  59124. }
  59125. p = pSorter->pRecord;
  59126. while( p ){
  59127. SorterRecord *pNext = p->pNext;
  59128. p->pNext = 0;
  59129. for(i=0; aSlot[i]; i++){
  59130. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  59131. aSlot[i] = 0;
  59132. }
  59133. aSlot[i] = p;
  59134. p = pNext;
  59135. }
  59136. p = 0;
  59137. for(i=0; i<64; i++){
  59138. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  59139. }
  59140. pSorter->pRecord = p;
  59141. sqlite3_free(aSlot);
  59142. return SQLITE_OK;
  59143. }
  59144. /*
  59145. ** Initialize a file-writer object.
  59146. */
  59147. static void fileWriterInit(
  59148. sqlite3 *db, /* Database (for malloc) */
  59149. sqlite3_file *pFile, /* File to write to */
  59150. FileWriter *p, /* Object to populate */
  59151. i64 iStart /* Offset of pFile to begin writing at */
  59152. ){
  59153. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  59154. memset(p, 0, sizeof(FileWriter));
  59155. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  59156. if( !p->aBuffer ){
  59157. p->eFWErr = SQLITE_NOMEM;
  59158. }else{
  59159. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  59160. p->iWriteOff = iStart - p->iBufStart;
  59161. p->nBuffer = nBuf;
  59162. p->pFile = pFile;
  59163. }
  59164. }
  59165. /*
  59166. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  59167. ** if successful, or an SQLite error code if an error occurs.
  59168. */
  59169. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  59170. int nRem = nData;
  59171. while( nRem>0 && p->eFWErr==0 ){
  59172. int nCopy = nRem;
  59173. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  59174. nCopy = p->nBuffer - p->iBufEnd;
  59175. }
  59176. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  59177. p->iBufEnd += nCopy;
  59178. if( p->iBufEnd==p->nBuffer ){
  59179. p->eFWErr = sqlite3OsWrite(p->pFile,
  59180. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  59181. p->iWriteOff + p->iBufStart
  59182. );
  59183. p->iBufStart = p->iBufEnd = 0;
  59184. p->iWriteOff += p->nBuffer;
  59185. }
  59186. assert( p->iBufEnd<p->nBuffer );
  59187. nRem -= nCopy;
  59188. }
  59189. }
  59190. /*
  59191. ** Flush any buffered data to disk and clean up the file-writer object.
  59192. ** The results of using the file-writer after this call are undefined.
  59193. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  59194. ** required. Otherwise, return an SQLite error code.
  59195. **
  59196. ** Before returning, set *piEof to the offset immediately following the
  59197. ** last byte written to the file.
  59198. */
  59199. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  59200. int rc;
  59201. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  59202. p->eFWErr = sqlite3OsWrite(p->pFile,
  59203. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  59204. p->iWriteOff + p->iBufStart
  59205. );
  59206. }
  59207. *piEof = (p->iWriteOff + p->iBufEnd);
  59208. sqlite3DbFree(db, p->aBuffer);
  59209. rc = p->eFWErr;
  59210. memset(p, 0, sizeof(FileWriter));
  59211. return rc;
  59212. }
  59213. /*
  59214. ** Write value iVal encoded as a varint to the file-write object. Return
  59215. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  59216. */
  59217. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  59218. int nByte;
  59219. u8 aByte[10];
  59220. nByte = sqlite3PutVarint(aByte, iVal);
  59221. fileWriterWrite(p, aByte, nByte);
  59222. }
  59223. /*
  59224. ** Write the current contents of the in-memory linked-list to a PMA. Return
  59225. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  59226. **
  59227. ** The format of a PMA is:
  59228. **
  59229. ** * A varint. This varint contains the total number of bytes of content
  59230. ** in the PMA (not including the varint itself).
  59231. **
  59232. ** * One or more records packed end-to-end in order of ascending keys.
  59233. ** Each record consists of a varint followed by a blob of data (the
  59234. ** key). The varint is the number of bytes in the blob of data.
  59235. */
  59236. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  59237. int rc = SQLITE_OK; /* Return code */
  59238. VdbeSorter *pSorter = pCsr->pSorter;
  59239. FileWriter writer;
  59240. memset(&writer, 0, sizeof(FileWriter));
  59241. if( pSorter->nInMemory==0 ){
  59242. assert( pSorter->pRecord==0 );
  59243. return rc;
  59244. }
  59245. rc = vdbeSorterSort(pCsr);
  59246. /* If the first temporary PMA file has not been opened, open it now. */
  59247. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  59248. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  59249. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  59250. assert( pSorter->iWriteOff==0 );
  59251. assert( pSorter->nPMA==0 );
  59252. }
  59253. if( rc==SQLITE_OK ){
  59254. SorterRecord *p;
  59255. SorterRecord *pNext = 0;
  59256. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  59257. pSorter->nPMA++;
  59258. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  59259. for(p=pSorter->pRecord; p; p=pNext){
  59260. pNext = p->pNext;
  59261. fileWriterWriteVarint(&writer, p->nVal);
  59262. fileWriterWrite(&writer, p->pVal, p->nVal);
  59263. sqlite3DbFree(db, p);
  59264. }
  59265. pSorter->pRecord = p;
  59266. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  59267. }
  59268. return rc;
  59269. }
  59270. /*
  59271. ** Add a record to the sorter.
  59272. */
  59273. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  59274. sqlite3 *db, /* Database handle */
  59275. const VdbeCursor *pCsr, /* Sorter cursor */
  59276. Mem *pVal /* Memory cell containing record */
  59277. ){
  59278. VdbeSorter *pSorter = pCsr->pSorter;
  59279. int rc = SQLITE_OK; /* Return Code */
  59280. SorterRecord *pNew; /* New list element */
  59281. assert( pSorter );
  59282. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  59283. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  59284. if( pNew==0 ){
  59285. rc = SQLITE_NOMEM;
  59286. }else{
  59287. pNew->pVal = (void *)&pNew[1];
  59288. memcpy(pNew->pVal, pVal->z, pVal->n);
  59289. pNew->nVal = pVal->n;
  59290. pNew->pNext = pSorter->pRecord;
  59291. pSorter->pRecord = pNew;
  59292. }
  59293. /* See if the contents of the sorter should now be written out. They
  59294. ** are written out when either of the following are true:
  59295. **
  59296. ** * The total memory allocated for the in-memory list is greater
  59297. ** than (page-size * cache-size), or
  59298. **
  59299. ** * The total memory allocated for the in-memory list is greater
  59300. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  59301. */
  59302. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  59303. (pSorter->nInMemory>pSorter->mxPmaSize)
  59304. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  59305. )){
  59306. #ifdef SQLITE_DEBUG
  59307. i64 nExpect = pSorter->iWriteOff
  59308. + sqlite3VarintLen(pSorter->nInMemory)
  59309. + pSorter->nInMemory;
  59310. #endif
  59311. rc = vdbeSorterListToPMA(db, pCsr);
  59312. pSorter->nInMemory = 0;
  59313. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  59314. }
  59315. return rc;
  59316. }
  59317. /*
  59318. ** Helper function for sqlite3VdbeSorterRewind().
  59319. */
  59320. static int vdbeSorterInitMerge(
  59321. sqlite3 *db, /* Database handle */
  59322. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  59323. i64 *pnByte /* Sum of bytes in all opened PMAs */
  59324. ){
  59325. VdbeSorter *pSorter = pCsr->pSorter;
  59326. int rc = SQLITE_OK; /* Return code */
  59327. int i; /* Used to iterator through aIter[] */
  59328. i64 nByte = 0; /* Total bytes in all opened PMAs */
  59329. /* Initialize the iterators. */
  59330. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  59331. VdbeSorterIter *pIter = &pSorter->aIter[i];
  59332. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  59333. pSorter->iReadOff = pIter->iEof;
  59334. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  59335. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  59336. }
  59337. /* Initialize the aTree[] array. */
  59338. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  59339. rc = vdbeSorterDoCompare(pCsr, i);
  59340. }
  59341. *pnByte = nByte;
  59342. return rc;
  59343. }
  59344. /*
  59345. ** Once the sorter has been populated, this function is called to prepare
  59346. ** for iterating through its contents in sorted order.
  59347. */
  59348. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  59349. VdbeSorter *pSorter = pCsr->pSorter;
  59350. int rc; /* Return code */
  59351. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  59352. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  59353. int nIter; /* Number of iterators used */
  59354. int nByte; /* Bytes of space required for aIter/aTree */
  59355. int N = 2; /* Power of 2 >= nIter */
  59356. assert( pSorter );
  59357. /* If no data has been written to disk, then do not do so now. Instead,
  59358. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  59359. ** from the in-memory list. */
  59360. if( pSorter->nPMA==0 ){
  59361. *pbEof = !pSorter->pRecord;
  59362. assert( pSorter->aTree==0 );
  59363. return vdbeSorterSort(pCsr);
  59364. }
  59365. /* Write the current in-memory list to a PMA. */
  59366. rc = vdbeSorterListToPMA(db, pCsr);
  59367. if( rc!=SQLITE_OK ) return rc;
  59368. /* Allocate space for aIter[] and aTree[]. */
  59369. nIter = pSorter->nPMA;
  59370. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  59371. assert( nIter>0 );
  59372. while( N<nIter ) N += N;
  59373. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  59374. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  59375. if( !pSorter->aIter ) return SQLITE_NOMEM;
  59376. pSorter->aTree = (int *)&pSorter->aIter[N];
  59377. pSorter->nTree = N;
  59378. do {
  59379. int iNew; /* Index of new, merged, PMA */
  59380. for(iNew=0;
  59381. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  59382. iNew++
  59383. ){
  59384. int rc2; /* Return code from fileWriterFinish() */
  59385. FileWriter writer; /* Object used to write to disk */
  59386. i64 nWrite; /* Number of bytes in new PMA */
  59387. memset(&writer, 0, sizeof(FileWriter));
  59388. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  59389. ** initialize an iterator for each of them and break out of the loop.
  59390. ** These iterators will be incrementally merged as the VDBE layer calls
  59391. ** sqlite3VdbeSorterNext().
  59392. **
  59393. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  59394. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  59395. ** are merged into a single PMA that is written to file pTemp2.
  59396. */
  59397. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  59398. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  59399. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  59400. break;
  59401. }
  59402. /* Open the second temp file, if it is not already open. */
  59403. if( pTemp2==0 ){
  59404. assert( iWrite2==0 );
  59405. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  59406. }
  59407. if( rc==SQLITE_OK ){
  59408. int bEof = 0;
  59409. fileWriterInit(db, pTemp2, &writer, iWrite2);
  59410. fileWriterWriteVarint(&writer, nWrite);
  59411. while( rc==SQLITE_OK && bEof==0 ){
  59412. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  59413. assert( pIter->pFile );
  59414. fileWriterWriteVarint(&writer, pIter->nKey);
  59415. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  59416. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  59417. }
  59418. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  59419. if( rc==SQLITE_OK ) rc = rc2;
  59420. }
  59421. }
  59422. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  59423. break;
  59424. }else{
  59425. sqlite3_file *pTmp = pSorter->pTemp1;
  59426. pSorter->nPMA = iNew;
  59427. pSorter->pTemp1 = pTemp2;
  59428. pTemp2 = pTmp;
  59429. pSorter->iWriteOff = iWrite2;
  59430. pSorter->iReadOff = 0;
  59431. iWrite2 = 0;
  59432. }
  59433. }while( rc==SQLITE_OK );
  59434. if( pTemp2 ){
  59435. sqlite3OsCloseFree(pTemp2);
  59436. }
  59437. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  59438. return rc;
  59439. }
  59440. /*
  59441. ** Advance to the next element in the sorter.
  59442. */
  59443. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  59444. VdbeSorter *pSorter = pCsr->pSorter;
  59445. int rc; /* Return code */
  59446. if( pSorter->aTree ){
  59447. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  59448. int i; /* Index of aTree[] to recalculate */
  59449. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  59450. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  59451. rc = vdbeSorterDoCompare(pCsr, i);
  59452. }
  59453. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  59454. }else{
  59455. SorterRecord *pFree = pSorter->pRecord;
  59456. pSorter->pRecord = pFree->pNext;
  59457. pFree->pNext = 0;
  59458. vdbeSorterRecordFree(db, pFree);
  59459. *pbEof = !pSorter->pRecord;
  59460. rc = SQLITE_OK;
  59461. }
  59462. return rc;
  59463. }
  59464. /*
  59465. ** Return a pointer to a buffer owned by the sorter that contains the
  59466. ** current key.
  59467. */
  59468. static void *vdbeSorterRowkey(
  59469. const VdbeSorter *pSorter, /* Sorter object */
  59470. int *pnKey /* OUT: Size of current key in bytes */
  59471. ){
  59472. void *pKey;
  59473. if( pSorter->aTree ){
  59474. VdbeSorterIter *pIter;
  59475. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  59476. *pnKey = pIter->nKey;
  59477. pKey = pIter->aKey;
  59478. }else{
  59479. *pnKey = pSorter->pRecord->nVal;
  59480. pKey = pSorter->pRecord->pVal;
  59481. }
  59482. return pKey;
  59483. }
  59484. /*
  59485. ** Copy the current sorter key into the memory cell pOut.
  59486. */
  59487. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  59488. VdbeSorter *pSorter = pCsr->pSorter;
  59489. void *pKey; int nKey; /* Sorter key to copy into pOut */
  59490. pKey = vdbeSorterRowkey(pSorter, &nKey);
  59491. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  59492. return SQLITE_NOMEM;
  59493. }
  59494. pOut->n = nKey;
  59495. MemSetTypeFlag(pOut, MEM_Blob);
  59496. memcpy(pOut->z, pKey, nKey);
  59497. return SQLITE_OK;
  59498. }
  59499. /*
  59500. ** Compare the key in memory cell pVal with the key that the sorter cursor
  59501. ** passed as the first argument currently points to. For the purposes of
  59502. ** the comparison, ignore the rowid field at the end of each record.
  59503. **
  59504. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  59505. ** Otherwise, set *pRes to a negative, zero or positive value if the
  59506. ** key in pVal is smaller than, equal to or larger than the current sorter
  59507. ** key.
  59508. */
  59509. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  59510. const VdbeCursor *pCsr, /* Sorter cursor */
  59511. Mem *pVal, /* Value to compare to current sorter key */
  59512. int *pRes /* OUT: Result of comparison */
  59513. ){
  59514. VdbeSorter *pSorter = pCsr->pSorter;
  59515. void *pKey; int nKey; /* Sorter key to compare pVal with */
  59516. pKey = vdbeSorterRowkey(pSorter, &nKey);
  59517. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  59518. return SQLITE_OK;
  59519. }
  59520. /************** End of vdbesort.c ********************************************/
  59521. /************** Begin file journal.c *****************************************/
  59522. /*
  59523. ** 2007 August 22
  59524. **
  59525. ** The author disclaims copyright to this source code. In place of
  59526. ** a legal notice, here is a blessing:
  59527. **
  59528. ** May you do good and not evil.
  59529. ** May you find forgiveness for yourself and forgive others.
  59530. ** May you share freely, never taking more than you give.
  59531. **
  59532. *************************************************************************
  59533. **
  59534. ** This file implements a special kind of sqlite3_file object used
  59535. ** by SQLite to create journal files if the atomic-write optimization
  59536. ** is enabled.
  59537. **
  59538. ** The distinctive characteristic of this sqlite3_file is that the
  59539. ** actual on disk file is created lazily. When the file is created,
  59540. ** the caller specifies a buffer size for an in-memory buffer to
  59541. ** be used to service read() and write() requests. The actual file
  59542. ** on disk is not created or populated until either:
  59543. **
  59544. ** 1) The in-memory representation grows too large for the allocated
  59545. ** buffer, or
  59546. ** 2) The sqlite3JournalCreate() function is called.
  59547. */
  59548. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  59549. /*
  59550. ** A JournalFile object is a subclass of sqlite3_file used by
  59551. ** as an open file handle for journal files.
  59552. */
  59553. struct JournalFile {
  59554. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  59555. int nBuf; /* Size of zBuf[] in bytes */
  59556. char *zBuf; /* Space to buffer journal writes */
  59557. int iSize; /* Amount of zBuf[] currently used */
  59558. int flags; /* xOpen flags */
  59559. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  59560. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  59561. const char *zJournal; /* Name of the journal file */
  59562. };
  59563. typedef struct JournalFile JournalFile;
  59564. /*
  59565. ** If it does not already exists, create and populate the on-disk file
  59566. ** for JournalFile p.
  59567. */
  59568. static int createFile(JournalFile *p){
  59569. int rc = SQLITE_OK;
  59570. if( !p->pReal ){
  59571. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  59572. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  59573. if( rc==SQLITE_OK ){
  59574. p->pReal = pReal;
  59575. if( p->iSize>0 ){
  59576. assert(p->iSize<=p->nBuf);
  59577. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  59578. }
  59579. if( rc!=SQLITE_OK ){
  59580. /* If an error occurred while writing to the file, close it before
  59581. ** returning. This way, SQLite uses the in-memory journal data to
  59582. ** roll back changes made to the internal page-cache before this
  59583. ** function was called. */
  59584. sqlite3OsClose(pReal);
  59585. p->pReal = 0;
  59586. }
  59587. }
  59588. }
  59589. return rc;
  59590. }
  59591. /*
  59592. ** Close the file.
  59593. */
  59594. static int jrnlClose(sqlite3_file *pJfd){
  59595. JournalFile *p = (JournalFile *)pJfd;
  59596. if( p->pReal ){
  59597. sqlite3OsClose(p->pReal);
  59598. }
  59599. sqlite3_free(p->zBuf);
  59600. return SQLITE_OK;
  59601. }
  59602. /*
  59603. ** Read data from the file.
  59604. */
  59605. static int jrnlRead(
  59606. sqlite3_file *pJfd, /* The journal file from which to read */
  59607. void *zBuf, /* Put the results here */
  59608. int iAmt, /* Number of bytes to read */
  59609. sqlite_int64 iOfst /* Begin reading at this offset */
  59610. ){
  59611. int rc = SQLITE_OK;
  59612. JournalFile *p = (JournalFile *)pJfd;
  59613. if( p->pReal ){
  59614. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  59615. }else if( (iAmt+iOfst)>p->iSize ){
  59616. rc = SQLITE_IOERR_SHORT_READ;
  59617. }else{
  59618. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  59619. }
  59620. return rc;
  59621. }
  59622. /*
  59623. ** Write data to the file.
  59624. */
  59625. static int jrnlWrite(
  59626. sqlite3_file *pJfd, /* The journal file into which to write */
  59627. const void *zBuf, /* Take data to be written from here */
  59628. int iAmt, /* Number of bytes to write */
  59629. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  59630. ){
  59631. int rc = SQLITE_OK;
  59632. JournalFile *p = (JournalFile *)pJfd;
  59633. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  59634. rc = createFile(p);
  59635. }
  59636. if( rc==SQLITE_OK ){
  59637. if( p->pReal ){
  59638. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  59639. }else{
  59640. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  59641. if( p->iSize<(iOfst+iAmt) ){
  59642. p->iSize = (iOfst+iAmt);
  59643. }
  59644. }
  59645. }
  59646. return rc;
  59647. }
  59648. /*
  59649. ** Truncate the file.
  59650. */
  59651. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  59652. int rc = SQLITE_OK;
  59653. JournalFile *p = (JournalFile *)pJfd;
  59654. if( p->pReal ){
  59655. rc = sqlite3OsTruncate(p->pReal, size);
  59656. }else if( size<p->iSize ){
  59657. p->iSize = size;
  59658. }
  59659. return rc;
  59660. }
  59661. /*
  59662. ** Sync the file.
  59663. */
  59664. static int jrnlSync(sqlite3_file *pJfd, int flags){
  59665. int rc;
  59666. JournalFile *p = (JournalFile *)pJfd;
  59667. if( p->pReal ){
  59668. rc = sqlite3OsSync(p->pReal, flags);
  59669. }else{
  59670. rc = SQLITE_OK;
  59671. }
  59672. return rc;
  59673. }
  59674. /*
  59675. ** Query the size of the file in bytes.
  59676. */
  59677. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  59678. int rc = SQLITE_OK;
  59679. JournalFile *p = (JournalFile *)pJfd;
  59680. if( p->pReal ){
  59681. rc = sqlite3OsFileSize(p->pReal, pSize);
  59682. }else{
  59683. *pSize = (sqlite_int64) p->iSize;
  59684. }
  59685. return rc;
  59686. }
  59687. /*
  59688. ** Table of methods for JournalFile sqlite3_file object.
  59689. */
  59690. static struct sqlite3_io_methods JournalFileMethods = {
  59691. 1, /* iVersion */
  59692. jrnlClose, /* xClose */
  59693. jrnlRead, /* xRead */
  59694. jrnlWrite, /* xWrite */
  59695. jrnlTruncate, /* xTruncate */
  59696. jrnlSync, /* xSync */
  59697. jrnlFileSize, /* xFileSize */
  59698. 0, /* xLock */
  59699. 0, /* xUnlock */
  59700. 0, /* xCheckReservedLock */
  59701. 0, /* xFileControl */
  59702. 0, /* xSectorSize */
  59703. 0, /* xDeviceCharacteristics */
  59704. 0, /* xShmMap */
  59705. 0, /* xShmLock */
  59706. 0, /* xShmBarrier */
  59707. 0 /* xShmUnmap */
  59708. };
  59709. /*
  59710. ** Open a journal file.
  59711. */
  59712. SQLITE_PRIVATE int sqlite3JournalOpen(
  59713. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  59714. const char *zName, /* Name of the journal file */
  59715. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  59716. int flags, /* Opening flags */
  59717. int nBuf /* Bytes buffered before opening the file */
  59718. ){
  59719. JournalFile *p = (JournalFile *)pJfd;
  59720. memset(p, 0, sqlite3JournalSize(pVfs));
  59721. if( nBuf>0 ){
  59722. p->zBuf = sqlite3MallocZero(nBuf);
  59723. if( !p->zBuf ){
  59724. return SQLITE_NOMEM;
  59725. }
  59726. }else{
  59727. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  59728. }
  59729. p->pMethod = &JournalFileMethods;
  59730. p->nBuf = nBuf;
  59731. p->flags = flags;
  59732. p->zJournal = zName;
  59733. p->pVfs = pVfs;
  59734. return SQLITE_OK;
  59735. }
  59736. /*
  59737. ** If the argument p points to a JournalFile structure, and the underlying
  59738. ** file has not yet been created, create it now.
  59739. */
  59740. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  59741. if( p->pMethods!=&JournalFileMethods ){
  59742. return SQLITE_OK;
  59743. }
  59744. return createFile((JournalFile *)p);
  59745. }
  59746. /*
  59747. ** The file-handle passed as the only argument is guaranteed to be an open
  59748. ** file. It may or may not be of class JournalFile. If the file is a
  59749. ** JournalFile, and the underlying file on disk has not yet been opened,
  59750. ** return 0. Otherwise, return 1.
  59751. */
  59752. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  59753. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  59754. }
  59755. /*
  59756. ** Return the number of bytes required to store a JournalFile that uses vfs
  59757. ** pVfs to create the underlying on-disk files.
  59758. */
  59759. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  59760. return (pVfs->szOsFile+sizeof(JournalFile));
  59761. }
  59762. #endif
  59763. /************** End of journal.c *********************************************/
  59764. /************** Begin file memjournal.c **************************************/
  59765. /*
  59766. ** 2008 October 7
  59767. **
  59768. ** The author disclaims copyright to this source code. In place of
  59769. ** a legal notice, here is a blessing:
  59770. **
  59771. ** May you do good and not evil.
  59772. ** May you find forgiveness for yourself and forgive others.
  59773. ** May you share freely, never taking more than you give.
  59774. **
  59775. *************************************************************************
  59776. **
  59777. ** This file contains code use to implement an in-memory rollback journal.
  59778. ** The in-memory rollback journal is used to journal transactions for
  59779. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  59780. */
  59781. /* Forward references to internal structures */
  59782. typedef struct MemJournal MemJournal;
  59783. typedef struct FilePoint FilePoint;
  59784. typedef struct FileChunk FileChunk;
  59785. /* Space to hold the rollback journal is allocated in increments of
  59786. ** this many bytes.
  59787. **
  59788. ** The size chosen is a little less than a power of two. That way,
  59789. ** the FileChunk object will have a size that almost exactly fills
  59790. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  59791. ** memory allocators.
  59792. */
  59793. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  59794. /*
  59795. ** The rollback journal is composed of a linked list of these structures.
  59796. */
  59797. struct FileChunk {
  59798. FileChunk *pNext; /* Next chunk in the journal */
  59799. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  59800. };
  59801. /*
  59802. ** An instance of this object serves as a cursor into the rollback journal.
  59803. ** The cursor can be either for reading or writing.
  59804. */
  59805. struct FilePoint {
  59806. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  59807. FileChunk *pChunk; /* Specific chunk into which cursor points */
  59808. };
  59809. /*
  59810. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  59811. ** is an instance of this class.
  59812. */
  59813. struct MemJournal {
  59814. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  59815. FileChunk *pFirst; /* Head of in-memory chunk-list */
  59816. FilePoint endpoint; /* Pointer to the end of the file */
  59817. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  59818. };
  59819. /*
  59820. ** Read data from the in-memory journal file. This is the implementation
  59821. ** of the sqlite3_vfs.xRead method.
  59822. */
  59823. static int memjrnlRead(
  59824. sqlite3_file *pJfd, /* The journal file from which to read */
  59825. void *zBuf, /* Put the results here */
  59826. int iAmt, /* Number of bytes to read */
  59827. sqlite_int64 iOfst /* Begin reading at this offset */
  59828. ){
  59829. MemJournal *p = (MemJournal *)pJfd;
  59830. u8 *zOut = zBuf;
  59831. int nRead = iAmt;
  59832. int iChunkOffset;
  59833. FileChunk *pChunk;
  59834. /* SQLite never tries to read past the end of a rollback journal file */
  59835. assert( iOfst+iAmt<=p->endpoint.iOffset );
  59836. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  59837. sqlite3_int64 iOff = 0;
  59838. for(pChunk=p->pFirst;
  59839. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  59840. pChunk=pChunk->pNext
  59841. ){
  59842. iOff += JOURNAL_CHUNKSIZE;
  59843. }
  59844. }else{
  59845. pChunk = p->readpoint.pChunk;
  59846. }
  59847. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  59848. do {
  59849. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  59850. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  59851. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  59852. zOut += nCopy;
  59853. nRead -= iSpace;
  59854. iChunkOffset = 0;
  59855. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  59856. p->readpoint.iOffset = iOfst+iAmt;
  59857. p->readpoint.pChunk = pChunk;
  59858. return SQLITE_OK;
  59859. }
  59860. /*
  59861. ** Write data to the file.
  59862. */
  59863. static int memjrnlWrite(
  59864. sqlite3_file *pJfd, /* The journal file into which to write */
  59865. const void *zBuf, /* Take data to be written from here */
  59866. int iAmt, /* Number of bytes to write */
  59867. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  59868. ){
  59869. MemJournal *p = (MemJournal *)pJfd;
  59870. int nWrite = iAmt;
  59871. u8 *zWrite = (u8 *)zBuf;
  59872. /* An in-memory journal file should only ever be appended to. Random
  59873. ** access writes are not required by sqlite.
  59874. */
  59875. assert( iOfst==p->endpoint.iOffset );
  59876. UNUSED_PARAMETER(iOfst);
  59877. while( nWrite>0 ){
  59878. FileChunk *pChunk = p->endpoint.pChunk;
  59879. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  59880. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  59881. if( iChunkOffset==0 ){
  59882. /* New chunk is required to extend the file. */
  59883. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  59884. if( !pNew ){
  59885. return SQLITE_IOERR_NOMEM;
  59886. }
  59887. pNew->pNext = 0;
  59888. if( pChunk ){
  59889. assert( p->pFirst );
  59890. pChunk->pNext = pNew;
  59891. }else{
  59892. assert( !p->pFirst );
  59893. p->pFirst = pNew;
  59894. }
  59895. p->endpoint.pChunk = pNew;
  59896. }
  59897. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  59898. zWrite += iSpace;
  59899. nWrite -= iSpace;
  59900. p->endpoint.iOffset += iSpace;
  59901. }
  59902. return SQLITE_OK;
  59903. }
  59904. /*
  59905. ** Truncate the file.
  59906. */
  59907. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  59908. MemJournal *p = (MemJournal *)pJfd;
  59909. FileChunk *pChunk;
  59910. assert(size==0);
  59911. UNUSED_PARAMETER(size);
  59912. pChunk = p->pFirst;
  59913. while( pChunk ){
  59914. FileChunk *pTmp = pChunk;
  59915. pChunk = pChunk->pNext;
  59916. sqlite3_free(pTmp);
  59917. }
  59918. sqlite3MemJournalOpen(pJfd);
  59919. return SQLITE_OK;
  59920. }
  59921. /*
  59922. ** Close the file.
  59923. */
  59924. static int memjrnlClose(sqlite3_file *pJfd){
  59925. memjrnlTruncate(pJfd, 0);
  59926. return SQLITE_OK;
  59927. }
  59928. /*
  59929. ** Sync the file.
  59930. **
  59931. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  59932. ** is never called in a working implementation. This implementation
  59933. ** exists purely as a contingency, in case some malfunction in some other
  59934. ** part of SQLite causes Sync to be called by mistake.
  59935. */
  59936. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  59937. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  59938. return SQLITE_OK;
  59939. }
  59940. /*
  59941. ** Query the size of the file in bytes.
  59942. */
  59943. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  59944. MemJournal *p = (MemJournal *)pJfd;
  59945. *pSize = (sqlite_int64) p->endpoint.iOffset;
  59946. return SQLITE_OK;
  59947. }
  59948. /*
  59949. ** Table of methods for MemJournal sqlite3_file object.
  59950. */
  59951. static const struct sqlite3_io_methods MemJournalMethods = {
  59952. 1, /* iVersion */
  59953. memjrnlClose, /* xClose */
  59954. memjrnlRead, /* xRead */
  59955. memjrnlWrite, /* xWrite */
  59956. memjrnlTruncate, /* xTruncate */
  59957. memjrnlSync, /* xSync */
  59958. memjrnlFileSize, /* xFileSize */
  59959. 0, /* xLock */
  59960. 0, /* xUnlock */
  59961. 0, /* xCheckReservedLock */
  59962. 0, /* xFileControl */
  59963. 0, /* xSectorSize */
  59964. 0, /* xDeviceCharacteristics */
  59965. 0, /* xShmMap */
  59966. 0, /* xShmLock */
  59967. 0, /* xShmBarrier */
  59968. 0, /* xShmUnmap */
  59969. 0, /* xFetch */
  59970. 0 /* xUnfetch */
  59971. };
  59972. /*
  59973. ** Open a journal file.
  59974. */
  59975. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  59976. MemJournal *p = (MemJournal *)pJfd;
  59977. assert( EIGHT_BYTE_ALIGNMENT(p) );
  59978. memset(p, 0, sqlite3MemJournalSize());
  59979. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  59980. }
  59981. /*
  59982. ** Return true if the file-handle passed as an argument is
  59983. ** an in-memory journal
  59984. */
  59985. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  59986. return pJfd->pMethods==&MemJournalMethods;
  59987. }
  59988. /*
  59989. ** Return the number of bytes required to store a MemJournal file descriptor.
  59990. */
  59991. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  59992. return sizeof(MemJournal);
  59993. }
  59994. /************** End of memjournal.c ******************************************/
  59995. /************** Begin file walker.c ******************************************/
  59996. /*
  59997. ** 2008 August 16
  59998. **
  59999. ** The author disclaims copyright to this source code. In place of
  60000. ** a legal notice, here is a blessing:
  60001. **
  60002. ** May you do good and not evil.
  60003. ** May you find forgiveness for yourself and forgive others.
  60004. ** May you share freely, never taking more than you give.
  60005. **
  60006. *************************************************************************
  60007. ** This file contains routines used for walking the parser tree for
  60008. ** an SQL statement.
  60009. */
  60010. /* #include <stdlib.h> */
  60011. /* #include <string.h> */
  60012. /*
  60013. ** Walk an expression tree. Invoke the callback once for each node
  60014. ** of the expression, while decending. (In other words, the callback
  60015. ** is invoked before visiting children.)
  60016. **
  60017. ** The return value from the callback should be one of the WRC_*
  60018. ** constants to specify how to proceed with the walk.
  60019. **
  60020. ** WRC_Continue Continue descending down the tree.
  60021. **
  60022. ** WRC_Prune Do not descend into child nodes. But allow
  60023. ** the walk to continue with sibling nodes.
  60024. **
  60025. ** WRC_Abort Do no more callbacks. Unwind the stack and
  60026. ** return the top-level walk call.
  60027. **
  60028. ** The return value from this routine is WRC_Abort to abandon the tree walk
  60029. ** and WRC_Continue to continue.
  60030. */
  60031. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  60032. int rc;
  60033. if( pExpr==0 ) return WRC_Continue;
  60034. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  60035. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  60036. rc = pWalker->xExprCallback(pWalker, pExpr);
  60037. if( rc==WRC_Continue
  60038. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  60039. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  60040. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  60041. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  60042. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  60043. }else{
  60044. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  60045. }
  60046. }
  60047. return rc & WRC_Abort;
  60048. }
  60049. /*
  60050. ** Call sqlite3WalkExpr() for every expression in list p or until
  60051. ** an abort request is seen.
  60052. */
  60053. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  60054. int i;
  60055. struct ExprList_item *pItem;
  60056. if( p ){
  60057. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  60058. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  60059. }
  60060. }
  60061. return WRC_Continue;
  60062. }
  60063. /*
  60064. ** Walk all expressions associated with SELECT statement p. Do
  60065. ** not invoke the SELECT callback on p, but do (of course) invoke
  60066. ** any expr callbacks and SELECT callbacks that come from subqueries.
  60067. ** Return WRC_Abort or WRC_Continue.
  60068. */
  60069. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  60070. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  60071. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  60072. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  60073. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  60074. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  60075. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  60076. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  60077. return WRC_Continue;
  60078. }
  60079. /*
  60080. ** Walk the parse trees associated with all subqueries in the
  60081. ** FROM clause of SELECT statement p. Do not invoke the select
  60082. ** callback on p, but do invoke it on each FROM clause subquery
  60083. ** and on any subqueries further down in the tree. Return
  60084. ** WRC_Abort or WRC_Continue;
  60085. */
  60086. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  60087. SrcList *pSrc;
  60088. int i;
  60089. struct SrcList_item *pItem;
  60090. pSrc = p->pSrc;
  60091. if( ALWAYS(pSrc) ){
  60092. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  60093. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  60094. return WRC_Abort;
  60095. }
  60096. }
  60097. }
  60098. return WRC_Continue;
  60099. }
  60100. /*
  60101. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  60102. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  60103. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  60104. ** either before or after the walk of expressions and FROM clause, depending
  60105. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  60106. **
  60107. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  60108. ** there is an abort request.
  60109. **
  60110. ** If the Walker does not have an xSelectCallback() then this routine
  60111. ** is a no-op returning WRC_Continue.
  60112. */
  60113. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  60114. int rc;
  60115. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  60116. rc = WRC_Continue;
  60117. pWalker->walkerDepth++;
  60118. while( p ){
  60119. if( !pWalker->bSelectDepthFirst ){
  60120. rc = pWalker->xSelectCallback(pWalker, p);
  60121. if( rc ) break;
  60122. }
  60123. if( sqlite3WalkSelectExpr(pWalker, p)
  60124. || sqlite3WalkSelectFrom(pWalker, p)
  60125. ){
  60126. pWalker->walkerDepth--;
  60127. return WRC_Abort;
  60128. }
  60129. if( pWalker->bSelectDepthFirst ){
  60130. rc = pWalker->xSelectCallback(pWalker, p);
  60131. /* Depth-first search is currently only used for
  60132. ** selectAddSubqueryTypeInfo() and that routine always returns
  60133. ** WRC_Continue (0). So the following branch is never taken. */
  60134. if( NEVER(rc) ) break;
  60135. }
  60136. p = p->pPrior;
  60137. }
  60138. pWalker->walkerDepth--;
  60139. return rc & WRC_Abort;
  60140. }
  60141. /************** End of walker.c **********************************************/
  60142. /************** Begin file resolve.c *****************************************/
  60143. /*
  60144. ** 2008 August 18
  60145. **
  60146. ** The author disclaims copyright to this source code. In place of
  60147. ** a legal notice, here is a blessing:
  60148. **
  60149. ** May you do good and not evil.
  60150. ** May you find forgiveness for yourself and forgive others.
  60151. ** May you share freely, never taking more than you give.
  60152. **
  60153. *************************************************************************
  60154. **
  60155. ** This file contains routines used for walking the parser tree and
  60156. ** resolve all identifiers by associating them with a particular
  60157. ** table and column.
  60158. */
  60159. /* #include <stdlib.h> */
  60160. /* #include <string.h> */
  60161. /*
  60162. ** Walk the expression tree pExpr and increase the aggregate function
  60163. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  60164. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  60165. ** outer query into an inner subquery.
  60166. **
  60167. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  60168. ** is a helper function - a callback for the tree walker.
  60169. */
  60170. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  60171. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  60172. return WRC_Continue;
  60173. }
  60174. static void incrAggFunctionDepth(Expr *pExpr, int N){
  60175. if( N>0 ){
  60176. Walker w;
  60177. memset(&w, 0, sizeof(w));
  60178. w.xExprCallback = incrAggDepth;
  60179. w.u.i = N;
  60180. sqlite3WalkExpr(&w, pExpr);
  60181. }
  60182. }
  60183. /*
  60184. ** Turn the pExpr expression into an alias for the iCol-th column of the
  60185. ** result set in pEList.
  60186. **
  60187. ** If the result set column is a simple column reference, then this routine
  60188. ** makes an exact copy. But for any other kind of expression, this
  60189. ** routine make a copy of the result set column as the argument to the
  60190. ** TK_AS operator. The TK_AS operator causes the expression to be
  60191. ** evaluated just once and then reused for each alias.
  60192. **
  60193. ** The reason for suppressing the TK_AS term when the expression is a simple
  60194. ** column reference is so that the column reference will be recognized as
  60195. ** usable by indices within the WHERE clause processing logic.
  60196. **
  60197. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  60198. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  60199. **
  60200. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  60201. **
  60202. ** Is equivalent to:
  60203. **
  60204. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  60205. **
  60206. ** The result of random()%5 in the GROUP BY clause is probably different
  60207. ** from the result in the result-set. On the other hand Standard SQL does
  60208. ** not allow the GROUP BY clause to contain references to result-set columns.
  60209. ** So this should never come up in well-formed queries.
  60210. **
  60211. ** If the reference is followed by a COLLATE operator, then make sure
  60212. ** the COLLATE operator is preserved. For example:
  60213. **
  60214. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  60215. **
  60216. ** Should be transformed into:
  60217. **
  60218. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  60219. **
  60220. ** The nSubquery parameter specifies how many levels of subquery the
  60221. ** alias is removed from the original expression. The usually value is
  60222. ** zero but it might be more if the alias is contained within a subquery
  60223. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  60224. ** structures must be increased by the nSubquery amount.
  60225. */
  60226. static void resolveAlias(
  60227. Parse *pParse, /* Parsing context */
  60228. ExprList *pEList, /* A result set */
  60229. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  60230. Expr *pExpr, /* Transform this into an alias to the result set */
  60231. const char *zType, /* "GROUP" or "ORDER" or "" */
  60232. int nSubquery /* Number of subqueries that the label is moving */
  60233. ){
  60234. Expr *pOrig; /* The iCol-th column of the result set */
  60235. Expr *pDup; /* Copy of pOrig */
  60236. sqlite3 *db; /* The database connection */
  60237. assert( iCol>=0 && iCol<pEList->nExpr );
  60238. pOrig = pEList->a[iCol].pExpr;
  60239. assert( pOrig!=0 );
  60240. assert( pOrig->flags & EP_Resolved );
  60241. db = pParse->db;
  60242. pDup = sqlite3ExprDup(db, pOrig, 0);
  60243. if( pDup==0 ) return;
  60244. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  60245. incrAggFunctionDepth(pDup, nSubquery);
  60246. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  60247. if( pDup==0 ) return;
  60248. ExprSetProperty(pDup, EP_Skip);
  60249. if( pEList->a[iCol].iAlias==0 ){
  60250. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  60251. }
  60252. pDup->iTable = pEList->a[iCol].iAlias;
  60253. }
  60254. if( pExpr->op==TK_COLLATE ){
  60255. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  60256. }
  60257. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  60258. ** prevents ExprDelete() from deleting the Expr structure itself,
  60259. ** allowing it to be repopulated by the memcpy() on the following line.
  60260. ** The pExpr->u.zToken might point into memory that will be freed by the
  60261. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  60262. ** make a copy of the token before doing the sqlite3DbFree().
  60263. */
  60264. ExprSetProperty(pExpr, EP_Static);
  60265. sqlite3ExprDelete(db, pExpr);
  60266. memcpy(pExpr, pDup, sizeof(*pExpr));
  60267. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  60268. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  60269. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  60270. pExpr->flags |= EP_MemToken;
  60271. }
  60272. sqlite3DbFree(db, pDup);
  60273. }
  60274. /*
  60275. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  60276. **
  60277. ** Return FALSE if the USING clause is NULL or if it does not contain
  60278. ** zCol.
  60279. */
  60280. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  60281. if( pUsing ){
  60282. int k;
  60283. for(k=0; k<pUsing->nId; k++){
  60284. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  60285. }
  60286. }
  60287. return 0;
  60288. }
  60289. /*
  60290. ** Subqueries stores the original database, table and column names for their
  60291. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  60292. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  60293. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  60294. ** match anything.
  60295. */
  60296. SQLITE_PRIVATE int sqlite3MatchSpanName(
  60297. const char *zSpan,
  60298. const char *zCol,
  60299. const char *zTab,
  60300. const char *zDb
  60301. ){
  60302. int n;
  60303. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  60304. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  60305. return 0;
  60306. }
  60307. zSpan += n+1;
  60308. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  60309. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  60310. return 0;
  60311. }
  60312. zSpan += n+1;
  60313. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  60314. return 0;
  60315. }
  60316. return 1;
  60317. }
  60318. /*
  60319. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  60320. ** that name in the set of source tables in pSrcList and make the pExpr
  60321. ** expression node refer back to that source column. The following changes
  60322. ** are made to pExpr:
  60323. **
  60324. ** pExpr->iDb Set the index in db->aDb[] of the database X
  60325. ** (even if X is implied).
  60326. ** pExpr->iTable Set to the cursor number for the table obtained
  60327. ** from pSrcList.
  60328. ** pExpr->pTab Points to the Table structure of X.Y (even if
  60329. ** X and/or Y are implied.)
  60330. ** pExpr->iColumn Set to the column number within the table.
  60331. ** pExpr->op Set to TK_COLUMN.
  60332. ** pExpr->pLeft Any expression this points to is deleted
  60333. ** pExpr->pRight Any expression this points to is deleted.
  60334. **
  60335. ** The zDb variable is the name of the database (the "X"). This value may be
  60336. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  60337. ** can be used. The zTable variable is the name of the table (the "Y"). This
  60338. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  60339. ** means that the form of the name is Z and that columns from any table
  60340. ** can be used.
  60341. **
  60342. ** If the name cannot be resolved unambiguously, leave an error message
  60343. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  60344. */
  60345. static int lookupName(
  60346. Parse *pParse, /* The parsing context */
  60347. const char *zDb, /* Name of the database containing table, or NULL */
  60348. const char *zTab, /* Name of table containing column, or NULL */
  60349. const char *zCol, /* Name of the column. */
  60350. NameContext *pNC, /* The name context used to resolve the name */
  60351. Expr *pExpr /* Make this EXPR node point to the selected column */
  60352. ){
  60353. int i, j; /* Loop counters */
  60354. int cnt = 0; /* Number of matching column names */
  60355. int cntTab = 0; /* Number of matching table names */
  60356. int nSubquery = 0; /* How many levels of subquery */
  60357. sqlite3 *db = pParse->db; /* The database connection */
  60358. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  60359. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  60360. NameContext *pTopNC = pNC; /* First namecontext in the list */
  60361. Schema *pSchema = 0; /* Schema of the expression */
  60362. int isTrigger = 0;
  60363. assert( pNC ); /* the name context cannot be NULL. */
  60364. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  60365. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  60366. /* Initialize the node to no-match */
  60367. pExpr->iTable = -1;
  60368. pExpr->pTab = 0;
  60369. ExprSetVVAProperty(pExpr, EP_NoReduce);
  60370. /* Translate the schema name in zDb into a pointer to the corresponding
  60371. ** schema. If not found, pSchema will remain NULL and nothing will match
  60372. ** resulting in an appropriate error message toward the end of this routine
  60373. */
  60374. if( zDb ){
  60375. testcase( pNC->ncFlags & NC_PartIdx );
  60376. testcase( pNC->ncFlags & NC_IsCheck );
  60377. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  60378. /* Silently ignore database qualifiers inside CHECK constraints and partial
  60379. ** indices. Do not raise errors because that might break legacy and
  60380. ** because it does not hurt anything to just ignore the database name. */
  60381. zDb = 0;
  60382. }else{
  60383. for(i=0; i<db->nDb; i++){
  60384. assert( db->aDb[i].zName );
  60385. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  60386. pSchema = db->aDb[i].pSchema;
  60387. break;
  60388. }
  60389. }
  60390. }
  60391. }
  60392. /* Start at the inner-most context and move outward until a match is found */
  60393. while( pNC && cnt==0 ){
  60394. ExprList *pEList;
  60395. SrcList *pSrcList = pNC->pSrcList;
  60396. if( pSrcList ){
  60397. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  60398. Table *pTab;
  60399. Column *pCol;
  60400. pTab = pItem->pTab;
  60401. assert( pTab!=0 && pTab->zName!=0 );
  60402. assert( pTab->nCol>0 );
  60403. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  60404. int hit = 0;
  60405. pEList = pItem->pSelect->pEList;
  60406. for(j=0; j<pEList->nExpr; j++){
  60407. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  60408. cnt++;
  60409. cntTab = 2;
  60410. pMatch = pItem;
  60411. pExpr->iColumn = j;
  60412. hit = 1;
  60413. }
  60414. }
  60415. if( hit || zTab==0 ) continue;
  60416. }
  60417. if( zDb && pTab->pSchema!=pSchema ){
  60418. continue;
  60419. }
  60420. if( zTab ){
  60421. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  60422. assert( zTabName!=0 );
  60423. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  60424. continue;
  60425. }
  60426. }
  60427. if( 0==(cntTab++) ){
  60428. pMatch = pItem;
  60429. }
  60430. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  60431. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  60432. /* If there has been exactly one prior match and this match
  60433. ** is for the right-hand table of a NATURAL JOIN or is in a
  60434. ** USING clause, then skip this match.
  60435. */
  60436. if( cnt==1 ){
  60437. if( pItem->jointype & JT_NATURAL ) continue;
  60438. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  60439. }
  60440. cnt++;
  60441. pMatch = pItem;
  60442. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  60443. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  60444. break;
  60445. }
  60446. }
  60447. }
  60448. if( pMatch ){
  60449. pExpr->iTable = pMatch->iCursor;
  60450. pExpr->pTab = pMatch->pTab;
  60451. pSchema = pExpr->pTab->pSchema;
  60452. }
  60453. } /* if( pSrcList ) */
  60454. #ifndef SQLITE_OMIT_TRIGGER
  60455. /* If we have not already resolved the name, then maybe
  60456. ** it is a new.* or old.* trigger argument reference
  60457. */
  60458. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  60459. int op = pParse->eTriggerOp;
  60460. Table *pTab = 0;
  60461. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  60462. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  60463. pExpr->iTable = 1;
  60464. pTab = pParse->pTriggerTab;
  60465. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  60466. pExpr->iTable = 0;
  60467. pTab = pParse->pTriggerTab;
  60468. }
  60469. if( pTab ){
  60470. int iCol;
  60471. pSchema = pTab->pSchema;
  60472. cntTab++;
  60473. for(iCol=0; iCol<pTab->nCol; iCol++){
  60474. Column *pCol = &pTab->aCol[iCol];
  60475. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  60476. if( iCol==pTab->iPKey ){
  60477. iCol = -1;
  60478. }
  60479. break;
  60480. }
  60481. }
  60482. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  60483. iCol = -1; /* IMP: R-44911-55124 */
  60484. }
  60485. if( iCol<pTab->nCol ){
  60486. cnt++;
  60487. if( iCol<0 ){
  60488. pExpr->affinity = SQLITE_AFF_INTEGER;
  60489. }else if( pExpr->iTable==0 ){
  60490. testcase( iCol==31 );
  60491. testcase( iCol==32 );
  60492. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  60493. }else{
  60494. testcase( iCol==31 );
  60495. testcase( iCol==32 );
  60496. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  60497. }
  60498. pExpr->iColumn = (i16)iCol;
  60499. pExpr->pTab = pTab;
  60500. isTrigger = 1;
  60501. }
  60502. }
  60503. }
  60504. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  60505. /*
  60506. ** Perhaps the name is a reference to the ROWID
  60507. */
  60508. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  60509. cnt = 1;
  60510. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  60511. pExpr->affinity = SQLITE_AFF_INTEGER;
  60512. }
  60513. /*
  60514. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  60515. ** might refer to an result-set alias. This happens, for example, when
  60516. ** we are resolving names in the WHERE clause of the following command:
  60517. **
  60518. ** SELECT a+b AS x FROM table WHERE x<10;
  60519. **
  60520. ** In cases like this, replace pExpr with a copy of the expression that
  60521. ** forms the result set entry ("a+b" in the example) and return immediately.
  60522. ** Note that the expression in the result set should have already been
  60523. ** resolved by the time the WHERE clause is resolved.
  60524. **
  60525. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  60526. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  60527. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  60528. ** is supported for backwards compatibility only. TO DO: Issue a warning
  60529. ** on sqlite3_log() whenever the capability is used.
  60530. */
  60531. if( (pEList = pNC->pEList)!=0
  60532. && zTab==0
  60533. && cnt==0
  60534. ){
  60535. for(j=0; j<pEList->nExpr; j++){
  60536. char *zAs = pEList->a[j].zName;
  60537. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  60538. Expr *pOrig;
  60539. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  60540. assert( pExpr->x.pList==0 );
  60541. assert( pExpr->x.pSelect==0 );
  60542. pOrig = pEList->a[j].pExpr;
  60543. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  60544. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  60545. return WRC_Abort;
  60546. }
  60547. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  60548. cnt = 1;
  60549. pMatch = 0;
  60550. assert( zTab==0 && zDb==0 );
  60551. goto lookupname_end;
  60552. }
  60553. }
  60554. }
  60555. /* Advance to the next name context. The loop will exit when either
  60556. ** we have a match (cnt>0) or when we run out of name contexts.
  60557. */
  60558. if( cnt==0 ){
  60559. pNC = pNC->pNext;
  60560. nSubquery++;
  60561. }
  60562. }
  60563. /*
  60564. ** If X and Y are NULL (in other words if only the column name Z is
  60565. ** supplied) and the value of Z is enclosed in double-quotes, then
  60566. ** Z is a string literal if it doesn't match any column names. In that
  60567. ** case, we need to return right away and not make any changes to
  60568. ** pExpr.
  60569. **
  60570. ** Because no reference was made to outer contexts, the pNC->nRef
  60571. ** fields are not changed in any context.
  60572. */
  60573. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  60574. pExpr->op = TK_STRING;
  60575. pExpr->pTab = 0;
  60576. return WRC_Prune;
  60577. }
  60578. /*
  60579. ** cnt==0 means there was not match. cnt>1 means there were two or
  60580. ** more matches. Either way, we have an error.
  60581. */
  60582. if( cnt!=1 ){
  60583. const char *zErr;
  60584. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  60585. if( zDb ){
  60586. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  60587. }else if( zTab ){
  60588. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  60589. }else{
  60590. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  60591. }
  60592. pParse->checkSchema = 1;
  60593. pTopNC->nErr++;
  60594. }
  60595. /* If a column from a table in pSrcList is referenced, then record
  60596. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  60597. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  60598. ** column number is greater than the number of bits in the bitmask
  60599. ** then set the high-order bit of the bitmask.
  60600. */
  60601. if( pExpr->iColumn>=0 && pMatch!=0 ){
  60602. int n = pExpr->iColumn;
  60603. testcase( n==BMS-1 );
  60604. if( n>=BMS ){
  60605. n = BMS-1;
  60606. }
  60607. assert( pMatch->iCursor==pExpr->iTable );
  60608. pMatch->colUsed |= ((Bitmask)1)<<n;
  60609. }
  60610. /* Clean up and return
  60611. */
  60612. sqlite3ExprDelete(db, pExpr->pLeft);
  60613. pExpr->pLeft = 0;
  60614. sqlite3ExprDelete(db, pExpr->pRight);
  60615. pExpr->pRight = 0;
  60616. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  60617. lookupname_end:
  60618. if( cnt==1 ){
  60619. assert( pNC!=0 );
  60620. if( pExpr->op!=TK_AS ){
  60621. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  60622. }
  60623. /* Increment the nRef value on all name contexts from TopNC up to
  60624. ** the point where the name matched. */
  60625. for(;;){
  60626. assert( pTopNC!=0 );
  60627. pTopNC->nRef++;
  60628. if( pTopNC==pNC ) break;
  60629. pTopNC = pTopNC->pNext;
  60630. }
  60631. return WRC_Prune;
  60632. } else {
  60633. return WRC_Abort;
  60634. }
  60635. }
  60636. /*
  60637. ** Allocate and return a pointer to an expression to load the column iCol
  60638. ** from datasource iSrc in SrcList pSrc.
  60639. */
  60640. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  60641. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  60642. if( p ){
  60643. struct SrcList_item *pItem = &pSrc->a[iSrc];
  60644. p->pTab = pItem->pTab;
  60645. p->iTable = pItem->iCursor;
  60646. if( p->pTab->iPKey==iCol ){
  60647. p->iColumn = -1;
  60648. }else{
  60649. p->iColumn = (ynVar)iCol;
  60650. testcase( iCol==BMS );
  60651. testcase( iCol==BMS-1 );
  60652. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  60653. }
  60654. ExprSetProperty(p, EP_Resolved);
  60655. }
  60656. return p;
  60657. }
  60658. /*
  60659. ** Report an error that an expression is not valid for a partial index WHERE
  60660. ** clause.
  60661. */
  60662. static void notValidPartIdxWhere(
  60663. Parse *pParse, /* Leave error message here */
  60664. NameContext *pNC, /* The name context */
  60665. const char *zMsg /* Type of error */
  60666. ){
  60667. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  60668. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  60669. zMsg);
  60670. }
  60671. }
  60672. #ifndef SQLITE_OMIT_CHECK
  60673. /*
  60674. ** Report an error that an expression is not valid for a CHECK constraint.
  60675. */
  60676. static void notValidCheckConstraint(
  60677. Parse *pParse, /* Leave error message here */
  60678. NameContext *pNC, /* The name context */
  60679. const char *zMsg /* Type of error */
  60680. ){
  60681. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  60682. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  60683. }
  60684. }
  60685. #else
  60686. # define notValidCheckConstraint(P,N,M)
  60687. #endif
  60688. /*
  60689. ** Expression p should encode a floating point value between 1.0 and 0.0.
  60690. ** Return 1024 times this value. Or return -1 if p is not a floating point
  60691. ** value between 1.0 and 0.0.
  60692. */
  60693. static int exprProbability(Expr *p){
  60694. double r = -1.0;
  60695. if( p->op!=TK_FLOAT ) return -1;
  60696. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  60697. assert( r>=0.0 );
  60698. if( r>1.0 ) return -1;
  60699. return (int)(r*1000.0);
  60700. }
  60701. /*
  60702. ** This routine is callback for sqlite3WalkExpr().
  60703. **
  60704. ** Resolve symbolic names into TK_COLUMN operators for the current
  60705. ** node in the expression tree. Return 0 to continue the search down
  60706. ** the tree or 2 to abort the tree walk.
  60707. **
  60708. ** This routine also does error checking and name resolution for
  60709. ** function names. The operator for aggregate functions is changed
  60710. ** to TK_AGG_FUNCTION.
  60711. */
  60712. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  60713. NameContext *pNC;
  60714. Parse *pParse;
  60715. pNC = pWalker->u.pNC;
  60716. assert( pNC!=0 );
  60717. pParse = pNC->pParse;
  60718. assert( pParse==pWalker->pParse );
  60719. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  60720. ExprSetProperty(pExpr, EP_Resolved);
  60721. #ifndef NDEBUG
  60722. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  60723. SrcList *pSrcList = pNC->pSrcList;
  60724. int i;
  60725. for(i=0; i<pNC->pSrcList->nSrc; i++){
  60726. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  60727. }
  60728. }
  60729. #endif
  60730. switch( pExpr->op ){
  60731. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  60732. /* The special operator TK_ROW means use the rowid for the first
  60733. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  60734. ** clause processing on UPDATE and DELETE statements.
  60735. */
  60736. case TK_ROW: {
  60737. SrcList *pSrcList = pNC->pSrcList;
  60738. struct SrcList_item *pItem;
  60739. assert( pSrcList && pSrcList->nSrc==1 );
  60740. pItem = pSrcList->a;
  60741. pExpr->op = TK_COLUMN;
  60742. pExpr->pTab = pItem->pTab;
  60743. pExpr->iTable = pItem->iCursor;
  60744. pExpr->iColumn = -1;
  60745. pExpr->affinity = SQLITE_AFF_INTEGER;
  60746. break;
  60747. }
  60748. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  60749. /* A lone identifier is the name of a column.
  60750. */
  60751. case TK_ID: {
  60752. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  60753. }
  60754. /* A table name and column name: ID.ID
  60755. ** Or a database, table and column: ID.ID.ID
  60756. */
  60757. case TK_DOT: {
  60758. const char *zColumn;
  60759. const char *zTable;
  60760. const char *zDb;
  60761. Expr *pRight;
  60762. /* if( pSrcList==0 ) break; */
  60763. pRight = pExpr->pRight;
  60764. if( pRight->op==TK_ID ){
  60765. zDb = 0;
  60766. zTable = pExpr->pLeft->u.zToken;
  60767. zColumn = pRight->u.zToken;
  60768. }else{
  60769. assert( pRight->op==TK_DOT );
  60770. zDb = pExpr->pLeft->u.zToken;
  60771. zTable = pRight->pLeft->u.zToken;
  60772. zColumn = pRight->pRight->u.zToken;
  60773. }
  60774. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  60775. }
  60776. /* Resolve function names
  60777. */
  60778. case TK_CONST_FUNC:
  60779. case TK_FUNCTION: {
  60780. ExprList *pList = pExpr->x.pList; /* The argument list */
  60781. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  60782. int no_such_func = 0; /* True if no such function exists */
  60783. int wrong_num_args = 0; /* True if wrong number of arguments */
  60784. int is_agg = 0; /* True if is an aggregate function */
  60785. int auth; /* Authorization to use the function */
  60786. int nId; /* Number of characters in function name */
  60787. const char *zId; /* The function name. */
  60788. FuncDef *pDef; /* Information about the function */
  60789. u8 enc = ENC(pParse->db); /* The database encoding */
  60790. testcase( pExpr->op==TK_CONST_FUNC );
  60791. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  60792. notValidPartIdxWhere(pParse, pNC, "functions");
  60793. zId = pExpr->u.zToken;
  60794. nId = sqlite3Strlen30(zId);
  60795. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  60796. if( pDef==0 ){
  60797. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  60798. if( pDef==0 ){
  60799. no_such_func = 1;
  60800. }else{
  60801. wrong_num_args = 1;
  60802. }
  60803. }else{
  60804. is_agg = pDef->xFunc==0;
  60805. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  60806. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  60807. if( n==2 ){
  60808. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  60809. if( pExpr->iTable<0 ){
  60810. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  60811. "constant between 0.0 and 1.0");
  60812. pNC->nErr++;
  60813. }
  60814. }else{
  60815. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  60816. ** likelihood(X, 0.0625).
  60817. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  60818. ** likelihood(X,0.0625). */
  60819. pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
  60820. }
  60821. }
  60822. }
  60823. #ifndef SQLITE_OMIT_AUTHORIZATION
  60824. if( pDef ){
  60825. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  60826. if( auth!=SQLITE_OK ){
  60827. if( auth==SQLITE_DENY ){
  60828. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  60829. pDef->zName);
  60830. pNC->nErr++;
  60831. }
  60832. pExpr->op = TK_NULL;
  60833. return WRC_Prune;
  60834. }
  60835. }
  60836. #endif
  60837. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  60838. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  60839. pNC->nErr++;
  60840. is_agg = 0;
  60841. }else if( no_such_func && pParse->db->init.busy==0 ){
  60842. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  60843. pNC->nErr++;
  60844. }else if( wrong_num_args ){
  60845. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  60846. nId, zId);
  60847. pNC->nErr++;
  60848. }
  60849. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  60850. sqlite3WalkExprList(pWalker, pList);
  60851. if( is_agg ){
  60852. NameContext *pNC2 = pNC;
  60853. pExpr->op = TK_AGG_FUNCTION;
  60854. pExpr->op2 = 0;
  60855. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  60856. pExpr->op2++;
  60857. pNC2 = pNC2->pNext;
  60858. }
  60859. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  60860. pNC->ncFlags |= NC_AllowAgg;
  60861. }
  60862. /* FIX ME: Compute pExpr->affinity based on the expected return
  60863. ** type of the function
  60864. */
  60865. return WRC_Prune;
  60866. }
  60867. #ifndef SQLITE_OMIT_SUBQUERY
  60868. case TK_SELECT:
  60869. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  60870. #endif
  60871. case TK_IN: {
  60872. testcase( pExpr->op==TK_IN );
  60873. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  60874. int nRef = pNC->nRef;
  60875. notValidCheckConstraint(pParse, pNC, "subqueries");
  60876. notValidPartIdxWhere(pParse, pNC, "subqueries");
  60877. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  60878. assert( pNC->nRef>=nRef );
  60879. if( nRef!=pNC->nRef ){
  60880. ExprSetProperty(pExpr, EP_VarSelect);
  60881. }
  60882. }
  60883. break;
  60884. }
  60885. case TK_VARIABLE: {
  60886. notValidCheckConstraint(pParse, pNC, "parameters");
  60887. notValidPartIdxWhere(pParse, pNC, "parameters");
  60888. break;
  60889. }
  60890. }
  60891. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  60892. }
  60893. /*
  60894. ** pEList is a list of expressions which are really the result set of the
  60895. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  60896. ** This routine checks to see if pE is a simple identifier which corresponds
  60897. ** to the AS-name of one of the terms of the expression list. If it is,
  60898. ** this routine return an integer between 1 and N where N is the number of
  60899. ** elements in pEList, corresponding to the matching entry. If there is
  60900. ** no match, or if pE is not a simple identifier, then this routine
  60901. ** return 0.
  60902. **
  60903. ** pEList has been resolved. pE has not.
  60904. */
  60905. static int resolveAsName(
  60906. Parse *pParse, /* Parsing context for error messages */
  60907. ExprList *pEList, /* List of expressions to scan */
  60908. Expr *pE /* Expression we are trying to match */
  60909. ){
  60910. int i; /* Loop counter */
  60911. UNUSED_PARAMETER(pParse);
  60912. if( pE->op==TK_ID ){
  60913. char *zCol = pE->u.zToken;
  60914. for(i=0; i<pEList->nExpr; i++){
  60915. char *zAs = pEList->a[i].zName;
  60916. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  60917. return i+1;
  60918. }
  60919. }
  60920. }
  60921. return 0;
  60922. }
  60923. /*
  60924. ** pE is a pointer to an expression which is a single term in the
  60925. ** ORDER BY of a compound SELECT. The expression has not been
  60926. ** name resolved.
  60927. **
  60928. ** At the point this routine is called, we already know that the
  60929. ** ORDER BY term is not an integer index into the result set. That
  60930. ** case is handled by the calling routine.
  60931. **
  60932. ** Attempt to match pE against result set columns in the left-most
  60933. ** SELECT statement. Return the index i of the matching column,
  60934. ** as an indication to the caller that it should sort by the i-th column.
  60935. ** The left-most column is 1. In other words, the value returned is the
  60936. ** same integer value that would be used in the SQL statement to indicate
  60937. ** the column.
  60938. **
  60939. ** If there is no match, return 0. Return -1 if an error occurs.
  60940. */
  60941. static int resolveOrderByTermToExprList(
  60942. Parse *pParse, /* Parsing context for error messages */
  60943. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  60944. Expr *pE /* The specific ORDER BY term */
  60945. ){
  60946. int i; /* Loop counter */
  60947. ExprList *pEList; /* The columns of the result set */
  60948. NameContext nc; /* Name context for resolving pE */
  60949. sqlite3 *db; /* Database connection */
  60950. int rc; /* Return code from subprocedures */
  60951. u8 savedSuppErr; /* Saved value of db->suppressErr */
  60952. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  60953. pEList = pSelect->pEList;
  60954. /* Resolve all names in the ORDER BY term expression
  60955. */
  60956. memset(&nc, 0, sizeof(nc));
  60957. nc.pParse = pParse;
  60958. nc.pSrcList = pSelect->pSrc;
  60959. nc.pEList = pEList;
  60960. nc.ncFlags = NC_AllowAgg;
  60961. nc.nErr = 0;
  60962. db = pParse->db;
  60963. savedSuppErr = db->suppressErr;
  60964. db->suppressErr = 1;
  60965. rc = sqlite3ResolveExprNames(&nc, pE);
  60966. db->suppressErr = savedSuppErr;
  60967. if( rc ) return 0;
  60968. /* Try to match the ORDER BY expression against an expression
  60969. ** in the result set. Return an 1-based index of the matching
  60970. ** result-set entry.
  60971. */
  60972. for(i=0; i<pEList->nExpr; i++){
  60973. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  60974. return i+1;
  60975. }
  60976. }
  60977. /* If no match, return 0. */
  60978. return 0;
  60979. }
  60980. /*
  60981. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  60982. */
  60983. static void resolveOutOfRangeError(
  60984. Parse *pParse, /* The error context into which to write the error */
  60985. const char *zType, /* "ORDER" or "GROUP" */
  60986. int i, /* The index (1-based) of the term out of range */
  60987. int mx /* Largest permissible value of i */
  60988. ){
  60989. sqlite3ErrorMsg(pParse,
  60990. "%r %s BY term out of range - should be "
  60991. "between 1 and %d", i, zType, mx);
  60992. }
  60993. /*
  60994. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  60995. ** each term of the ORDER BY clause is a constant integer between 1
  60996. ** and N where N is the number of columns in the compound SELECT.
  60997. **
  60998. ** ORDER BY terms that are already an integer between 1 and N are
  60999. ** unmodified. ORDER BY terms that are integers outside the range of
  61000. ** 1 through N generate an error. ORDER BY terms that are expressions
  61001. ** are matched against result set expressions of compound SELECT
  61002. ** beginning with the left-most SELECT and working toward the right.
  61003. ** At the first match, the ORDER BY expression is transformed into
  61004. ** the integer column number.
  61005. **
  61006. ** Return the number of errors seen.
  61007. */
  61008. static int resolveCompoundOrderBy(
  61009. Parse *pParse, /* Parsing context. Leave error messages here */
  61010. Select *pSelect /* The SELECT statement containing the ORDER BY */
  61011. ){
  61012. int i;
  61013. ExprList *pOrderBy;
  61014. ExprList *pEList;
  61015. sqlite3 *db;
  61016. int moreToDo = 1;
  61017. pOrderBy = pSelect->pOrderBy;
  61018. if( pOrderBy==0 ) return 0;
  61019. db = pParse->db;
  61020. #if SQLITE_MAX_COLUMN
  61021. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  61022. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  61023. return 1;
  61024. }
  61025. #endif
  61026. for(i=0; i<pOrderBy->nExpr; i++){
  61027. pOrderBy->a[i].done = 0;
  61028. }
  61029. pSelect->pNext = 0;
  61030. while( pSelect->pPrior ){
  61031. pSelect->pPrior->pNext = pSelect;
  61032. pSelect = pSelect->pPrior;
  61033. }
  61034. while( pSelect && moreToDo ){
  61035. struct ExprList_item *pItem;
  61036. moreToDo = 0;
  61037. pEList = pSelect->pEList;
  61038. assert( pEList!=0 );
  61039. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61040. int iCol = -1;
  61041. Expr *pE, *pDup;
  61042. if( pItem->done ) continue;
  61043. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  61044. if( sqlite3ExprIsInteger(pE, &iCol) ){
  61045. if( iCol<=0 || iCol>pEList->nExpr ){
  61046. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  61047. return 1;
  61048. }
  61049. }else{
  61050. iCol = resolveAsName(pParse, pEList, pE);
  61051. if( iCol==0 ){
  61052. pDup = sqlite3ExprDup(db, pE, 0);
  61053. if( !db->mallocFailed ){
  61054. assert(pDup);
  61055. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  61056. }
  61057. sqlite3ExprDelete(db, pDup);
  61058. }
  61059. }
  61060. if( iCol>0 ){
  61061. /* Convert the ORDER BY term into an integer column number iCol,
  61062. ** taking care to preserve the COLLATE clause if it exists */
  61063. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  61064. if( pNew==0 ) return 1;
  61065. pNew->flags |= EP_IntValue;
  61066. pNew->u.iValue = iCol;
  61067. if( pItem->pExpr==pE ){
  61068. pItem->pExpr = pNew;
  61069. }else{
  61070. assert( pItem->pExpr->op==TK_COLLATE );
  61071. assert( pItem->pExpr->pLeft==pE );
  61072. pItem->pExpr->pLeft = pNew;
  61073. }
  61074. sqlite3ExprDelete(db, pE);
  61075. pItem->iOrderByCol = (u16)iCol;
  61076. pItem->done = 1;
  61077. }else{
  61078. moreToDo = 1;
  61079. }
  61080. }
  61081. pSelect = pSelect->pNext;
  61082. }
  61083. for(i=0; i<pOrderBy->nExpr; i++){
  61084. if( pOrderBy->a[i].done==0 ){
  61085. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  61086. "column in the result set", i+1);
  61087. return 1;
  61088. }
  61089. }
  61090. return 0;
  61091. }
  61092. /*
  61093. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  61094. ** the SELECT statement pSelect. If any term is reference to a
  61095. ** result set expression (as determined by the ExprList.a.iOrderByCol field)
  61096. ** then convert that term into a copy of the corresponding result set
  61097. ** column.
  61098. **
  61099. ** If any errors are detected, add an error message to pParse and
  61100. ** return non-zero. Return zero if no errors are seen.
  61101. */
  61102. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  61103. Parse *pParse, /* Parsing context. Leave error messages here */
  61104. Select *pSelect, /* The SELECT statement containing the clause */
  61105. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  61106. const char *zType /* "ORDER" or "GROUP" */
  61107. ){
  61108. int i;
  61109. sqlite3 *db = pParse->db;
  61110. ExprList *pEList;
  61111. struct ExprList_item *pItem;
  61112. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  61113. #if SQLITE_MAX_COLUMN
  61114. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  61115. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  61116. return 1;
  61117. }
  61118. #endif
  61119. pEList = pSelect->pEList;
  61120. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  61121. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61122. if( pItem->iOrderByCol ){
  61123. if( pItem->iOrderByCol>pEList->nExpr ){
  61124. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  61125. return 1;
  61126. }
  61127. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  61128. }
  61129. }
  61130. return 0;
  61131. }
  61132. /*
  61133. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  61134. ** The Name context of the SELECT statement is pNC. zType is either
  61135. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  61136. **
  61137. ** This routine resolves each term of the clause into an expression.
  61138. ** If the order-by term is an integer I between 1 and N (where N is the
  61139. ** number of columns in the result set of the SELECT) then the expression
  61140. ** in the resolution is a copy of the I-th result-set expression. If
  61141. ** the order-by term is an identifier that corresponds to the AS-name of
  61142. ** a result-set expression, then the term resolves to a copy of the
  61143. ** result-set expression. Otherwise, the expression is resolved in
  61144. ** the usual way - using sqlite3ResolveExprNames().
  61145. **
  61146. ** This routine returns the number of errors. If errors occur, then
  61147. ** an appropriate error message might be left in pParse. (OOM errors
  61148. ** excepted.)
  61149. */
  61150. static int resolveOrderGroupBy(
  61151. NameContext *pNC, /* The name context of the SELECT statement */
  61152. Select *pSelect, /* The SELECT statement holding pOrderBy */
  61153. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  61154. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  61155. ){
  61156. int i, j; /* Loop counters */
  61157. int iCol; /* Column number */
  61158. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  61159. Parse *pParse; /* Parsing context */
  61160. int nResult; /* Number of terms in the result set */
  61161. if( pOrderBy==0 ) return 0;
  61162. nResult = pSelect->pEList->nExpr;
  61163. pParse = pNC->pParse;
  61164. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61165. Expr *pE = pItem->pExpr;
  61166. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  61167. if( zType[0]!='G' ){
  61168. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  61169. if( iCol>0 ){
  61170. /* If an AS-name match is found, mark this ORDER BY column as being
  61171. ** a copy of the iCol-th result-set column. The subsequent call to
  61172. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  61173. ** copy of the iCol-th result-set expression. */
  61174. pItem->iOrderByCol = (u16)iCol;
  61175. continue;
  61176. }
  61177. }
  61178. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  61179. /* The ORDER BY term is an integer constant. Again, set the column
  61180. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  61181. ** order-by term to a copy of the result-set expression */
  61182. if( iCol<1 || iCol>0xffff ){
  61183. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  61184. return 1;
  61185. }
  61186. pItem->iOrderByCol = (u16)iCol;
  61187. continue;
  61188. }
  61189. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  61190. pItem->iOrderByCol = 0;
  61191. if( sqlite3ResolveExprNames(pNC, pE) ){
  61192. return 1;
  61193. }
  61194. for(j=0; j<pSelect->pEList->nExpr; j++){
  61195. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  61196. pItem->iOrderByCol = j+1;
  61197. }
  61198. }
  61199. }
  61200. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  61201. }
  61202. /*
  61203. ** Resolve names in the SELECT statement p and all of its descendents.
  61204. */
  61205. static int resolveSelectStep(Walker *pWalker, Select *p){
  61206. NameContext *pOuterNC; /* Context that contains this SELECT */
  61207. NameContext sNC; /* Name context of this SELECT */
  61208. int isCompound; /* True if p is a compound select */
  61209. int nCompound; /* Number of compound terms processed so far */
  61210. Parse *pParse; /* Parsing context */
  61211. ExprList *pEList; /* Result set expression list */
  61212. int i; /* Loop counter */
  61213. ExprList *pGroupBy; /* The GROUP BY clause */
  61214. Select *pLeftmost; /* Left-most of SELECT of a compound */
  61215. sqlite3 *db; /* Database connection */
  61216. assert( p!=0 );
  61217. if( p->selFlags & SF_Resolved ){
  61218. return WRC_Prune;
  61219. }
  61220. pOuterNC = pWalker->u.pNC;
  61221. pParse = pWalker->pParse;
  61222. db = pParse->db;
  61223. /* Normally sqlite3SelectExpand() will be called first and will have
  61224. ** already expanded this SELECT. However, if this is a subquery within
  61225. ** an expression, sqlite3ResolveExprNames() will be called without a
  61226. ** prior call to sqlite3SelectExpand(). When that happens, let
  61227. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  61228. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  61229. ** this routine in the correct order.
  61230. */
  61231. if( (p->selFlags & SF_Expanded)==0 ){
  61232. sqlite3SelectPrep(pParse, p, pOuterNC);
  61233. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  61234. }
  61235. isCompound = p->pPrior!=0;
  61236. nCompound = 0;
  61237. pLeftmost = p;
  61238. while( p ){
  61239. assert( (p->selFlags & SF_Expanded)!=0 );
  61240. assert( (p->selFlags & SF_Resolved)==0 );
  61241. p->selFlags |= SF_Resolved;
  61242. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  61243. ** are not allowed to refer to any names, so pass an empty NameContext.
  61244. */
  61245. memset(&sNC, 0, sizeof(sNC));
  61246. sNC.pParse = pParse;
  61247. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  61248. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  61249. return WRC_Abort;
  61250. }
  61251. /* Recursively resolve names in all subqueries
  61252. */
  61253. for(i=0; i<p->pSrc->nSrc; i++){
  61254. struct SrcList_item *pItem = &p->pSrc->a[i];
  61255. if( pItem->pSelect ){
  61256. NameContext *pNC; /* Used to iterate name contexts */
  61257. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  61258. const char *zSavedContext = pParse->zAuthContext;
  61259. /* Count the total number of references to pOuterNC and all of its
  61260. ** parent contexts. After resolving references to expressions in
  61261. ** pItem->pSelect, check if this value has changed. If so, then
  61262. ** SELECT statement pItem->pSelect must be correlated. Set the
  61263. ** pItem->isCorrelated flag if this is the case. */
  61264. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  61265. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  61266. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  61267. pParse->zAuthContext = zSavedContext;
  61268. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  61269. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  61270. assert( pItem->isCorrelated==0 && nRef<=0 );
  61271. pItem->isCorrelated = (nRef!=0);
  61272. }
  61273. }
  61274. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  61275. ** resolve the result-set expression list.
  61276. */
  61277. sNC.ncFlags = NC_AllowAgg;
  61278. sNC.pSrcList = p->pSrc;
  61279. sNC.pNext = pOuterNC;
  61280. /* Resolve names in the result set. */
  61281. pEList = p->pEList;
  61282. assert( pEList!=0 );
  61283. for(i=0; i<pEList->nExpr; i++){
  61284. Expr *pX = pEList->a[i].pExpr;
  61285. if( sqlite3ResolveExprNames(&sNC, pX) ){
  61286. return WRC_Abort;
  61287. }
  61288. }
  61289. /* If there are no aggregate functions in the result-set, and no GROUP BY
  61290. ** expression, do not allow aggregates in any of the other expressions.
  61291. */
  61292. assert( (p->selFlags & SF_Aggregate)==0 );
  61293. pGroupBy = p->pGroupBy;
  61294. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  61295. p->selFlags |= SF_Aggregate;
  61296. }else{
  61297. sNC.ncFlags &= ~NC_AllowAgg;
  61298. }
  61299. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  61300. */
  61301. if( p->pHaving && !pGroupBy ){
  61302. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  61303. return WRC_Abort;
  61304. }
  61305. /* Add the output column list to the name-context before parsing the
  61306. ** other expressions in the SELECT statement. This is so that
  61307. ** expressions in the WHERE clause (etc.) can refer to expressions by
  61308. ** aliases in the result set.
  61309. **
  61310. ** Minor point: If this is the case, then the expression will be
  61311. ** re-evaluated for each reference to it.
  61312. */
  61313. sNC.pEList = p->pEList;
  61314. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  61315. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  61316. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  61317. ** outer queries
  61318. */
  61319. sNC.pNext = 0;
  61320. sNC.ncFlags |= NC_AllowAgg;
  61321. /* Process the ORDER BY clause for singleton SELECT statements.
  61322. ** The ORDER BY clause for compounds SELECT statements is handled
  61323. ** below, after all of the result-sets for all of the elements of
  61324. ** the compound have been resolved.
  61325. */
  61326. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  61327. return WRC_Abort;
  61328. }
  61329. if( db->mallocFailed ){
  61330. return WRC_Abort;
  61331. }
  61332. /* Resolve the GROUP BY clause. At the same time, make sure
  61333. ** the GROUP BY clause does not contain aggregate functions.
  61334. */
  61335. if( pGroupBy ){
  61336. struct ExprList_item *pItem;
  61337. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  61338. return WRC_Abort;
  61339. }
  61340. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  61341. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  61342. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  61343. "the GROUP BY clause");
  61344. return WRC_Abort;
  61345. }
  61346. }
  61347. }
  61348. /* Advance to the next term of the compound
  61349. */
  61350. p = p->pPrior;
  61351. nCompound++;
  61352. }
  61353. /* Resolve the ORDER BY on a compound SELECT after all terms of
  61354. ** the compound have been resolved.
  61355. */
  61356. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  61357. return WRC_Abort;
  61358. }
  61359. return WRC_Prune;
  61360. }
  61361. /*
  61362. ** This routine walks an expression tree and resolves references to
  61363. ** table columns and result-set columns. At the same time, do error
  61364. ** checking on function usage and set a flag if any aggregate functions
  61365. ** are seen.
  61366. **
  61367. ** To resolve table columns references we look for nodes (or subtrees) of the
  61368. ** form X.Y.Z or Y.Z or just Z where
  61369. **
  61370. ** X: The name of a database. Ex: "main" or "temp" or
  61371. ** the symbolic name assigned to an ATTACH-ed database.
  61372. **
  61373. ** Y: The name of a table in a FROM clause. Or in a trigger
  61374. ** one of the special names "old" or "new".
  61375. **
  61376. ** Z: The name of a column in table Y.
  61377. **
  61378. ** The node at the root of the subtree is modified as follows:
  61379. **
  61380. ** Expr.op Changed to TK_COLUMN
  61381. ** Expr.pTab Points to the Table object for X.Y
  61382. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  61383. ** Expr.iTable The VDBE cursor number for X.Y
  61384. **
  61385. **
  61386. ** To resolve result-set references, look for expression nodes of the
  61387. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  61388. ** size of an AS clause in the result-set of a SELECT. The Z expression
  61389. ** is replaced by a copy of the left-hand side of the result-set expression.
  61390. ** Table-name and function resolution occurs on the substituted expression
  61391. ** tree. For example, in:
  61392. **
  61393. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  61394. **
  61395. ** The "x" term of the order by is replaced by "a+b" to render:
  61396. **
  61397. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  61398. **
  61399. ** Function calls are checked to make sure that the function is
  61400. ** defined and that the correct number of arguments are specified.
  61401. ** If the function is an aggregate function, then the NC_HasAgg flag is
  61402. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  61403. ** If an expression contains aggregate functions then the EP_Agg
  61404. ** property on the expression is set.
  61405. **
  61406. ** An error message is left in pParse if anything is amiss. The number
  61407. ** if errors is returned.
  61408. */
  61409. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  61410. NameContext *pNC, /* Namespace to resolve expressions in. */
  61411. Expr *pExpr /* The expression to be analyzed. */
  61412. ){
  61413. u8 savedHasAgg;
  61414. Walker w;
  61415. if( pExpr==0 ) return 0;
  61416. #if SQLITE_MAX_EXPR_DEPTH>0
  61417. {
  61418. Parse *pParse = pNC->pParse;
  61419. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  61420. return 1;
  61421. }
  61422. pParse->nHeight += pExpr->nHeight;
  61423. }
  61424. #endif
  61425. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  61426. pNC->ncFlags &= ~NC_HasAgg;
  61427. memset(&w, 0, sizeof(w));
  61428. w.xExprCallback = resolveExprStep;
  61429. w.xSelectCallback = resolveSelectStep;
  61430. w.pParse = pNC->pParse;
  61431. w.u.pNC = pNC;
  61432. sqlite3WalkExpr(&w, pExpr);
  61433. #if SQLITE_MAX_EXPR_DEPTH>0
  61434. pNC->pParse->nHeight -= pExpr->nHeight;
  61435. #endif
  61436. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  61437. ExprSetProperty(pExpr, EP_Error);
  61438. }
  61439. if( pNC->ncFlags & NC_HasAgg ){
  61440. ExprSetProperty(pExpr, EP_Agg);
  61441. }else if( savedHasAgg ){
  61442. pNC->ncFlags |= NC_HasAgg;
  61443. }
  61444. return ExprHasProperty(pExpr, EP_Error);
  61445. }
  61446. /*
  61447. ** Resolve all names in all expressions of a SELECT and in all
  61448. ** decendents of the SELECT, including compounds off of p->pPrior,
  61449. ** subqueries in expressions, and subqueries used as FROM clause
  61450. ** terms.
  61451. **
  61452. ** See sqlite3ResolveExprNames() for a description of the kinds of
  61453. ** transformations that occur.
  61454. **
  61455. ** All SELECT statements should have been expanded using
  61456. ** sqlite3SelectExpand() prior to invoking this routine.
  61457. */
  61458. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  61459. Parse *pParse, /* The parser context */
  61460. Select *p, /* The SELECT statement being coded. */
  61461. NameContext *pOuterNC /* Name context for parent SELECT statement */
  61462. ){
  61463. Walker w;
  61464. assert( p!=0 );
  61465. memset(&w, 0, sizeof(w));
  61466. w.xExprCallback = resolveExprStep;
  61467. w.xSelectCallback = resolveSelectStep;
  61468. w.pParse = pParse;
  61469. w.u.pNC = pOuterNC;
  61470. sqlite3WalkSelect(&w, p);
  61471. }
  61472. /*
  61473. ** Resolve names in expressions that can only reference a single table:
  61474. **
  61475. ** * CHECK constraints
  61476. ** * WHERE clauses on partial indices
  61477. **
  61478. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  61479. ** is set to -1 and the Expr.iColumn value is set to the column number.
  61480. **
  61481. ** Any errors cause an error message to be set in pParse.
  61482. */
  61483. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  61484. Parse *pParse, /* Parsing context */
  61485. Table *pTab, /* The table being referenced */
  61486. int type, /* NC_IsCheck or NC_PartIdx */
  61487. Expr *pExpr, /* Expression to resolve. May be NULL. */
  61488. ExprList *pList /* Expression list to resolve. May be NUL. */
  61489. ){
  61490. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  61491. NameContext sNC; /* Name context for pParse->pNewTable */
  61492. int i; /* Loop counter */
  61493. assert( type==NC_IsCheck || type==NC_PartIdx );
  61494. memset(&sNC, 0, sizeof(sNC));
  61495. memset(&sSrc, 0, sizeof(sSrc));
  61496. sSrc.nSrc = 1;
  61497. sSrc.a[0].zName = pTab->zName;
  61498. sSrc.a[0].pTab = pTab;
  61499. sSrc.a[0].iCursor = -1;
  61500. sNC.pParse = pParse;
  61501. sNC.pSrcList = &sSrc;
  61502. sNC.ncFlags = type;
  61503. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  61504. if( pList ){
  61505. for(i=0; i<pList->nExpr; i++){
  61506. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  61507. return;
  61508. }
  61509. }
  61510. }
  61511. }
  61512. /************** End of resolve.c *********************************************/
  61513. /************** Begin file expr.c ********************************************/
  61514. /*
  61515. ** 2001 September 15
  61516. **
  61517. ** The author disclaims copyright to this source code. In place of
  61518. ** a legal notice, here is a blessing:
  61519. **
  61520. ** May you do good and not evil.
  61521. ** May you find forgiveness for yourself and forgive others.
  61522. ** May you share freely, never taking more than you give.
  61523. **
  61524. *************************************************************************
  61525. ** This file contains routines used for analyzing expressions and
  61526. ** for generating VDBE code that evaluates expressions in SQLite.
  61527. */
  61528. /*
  61529. ** Return the 'affinity' of the expression pExpr if any.
  61530. **
  61531. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  61532. ** or a sub-select with a column as the return value, then the
  61533. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  61534. ** indicating no affinity for the expression.
  61535. **
  61536. ** i.e. the WHERE clause expresssions in the following statements all
  61537. ** have an affinity:
  61538. **
  61539. ** CREATE TABLE t1(a);
  61540. ** SELECT * FROM t1 WHERE a;
  61541. ** SELECT a AS b FROM t1 WHERE b;
  61542. ** SELECT * FROM t1 WHERE (select a from t1);
  61543. */
  61544. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  61545. int op;
  61546. pExpr = sqlite3ExprSkipCollate(pExpr);
  61547. op = pExpr->op;
  61548. if( op==TK_SELECT ){
  61549. assert( pExpr->flags&EP_xIsSelect );
  61550. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  61551. }
  61552. #ifndef SQLITE_OMIT_CAST
  61553. if( op==TK_CAST ){
  61554. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  61555. return sqlite3AffinityType(pExpr->u.zToken, 0);
  61556. }
  61557. #endif
  61558. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  61559. && pExpr->pTab!=0
  61560. ){
  61561. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  61562. ** a TK_COLUMN but was previously evaluated and cached in a register */
  61563. int j = pExpr->iColumn;
  61564. if( j<0 ) return SQLITE_AFF_INTEGER;
  61565. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  61566. return pExpr->pTab->aCol[j].affinity;
  61567. }
  61568. return pExpr->affinity;
  61569. }
  61570. /*
  61571. ** Set the collating sequence for expression pExpr to be the collating
  61572. ** sequence named by pToken. Return a pointer to a new Expr node that
  61573. ** implements the COLLATE operator.
  61574. **
  61575. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  61576. ** and the pExpr parameter is returned unchanged.
  61577. */
  61578. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  61579. if( pCollName->n>0 ){
  61580. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  61581. if( pNew ){
  61582. pNew->pLeft = pExpr;
  61583. pNew->flags |= EP_Collate|EP_Skip;
  61584. pExpr = pNew;
  61585. }
  61586. }
  61587. return pExpr;
  61588. }
  61589. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  61590. Token s;
  61591. assert( zC!=0 );
  61592. s.z = zC;
  61593. s.n = sqlite3Strlen30(s.z);
  61594. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  61595. }
  61596. /*
  61597. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  61598. ** or likelihood() function at the root of an expression.
  61599. */
  61600. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  61601. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  61602. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  61603. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  61604. assert( pExpr->x.pList->nExpr>0 );
  61605. assert( pExpr->op==TK_FUNCTION );
  61606. pExpr = pExpr->x.pList->a[0].pExpr;
  61607. }else{
  61608. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  61609. pExpr = pExpr->pLeft;
  61610. }
  61611. }
  61612. return pExpr;
  61613. }
  61614. /*
  61615. ** Return the collation sequence for the expression pExpr. If
  61616. ** there is no defined collating sequence, return NULL.
  61617. **
  61618. ** The collating sequence might be determined by a COLLATE operator
  61619. ** or by the presence of a column with a defined collating sequence.
  61620. ** COLLATE operators take first precedence. Left operands take
  61621. ** precedence over right operands.
  61622. */
  61623. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  61624. sqlite3 *db = pParse->db;
  61625. CollSeq *pColl = 0;
  61626. Expr *p = pExpr;
  61627. while( p ){
  61628. int op = p->op;
  61629. if( op==TK_CAST || op==TK_UPLUS ){
  61630. p = p->pLeft;
  61631. continue;
  61632. }
  61633. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  61634. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  61635. break;
  61636. }
  61637. if( p->pTab!=0
  61638. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  61639. || op==TK_REGISTER || op==TK_TRIGGER)
  61640. ){
  61641. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  61642. ** a TK_COLUMN but was previously evaluated and cached in a register */
  61643. int j = p->iColumn;
  61644. if( j>=0 ){
  61645. const char *zColl = p->pTab->aCol[j].zColl;
  61646. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  61647. }
  61648. break;
  61649. }
  61650. if( p->flags & EP_Collate ){
  61651. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  61652. p = p->pLeft;
  61653. }else{
  61654. p = p->pRight;
  61655. }
  61656. }else{
  61657. break;
  61658. }
  61659. }
  61660. if( sqlite3CheckCollSeq(pParse, pColl) ){
  61661. pColl = 0;
  61662. }
  61663. return pColl;
  61664. }
  61665. /*
  61666. ** pExpr is an operand of a comparison operator. aff2 is the
  61667. ** type affinity of the other operand. This routine returns the
  61668. ** type affinity that should be used for the comparison operator.
  61669. */
  61670. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  61671. char aff1 = sqlite3ExprAffinity(pExpr);
  61672. if( aff1 && aff2 ){
  61673. /* Both sides of the comparison are columns. If one has numeric
  61674. ** affinity, use that. Otherwise use no affinity.
  61675. */
  61676. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  61677. return SQLITE_AFF_NUMERIC;
  61678. }else{
  61679. return SQLITE_AFF_NONE;
  61680. }
  61681. }else if( !aff1 && !aff2 ){
  61682. /* Neither side of the comparison is a column. Compare the
  61683. ** results directly.
  61684. */
  61685. return SQLITE_AFF_NONE;
  61686. }else{
  61687. /* One side is a column, the other is not. Use the columns affinity. */
  61688. assert( aff1==0 || aff2==0 );
  61689. return (aff1 + aff2);
  61690. }
  61691. }
  61692. /*
  61693. ** pExpr is a comparison operator. Return the type affinity that should
  61694. ** be applied to both operands prior to doing the comparison.
  61695. */
  61696. static char comparisonAffinity(Expr *pExpr){
  61697. char aff;
  61698. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  61699. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  61700. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  61701. assert( pExpr->pLeft );
  61702. aff = sqlite3ExprAffinity(pExpr->pLeft);
  61703. if( pExpr->pRight ){
  61704. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  61705. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  61706. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  61707. }else if( !aff ){
  61708. aff = SQLITE_AFF_NONE;
  61709. }
  61710. return aff;
  61711. }
  61712. /*
  61713. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  61714. ** idx_affinity is the affinity of an indexed column. Return true
  61715. ** if the index with affinity idx_affinity may be used to implement
  61716. ** the comparison in pExpr.
  61717. */
  61718. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  61719. char aff = comparisonAffinity(pExpr);
  61720. switch( aff ){
  61721. case SQLITE_AFF_NONE:
  61722. return 1;
  61723. case SQLITE_AFF_TEXT:
  61724. return idx_affinity==SQLITE_AFF_TEXT;
  61725. default:
  61726. return sqlite3IsNumericAffinity(idx_affinity);
  61727. }
  61728. }
  61729. /*
  61730. ** Return the P5 value that should be used for a binary comparison
  61731. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  61732. */
  61733. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  61734. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  61735. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  61736. return aff;
  61737. }
  61738. /*
  61739. ** Return a pointer to the collation sequence that should be used by
  61740. ** a binary comparison operator comparing pLeft and pRight.
  61741. **
  61742. ** If the left hand expression has a collating sequence type, then it is
  61743. ** used. Otherwise the collation sequence for the right hand expression
  61744. ** is used, or the default (BINARY) if neither expression has a collating
  61745. ** type.
  61746. **
  61747. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  61748. ** it is not considered.
  61749. */
  61750. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  61751. Parse *pParse,
  61752. Expr *pLeft,
  61753. Expr *pRight
  61754. ){
  61755. CollSeq *pColl;
  61756. assert( pLeft );
  61757. if( pLeft->flags & EP_Collate ){
  61758. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  61759. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  61760. pColl = sqlite3ExprCollSeq(pParse, pRight);
  61761. }else{
  61762. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  61763. if( !pColl ){
  61764. pColl = sqlite3ExprCollSeq(pParse, pRight);
  61765. }
  61766. }
  61767. return pColl;
  61768. }
  61769. /*
  61770. ** Generate code for a comparison operator.
  61771. */
  61772. static int codeCompare(
  61773. Parse *pParse, /* The parsing (and code generating) context */
  61774. Expr *pLeft, /* The left operand */
  61775. Expr *pRight, /* The right operand */
  61776. int opcode, /* The comparison opcode */
  61777. int in1, int in2, /* Register holding operands */
  61778. int dest, /* Jump here if true. */
  61779. int jumpIfNull /* If true, jump if either operand is NULL */
  61780. ){
  61781. int p5;
  61782. int addr;
  61783. CollSeq *p4;
  61784. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  61785. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  61786. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  61787. (void*)p4, P4_COLLSEQ);
  61788. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  61789. return addr;
  61790. }
  61791. #if SQLITE_MAX_EXPR_DEPTH>0
  61792. /*
  61793. ** Check that argument nHeight is less than or equal to the maximum
  61794. ** expression depth allowed. If it is not, leave an error message in
  61795. ** pParse.
  61796. */
  61797. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  61798. int rc = SQLITE_OK;
  61799. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  61800. if( nHeight>mxHeight ){
  61801. sqlite3ErrorMsg(pParse,
  61802. "Expression tree is too large (maximum depth %d)", mxHeight
  61803. );
  61804. rc = SQLITE_ERROR;
  61805. }
  61806. return rc;
  61807. }
  61808. /* The following three functions, heightOfExpr(), heightOfExprList()
  61809. ** and heightOfSelect(), are used to determine the maximum height
  61810. ** of any expression tree referenced by the structure passed as the
  61811. ** first argument.
  61812. **
  61813. ** If this maximum height is greater than the current value pointed
  61814. ** to by pnHeight, the second parameter, then set *pnHeight to that
  61815. ** value.
  61816. */
  61817. static void heightOfExpr(Expr *p, int *pnHeight){
  61818. if( p ){
  61819. if( p->nHeight>*pnHeight ){
  61820. *pnHeight = p->nHeight;
  61821. }
  61822. }
  61823. }
  61824. static void heightOfExprList(ExprList *p, int *pnHeight){
  61825. if( p ){
  61826. int i;
  61827. for(i=0; i<p->nExpr; i++){
  61828. heightOfExpr(p->a[i].pExpr, pnHeight);
  61829. }
  61830. }
  61831. }
  61832. static void heightOfSelect(Select *p, int *pnHeight){
  61833. if( p ){
  61834. heightOfExpr(p->pWhere, pnHeight);
  61835. heightOfExpr(p->pHaving, pnHeight);
  61836. heightOfExpr(p->pLimit, pnHeight);
  61837. heightOfExpr(p->pOffset, pnHeight);
  61838. heightOfExprList(p->pEList, pnHeight);
  61839. heightOfExprList(p->pGroupBy, pnHeight);
  61840. heightOfExprList(p->pOrderBy, pnHeight);
  61841. heightOfSelect(p->pPrior, pnHeight);
  61842. }
  61843. }
  61844. /*
  61845. ** Set the Expr.nHeight variable in the structure passed as an
  61846. ** argument. An expression with no children, Expr.pList or
  61847. ** Expr.pSelect member has a height of 1. Any other expression
  61848. ** has a height equal to the maximum height of any other
  61849. ** referenced Expr plus one.
  61850. */
  61851. static void exprSetHeight(Expr *p){
  61852. int nHeight = 0;
  61853. heightOfExpr(p->pLeft, &nHeight);
  61854. heightOfExpr(p->pRight, &nHeight);
  61855. if( ExprHasProperty(p, EP_xIsSelect) ){
  61856. heightOfSelect(p->x.pSelect, &nHeight);
  61857. }else{
  61858. heightOfExprList(p->x.pList, &nHeight);
  61859. }
  61860. p->nHeight = nHeight + 1;
  61861. }
  61862. /*
  61863. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  61864. ** the height is greater than the maximum allowed expression depth,
  61865. ** leave an error in pParse.
  61866. */
  61867. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  61868. exprSetHeight(p);
  61869. sqlite3ExprCheckHeight(pParse, p->nHeight);
  61870. }
  61871. /*
  61872. ** Return the maximum height of any expression tree referenced
  61873. ** by the select statement passed as an argument.
  61874. */
  61875. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  61876. int nHeight = 0;
  61877. heightOfSelect(p, &nHeight);
  61878. return nHeight;
  61879. }
  61880. #else
  61881. #define exprSetHeight(y)
  61882. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  61883. /*
  61884. ** This routine is the core allocator for Expr nodes.
  61885. **
  61886. ** Construct a new expression node and return a pointer to it. Memory
  61887. ** for this node and for the pToken argument is a single allocation
  61888. ** obtained from sqlite3DbMalloc(). The calling function
  61889. ** is responsible for making sure the node eventually gets freed.
  61890. **
  61891. ** If dequote is true, then the token (if it exists) is dequoted.
  61892. ** If dequote is false, no dequoting is performance. The deQuote
  61893. ** parameter is ignored if pToken is NULL or if the token does not
  61894. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  61895. ** then the EP_DblQuoted flag is set on the expression node.
  61896. **
  61897. ** Special case: If op==TK_INTEGER and pToken points to a string that
  61898. ** can be translated into a 32-bit integer, then the token is not
  61899. ** stored in u.zToken. Instead, the integer values is written
  61900. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  61901. ** is allocated to hold the integer text and the dequote flag is ignored.
  61902. */
  61903. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  61904. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  61905. int op, /* Expression opcode */
  61906. const Token *pToken, /* Token argument. Might be NULL */
  61907. int dequote /* True to dequote */
  61908. ){
  61909. Expr *pNew;
  61910. int nExtra = 0;
  61911. int iValue = 0;
  61912. if( pToken ){
  61913. if( op!=TK_INTEGER || pToken->z==0
  61914. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  61915. nExtra = pToken->n+1;
  61916. assert( iValue>=0 );
  61917. }
  61918. }
  61919. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  61920. if( pNew ){
  61921. pNew->op = (u8)op;
  61922. pNew->iAgg = -1;
  61923. if( pToken ){
  61924. if( nExtra==0 ){
  61925. pNew->flags |= EP_IntValue;
  61926. pNew->u.iValue = iValue;
  61927. }else{
  61928. int c;
  61929. pNew->u.zToken = (char*)&pNew[1];
  61930. assert( pToken->z!=0 || pToken->n==0 );
  61931. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  61932. pNew->u.zToken[pToken->n] = 0;
  61933. if( dequote && nExtra>=3
  61934. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  61935. sqlite3Dequote(pNew->u.zToken);
  61936. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  61937. }
  61938. }
  61939. }
  61940. #if SQLITE_MAX_EXPR_DEPTH>0
  61941. pNew->nHeight = 1;
  61942. #endif
  61943. }
  61944. return pNew;
  61945. }
  61946. /*
  61947. ** Allocate a new expression node from a zero-terminated token that has
  61948. ** already been dequoted.
  61949. */
  61950. SQLITE_PRIVATE Expr *sqlite3Expr(
  61951. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  61952. int op, /* Expression opcode */
  61953. const char *zToken /* Token argument. Might be NULL */
  61954. ){
  61955. Token x;
  61956. x.z = zToken;
  61957. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  61958. return sqlite3ExprAlloc(db, op, &x, 0);
  61959. }
  61960. /*
  61961. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  61962. **
  61963. ** If pRoot==NULL that means that a memory allocation error has occurred.
  61964. ** In that case, delete the subtrees pLeft and pRight.
  61965. */
  61966. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  61967. sqlite3 *db,
  61968. Expr *pRoot,
  61969. Expr *pLeft,
  61970. Expr *pRight
  61971. ){
  61972. if( pRoot==0 ){
  61973. assert( db->mallocFailed );
  61974. sqlite3ExprDelete(db, pLeft);
  61975. sqlite3ExprDelete(db, pRight);
  61976. }else{
  61977. if( pRight ){
  61978. pRoot->pRight = pRight;
  61979. pRoot->flags |= EP_Collate & pRight->flags;
  61980. }
  61981. if( pLeft ){
  61982. pRoot->pLeft = pLeft;
  61983. pRoot->flags |= EP_Collate & pLeft->flags;
  61984. }
  61985. exprSetHeight(pRoot);
  61986. }
  61987. }
  61988. /*
  61989. ** Allocate a Expr node which joins as many as two subtrees.
  61990. **
  61991. ** One or both of the subtrees can be NULL. Return a pointer to the new
  61992. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  61993. ** free the subtrees and return NULL.
  61994. */
  61995. SQLITE_PRIVATE Expr *sqlite3PExpr(
  61996. Parse *pParse, /* Parsing context */
  61997. int op, /* Expression opcode */
  61998. Expr *pLeft, /* Left operand */
  61999. Expr *pRight, /* Right operand */
  62000. const Token *pToken /* Argument token */
  62001. ){
  62002. Expr *p;
  62003. if( op==TK_AND && pLeft && pRight ){
  62004. /* Take advantage of short-circuit false optimization for AND */
  62005. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  62006. }else{
  62007. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  62008. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  62009. }
  62010. if( p ) {
  62011. sqlite3ExprCheckHeight(pParse, p->nHeight);
  62012. }
  62013. return p;
  62014. }
  62015. /*
  62016. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  62017. ** expression might be true. This is an optimization. If is OK to
  62018. ** return 0 here even if the expression really is always false (a
  62019. ** false negative). But it is a bug to return 1 if the expression
  62020. ** might be true in some rare circumstances (a false positive.)
  62021. **
  62022. ** Note that if the expression is part of conditional for a
  62023. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  62024. ** is it true or false, so always return 0.
  62025. */
  62026. static int exprAlwaysFalse(Expr *p){
  62027. int v = 0;
  62028. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  62029. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  62030. return v==0;
  62031. }
  62032. /*
  62033. ** Join two expressions using an AND operator. If either expression is
  62034. ** NULL, then just return the other expression.
  62035. **
  62036. ** If one side or the other of the AND is known to be false, then instead
  62037. ** of returning an AND expression, just return a constant expression with
  62038. ** a value of false.
  62039. */
  62040. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  62041. if( pLeft==0 ){
  62042. return pRight;
  62043. }else if( pRight==0 ){
  62044. return pLeft;
  62045. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  62046. sqlite3ExprDelete(db, pLeft);
  62047. sqlite3ExprDelete(db, pRight);
  62048. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  62049. }else{
  62050. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  62051. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  62052. return pNew;
  62053. }
  62054. }
  62055. /*
  62056. ** Construct a new expression node for a function with multiple
  62057. ** arguments.
  62058. */
  62059. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  62060. Expr *pNew;
  62061. sqlite3 *db = pParse->db;
  62062. assert( pToken );
  62063. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  62064. if( pNew==0 ){
  62065. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  62066. return 0;
  62067. }
  62068. pNew->x.pList = pList;
  62069. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  62070. sqlite3ExprSetHeight(pParse, pNew);
  62071. return pNew;
  62072. }
  62073. /*
  62074. ** Assign a variable number to an expression that encodes a wildcard
  62075. ** in the original SQL statement.
  62076. **
  62077. ** Wildcards consisting of a single "?" are assigned the next sequential
  62078. ** variable number.
  62079. **
  62080. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  62081. ** sure "nnn" is not too be to avoid a denial of service attack when
  62082. ** the SQL statement comes from an external source.
  62083. **
  62084. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  62085. ** as the previous instance of the same wildcard. Or if this is the first
  62086. ** instance of the wildcard, the next sequenial variable number is
  62087. ** assigned.
  62088. */
  62089. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  62090. sqlite3 *db = pParse->db;
  62091. const char *z;
  62092. if( pExpr==0 ) return;
  62093. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  62094. z = pExpr->u.zToken;
  62095. assert( z!=0 );
  62096. assert( z[0]!=0 );
  62097. if( z[1]==0 ){
  62098. /* Wildcard of the form "?". Assign the next variable number */
  62099. assert( z[0]=='?' );
  62100. pExpr->iColumn = (ynVar)(++pParse->nVar);
  62101. }else{
  62102. ynVar x = 0;
  62103. u32 n = sqlite3Strlen30(z);
  62104. if( z[0]=='?' ){
  62105. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  62106. ** use it as the variable number */
  62107. i64 i;
  62108. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  62109. pExpr->iColumn = x = (ynVar)i;
  62110. testcase( i==0 );
  62111. testcase( i==1 );
  62112. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  62113. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  62114. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  62115. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  62116. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  62117. x = 0;
  62118. }
  62119. if( i>pParse->nVar ){
  62120. pParse->nVar = (int)i;
  62121. }
  62122. }else{
  62123. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  62124. ** number as the prior appearance of the same name, or if the name
  62125. ** has never appeared before, reuse the same variable number
  62126. */
  62127. ynVar i;
  62128. for(i=0; i<pParse->nzVar; i++){
  62129. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  62130. pExpr->iColumn = x = (ynVar)i+1;
  62131. break;
  62132. }
  62133. }
  62134. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  62135. }
  62136. if( x>0 ){
  62137. if( x>pParse->nzVar ){
  62138. char **a;
  62139. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  62140. if( a==0 ) return; /* Error reported through db->mallocFailed */
  62141. pParse->azVar = a;
  62142. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  62143. pParse->nzVar = x;
  62144. }
  62145. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  62146. sqlite3DbFree(db, pParse->azVar[x-1]);
  62147. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  62148. }
  62149. }
  62150. }
  62151. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  62152. sqlite3ErrorMsg(pParse, "too many SQL variables");
  62153. }
  62154. }
  62155. /*
  62156. ** Recursively delete an expression tree.
  62157. */
  62158. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  62159. if( p==0 ) return;
  62160. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  62161. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  62162. if( !ExprHasProperty(p, EP_TokenOnly) ){
  62163. /* The Expr.x union is never used at the same time as Expr.pRight */
  62164. assert( p->x.pList==0 || p->pRight==0 );
  62165. sqlite3ExprDelete(db, p->pLeft);
  62166. sqlite3ExprDelete(db, p->pRight);
  62167. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  62168. if( ExprHasProperty(p, EP_xIsSelect) ){
  62169. sqlite3SelectDelete(db, p->x.pSelect);
  62170. }else{
  62171. sqlite3ExprListDelete(db, p->x.pList);
  62172. }
  62173. }
  62174. if( !ExprHasProperty(p, EP_Static) ){
  62175. sqlite3DbFree(db, p);
  62176. }
  62177. }
  62178. /*
  62179. ** Return the number of bytes allocated for the expression structure
  62180. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  62181. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  62182. */
  62183. static int exprStructSize(Expr *p){
  62184. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  62185. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  62186. return EXPR_FULLSIZE;
  62187. }
  62188. /*
  62189. ** The dupedExpr*Size() routines each return the number of bytes required
  62190. ** to store a copy of an expression or expression tree. They differ in
  62191. ** how much of the tree is measured.
  62192. **
  62193. ** dupedExprStructSize() Size of only the Expr structure
  62194. ** dupedExprNodeSize() Size of Expr + space for token
  62195. ** dupedExprSize() Expr + token + subtree components
  62196. **
  62197. ***************************************************************************
  62198. **
  62199. ** The dupedExprStructSize() function returns two values OR-ed together:
  62200. ** (1) the space required for a copy of the Expr structure only and
  62201. ** (2) the EP_xxx flags that indicate what the structure size should be.
  62202. ** The return values is always one of:
  62203. **
  62204. ** EXPR_FULLSIZE
  62205. ** EXPR_REDUCEDSIZE | EP_Reduced
  62206. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  62207. **
  62208. ** The size of the structure can be found by masking the return value
  62209. ** of this routine with 0xfff. The flags can be found by masking the
  62210. ** return value with EP_Reduced|EP_TokenOnly.
  62211. **
  62212. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  62213. ** (unreduced) Expr objects as they or originally constructed by the parser.
  62214. ** During expression analysis, extra information is computed and moved into
  62215. ** later parts of teh Expr object and that extra information might get chopped
  62216. ** off if the expression is reduced. Note also that it does not work to
  62217. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  62218. ** to reduce a pristine expression tree from the parser. The implementation
  62219. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  62220. ** to enforce this constraint.
  62221. */
  62222. static int dupedExprStructSize(Expr *p, int flags){
  62223. int nSize;
  62224. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  62225. assert( EXPR_FULLSIZE<=0xfff );
  62226. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  62227. if( 0==(flags&EXPRDUP_REDUCE) ){
  62228. nSize = EXPR_FULLSIZE;
  62229. }else{
  62230. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  62231. assert( !ExprHasProperty(p, EP_FromJoin) );
  62232. assert( !ExprHasProperty(p, EP_MemToken) );
  62233. assert( !ExprHasProperty(p, EP_NoReduce) );
  62234. if( p->pLeft || p->x.pList ){
  62235. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  62236. }else{
  62237. assert( p->pRight==0 );
  62238. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  62239. }
  62240. }
  62241. return nSize;
  62242. }
  62243. /*
  62244. ** This function returns the space in bytes required to store the copy
  62245. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  62246. ** string is defined.)
  62247. */
  62248. static int dupedExprNodeSize(Expr *p, int flags){
  62249. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  62250. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  62251. nByte += sqlite3Strlen30(p->u.zToken)+1;
  62252. }
  62253. return ROUND8(nByte);
  62254. }
  62255. /*
  62256. ** Return the number of bytes required to create a duplicate of the
  62257. ** expression passed as the first argument. The second argument is a
  62258. ** mask containing EXPRDUP_XXX flags.
  62259. **
  62260. ** The value returned includes space to create a copy of the Expr struct
  62261. ** itself and the buffer referred to by Expr.u.zToken, if any.
  62262. **
  62263. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  62264. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  62265. ** and Expr.pRight variables (but not for any structures pointed to or
  62266. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  62267. */
  62268. static int dupedExprSize(Expr *p, int flags){
  62269. int nByte = 0;
  62270. if( p ){
  62271. nByte = dupedExprNodeSize(p, flags);
  62272. if( flags&EXPRDUP_REDUCE ){
  62273. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  62274. }
  62275. }
  62276. return nByte;
  62277. }
  62278. /*
  62279. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  62280. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  62281. ** to store the copy of expression p, the copies of p->u.zToken
  62282. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  62283. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  62284. ** portion of the buffer copied into by this function.
  62285. */
  62286. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  62287. Expr *pNew = 0; /* Value to return */
  62288. if( p ){
  62289. const int isReduced = (flags&EXPRDUP_REDUCE);
  62290. u8 *zAlloc;
  62291. u32 staticFlag = 0;
  62292. assert( pzBuffer==0 || isReduced );
  62293. /* Figure out where to write the new Expr structure. */
  62294. if( pzBuffer ){
  62295. zAlloc = *pzBuffer;
  62296. staticFlag = EP_Static;
  62297. }else{
  62298. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  62299. }
  62300. pNew = (Expr *)zAlloc;
  62301. if( pNew ){
  62302. /* Set nNewSize to the size allocated for the structure pointed to
  62303. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  62304. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  62305. ** by the copy of the p->u.zToken string (if any).
  62306. */
  62307. const unsigned nStructSize = dupedExprStructSize(p, flags);
  62308. const int nNewSize = nStructSize & 0xfff;
  62309. int nToken;
  62310. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  62311. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  62312. }else{
  62313. nToken = 0;
  62314. }
  62315. if( isReduced ){
  62316. assert( ExprHasProperty(p, EP_Reduced)==0 );
  62317. memcpy(zAlloc, p, nNewSize);
  62318. }else{
  62319. int nSize = exprStructSize(p);
  62320. memcpy(zAlloc, p, nSize);
  62321. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  62322. }
  62323. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  62324. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  62325. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  62326. pNew->flags |= staticFlag;
  62327. /* Copy the p->u.zToken string, if any. */
  62328. if( nToken ){
  62329. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  62330. memcpy(zToken, p->u.zToken, nToken);
  62331. }
  62332. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  62333. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  62334. if( ExprHasProperty(p, EP_xIsSelect) ){
  62335. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  62336. }else{
  62337. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  62338. }
  62339. }
  62340. /* Fill in pNew->pLeft and pNew->pRight. */
  62341. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  62342. zAlloc += dupedExprNodeSize(p, flags);
  62343. if( ExprHasProperty(pNew, EP_Reduced) ){
  62344. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  62345. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  62346. }
  62347. if( pzBuffer ){
  62348. *pzBuffer = zAlloc;
  62349. }
  62350. }else{
  62351. if( !ExprHasProperty(p, EP_TokenOnly) ){
  62352. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  62353. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  62354. }
  62355. }
  62356. }
  62357. }
  62358. return pNew;
  62359. }
  62360. /*
  62361. ** The following group of routines make deep copies of expressions,
  62362. ** expression lists, ID lists, and select statements. The copies can
  62363. ** be deleted (by being passed to their respective ...Delete() routines)
  62364. ** without effecting the originals.
  62365. **
  62366. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  62367. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  62368. ** by subsequent calls to sqlite*ListAppend() routines.
  62369. **
  62370. ** Any tables that the SrcList might point to are not duplicated.
  62371. **
  62372. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  62373. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  62374. ** truncated version of the usual Expr structure that will be stored as
  62375. ** part of the in-memory representation of the database schema.
  62376. */
  62377. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  62378. return exprDup(db, p, flags, 0);
  62379. }
  62380. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  62381. ExprList *pNew;
  62382. struct ExprList_item *pItem, *pOldItem;
  62383. int i;
  62384. if( p==0 ) return 0;
  62385. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  62386. if( pNew==0 ) return 0;
  62387. pNew->iECursor = 0;
  62388. pNew->nExpr = i = p->nExpr;
  62389. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  62390. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  62391. if( pItem==0 ){
  62392. sqlite3DbFree(db, pNew);
  62393. return 0;
  62394. }
  62395. pOldItem = p->a;
  62396. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  62397. Expr *pOldExpr = pOldItem->pExpr;
  62398. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  62399. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62400. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  62401. pItem->sortOrder = pOldItem->sortOrder;
  62402. pItem->done = 0;
  62403. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  62404. pItem->iOrderByCol = pOldItem->iOrderByCol;
  62405. pItem->iAlias = pOldItem->iAlias;
  62406. }
  62407. return pNew;
  62408. }
  62409. /*
  62410. ** If cursors, triggers, views and subqueries are all omitted from
  62411. ** the build, then none of the following routines, except for
  62412. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  62413. ** called with a NULL argument.
  62414. */
  62415. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  62416. || !defined(SQLITE_OMIT_SUBQUERY)
  62417. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  62418. SrcList *pNew;
  62419. int i;
  62420. int nByte;
  62421. if( p==0 ) return 0;
  62422. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  62423. pNew = sqlite3DbMallocRaw(db, nByte );
  62424. if( pNew==0 ) return 0;
  62425. pNew->nSrc = pNew->nAlloc = p->nSrc;
  62426. for(i=0; i<p->nSrc; i++){
  62427. struct SrcList_item *pNewItem = &pNew->a[i];
  62428. struct SrcList_item *pOldItem = &p->a[i];
  62429. Table *pTab;
  62430. pNewItem->pSchema = pOldItem->pSchema;
  62431. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  62432. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62433. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  62434. pNewItem->jointype = pOldItem->jointype;
  62435. pNewItem->iCursor = pOldItem->iCursor;
  62436. pNewItem->addrFillSub = pOldItem->addrFillSub;
  62437. pNewItem->regReturn = pOldItem->regReturn;
  62438. pNewItem->isCorrelated = pOldItem->isCorrelated;
  62439. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  62440. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  62441. pNewItem->notIndexed = pOldItem->notIndexed;
  62442. pNewItem->pIndex = pOldItem->pIndex;
  62443. pTab = pNewItem->pTab = pOldItem->pTab;
  62444. if( pTab ){
  62445. pTab->nRef++;
  62446. }
  62447. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  62448. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  62449. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  62450. pNewItem->colUsed = pOldItem->colUsed;
  62451. }
  62452. return pNew;
  62453. }
  62454. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  62455. IdList *pNew;
  62456. int i;
  62457. if( p==0 ) return 0;
  62458. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  62459. if( pNew==0 ) return 0;
  62460. pNew->nId = p->nId;
  62461. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  62462. if( pNew->a==0 ){
  62463. sqlite3DbFree(db, pNew);
  62464. return 0;
  62465. }
  62466. /* Note that because the size of the allocation for p->a[] is not
  62467. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  62468. ** on the duplicate created by this function. */
  62469. for(i=0; i<p->nId; i++){
  62470. struct IdList_item *pNewItem = &pNew->a[i];
  62471. struct IdList_item *pOldItem = &p->a[i];
  62472. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62473. pNewItem->idx = pOldItem->idx;
  62474. }
  62475. return pNew;
  62476. }
  62477. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  62478. Select *pNew, *pPrior;
  62479. if( p==0 ) return 0;
  62480. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  62481. if( pNew==0 ) return 0;
  62482. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  62483. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  62484. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  62485. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  62486. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  62487. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  62488. pNew->op = p->op;
  62489. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  62490. if( pPrior ) pPrior->pNext = pNew;
  62491. pNew->pNext = 0;
  62492. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  62493. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  62494. pNew->iLimit = 0;
  62495. pNew->iOffset = 0;
  62496. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  62497. pNew->pRightmost = 0;
  62498. pNew->addrOpenEphm[0] = -1;
  62499. pNew->addrOpenEphm[1] = -1;
  62500. pNew->addrOpenEphm[2] = -1;
  62501. return pNew;
  62502. }
  62503. #else
  62504. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  62505. assert( p==0 );
  62506. return 0;
  62507. }
  62508. #endif
  62509. /*
  62510. ** Add a new element to the end of an expression list. If pList is
  62511. ** initially NULL, then create a new expression list.
  62512. **
  62513. ** If a memory allocation error occurs, the entire list is freed and
  62514. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  62515. ** that the new entry was successfully appended.
  62516. */
  62517. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  62518. Parse *pParse, /* Parsing context */
  62519. ExprList *pList, /* List to which to append. Might be NULL */
  62520. Expr *pExpr /* Expression to be appended. Might be NULL */
  62521. ){
  62522. sqlite3 *db = pParse->db;
  62523. if( pList==0 ){
  62524. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  62525. if( pList==0 ){
  62526. goto no_mem;
  62527. }
  62528. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  62529. if( pList->a==0 ) goto no_mem;
  62530. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  62531. struct ExprList_item *a;
  62532. assert( pList->nExpr>0 );
  62533. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  62534. if( a==0 ){
  62535. goto no_mem;
  62536. }
  62537. pList->a = a;
  62538. }
  62539. assert( pList->a!=0 );
  62540. if( 1 ){
  62541. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  62542. memset(pItem, 0, sizeof(*pItem));
  62543. pItem->pExpr = pExpr;
  62544. }
  62545. return pList;
  62546. no_mem:
  62547. /* Avoid leaking memory if malloc has failed. */
  62548. sqlite3ExprDelete(db, pExpr);
  62549. sqlite3ExprListDelete(db, pList);
  62550. return 0;
  62551. }
  62552. /*
  62553. ** Set the ExprList.a[].zName element of the most recently added item
  62554. ** on the expression list.
  62555. **
  62556. ** pList might be NULL following an OOM error. But pName should never be
  62557. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  62558. ** is set.
  62559. */
  62560. SQLITE_PRIVATE void sqlite3ExprListSetName(
  62561. Parse *pParse, /* Parsing context */
  62562. ExprList *pList, /* List to which to add the span. */
  62563. Token *pName, /* Name to be added */
  62564. int dequote /* True to cause the name to be dequoted */
  62565. ){
  62566. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  62567. if( pList ){
  62568. struct ExprList_item *pItem;
  62569. assert( pList->nExpr>0 );
  62570. pItem = &pList->a[pList->nExpr-1];
  62571. assert( pItem->zName==0 );
  62572. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  62573. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  62574. }
  62575. }
  62576. /*
  62577. ** Set the ExprList.a[].zSpan element of the most recently added item
  62578. ** on the expression list.
  62579. **
  62580. ** pList might be NULL following an OOM error. But pSpan should never be
  62581. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  62582. ** is set.
  62583. */
  62584. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  62585. Parse *pParse, /* Parsing context */
  62586. ExprList *pList, /* List to which to add the span. */
  62587. ExprSpan *pSpan /* The span to be added */
  62588. ){
  62589. sqlite3 *db = pParse->db;
  62590. assert( pList!=0 || db->mallocFailed!=0 );
  62591. if( pList ){
  62592. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  62593. assert( pList->nExpr>0 );
  62594. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  62595. sqlite3DbFree(db, pItem->zSpan);
  62596. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  62597. (int)(pSpan->zEnd - pSpan->zStart));
  62598. }
  62599. }
  62600. /*
  62601. ** If the expression list pEList contains more than iLimit elements,
  62602. ** leave an error message in pParse.
  62603. */
  62604. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  62605. Parse *pParse,
  62606. ExprList *pEList,
  62607. const char *zObject
  62608. ){
  62609. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  62610. testcase( pEList && pEList->nExpr==mx );
  62611. testcase( pEList && pEList->nExpr==mx+1 );
  62612. if( pEList && pEList->nExpr>mx ){
  62613. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  62614. }
  62615. }
  62616. /*
  62617. ** Delete an entire expression list.
  62618. */
  62619. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  62620. int i;
  62621. struct ExprList_item *pItem;
  62622. if( pList==0 ) return;
  62623. assert( pList->a!=0 || pList->nExpr==0 );
  62624. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  62625. sqlite3ExprDelete(db, pItem->pExpr);
  62626. sqlite3DbFree(db, pItem->zName);
  62627. sqlite3DbFree(db, pItem->zSpan);
  62628. }
  62629. sqlite3DbFree(db, pList->a);
  62630. sqlite3DbFree(db, pList);
  62631. }
  62632. /*
  62633. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  62634. ** to an integer. These routines are checking an expression to see
  62635. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  62636. ** not constant.
  62637. **
  62638. ** These callback routines are used to implement the following:
  62639. **
  62640. ** sqlite3ExprIsConstant()
  62641. ** sqlite3ExprIsConstantNotJoin()
  62642. ** sqlite3ExprIsConstantOrFunction()
  62643. **
  62644. */
  62645. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  62646. /* If pWalker->u.i is 3 then any term of the expression that comes from
  62647. ** the ON or USING clauses of a join disqualifies the expression
  62648. ** from being considered constant. */
  62649. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  62650. pWalker->u.i = 0;
  62651. return WRC_Abort;
  62652. }
  62653. switch( pExpr->op ){
  62654. /* Consider functions to be constant if all their arguments are constant
  62655. ** and pWalker->u.i==2 */
  62656. case TK_FUNCTION:
  62657. if( pWalker->u.i==2 ) return 0;
  62658. /* Fall through */
  62659. case TK_ID:
  62660. case TK_COLUMN:
  62661. case TK_AGG_FUNCTION:
  62662. case TK_AGG_COLUMN:
  62663. testcase( pExpr->op==TK_ID );
  62664. testcase( pExpr->op==TK_COLUMN );
  62665. testcase( pExpr->op==TK_AGG_FUNCTION );
  62666. testcase( pExpr->op==TK_AGG_COLUMN );
  62667. pWalker->u.i = 0;
  62668. return WRC_Abort;
  62669. default:
  62670. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  62671. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  62672. return WRC_Continue;
  62673. }
  62674. }
  62675. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  62676. UNUSED_PARAMETER(NotUsed);
  62677. pWalker->u.i = 0;
  62678. return WRC_Abort;
  62679. }
  62680. static int exprIsConst(Expr *p, int initFlag){
  62681. Walker w;
  62682. memset(&w, 0, sizeof(w));
  62683. w.u.i = initFlag;
  62684. w.xExprCallback = exprNodeIsConstant;
  62685. w.xSelectCallback = selectNodeIsConstant;
  62686. sqlite3WalkExpr(&w, p);
  62687. return w.u.i;
  62688. }
  62689. /*
  62690. ** Walk an expression tree. Return 1 if the expression is constant
  62691. ** and 0 if it involves variables or function calls.
  62692. **
  62693. ** For the purposes of this function, a double-quoted string (ex: "abc")
  62694. ** is considered a variable but a single-quoted string (ex: 'abc') is
  62695. ** a constant.
  62696. */
  62697. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  62698. return exprIsConst(p, 1);
  62699. }
  62700. /*
  62701. ** Walk an expression tree. Return 1 if the expression is constant
  62702. ** that does no originate from the ON or USING clauses of a join.
  62703. ** Return 0 if it involves variables or function calls or terms from
  62704. ** an ON or USING clause.
  62705. */
  62706. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  62707. return exprIsConst(p, 3);
  62708. }
  62709. /*
  62710. ** Walk an expression tree. Return 1 if the expression is constant
  62711. ** or a function call with constant arguments. Return and 0 if there
  62712. ** are any variables.
  62713. **
  62714. ** For the purposes of this function, a double-quoted string (ex: "abc")
  62715. ** is considered a variable but a single-quoted string (ex: 'abc') is
  62716. ** a constant.
  62717. */
  62718. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  62719. return exprIsConst(p, 2);
  62720. }
  62721. /*
  62722. ** If the expression p codes a constant integer that is small enough
  62723. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  62724. ** in *pValue. If the expression is not an integer or if it is too big
  62725. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  62726. */
  62727. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  62728. int rc = 0;
  62729. /* If an expression is an integer literal that fits in a signed 32-bit
  62730. ** integer, then the EP_IntValue flag will have already been set */
  62731. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  62732. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  62733. if( p->flags & EP_IntValue ){
  62734. *pValue = p->u.iValue;
  62735. return 1;
  62736. }
  62737. switch( p->op ){
  62738. case TK_UPLUS: {
  62739. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  62740. break;
  62741. }
  62742. case TK_UMINUS: {
  62743. int v;
  62744. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  62745. assert( v!=(-2147483647-1) );
  62746. *pValue = -v;
  62747. rc = 1;
  62748. }
  62749. break;
  62750. }
  62751. default: break;
  62752. }
  62753. return rc;
  62754. }
  62755. /*
  62756. ** Return FALSE if there is no chance that the expression can be NULL.
  62757. **
  62758. ** If the expression might be NULL or if the expression is too complex
  62759. ** to tell return TRUE.
  62760. **
  62761. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  62762. ** when we know that a value cannot be NULL. Hence, a false positive
  62763. ** (returning TRUE when in fact the expression can never be NULL) might
  62764. ** be a small performance hit but is otherwise harmless. On the other
  62765. ** hand, a false negative (returning FALSE when the result could be NULL)
  62766. ** will likely result in an incorrect answer. So when in doubt, return
  62767. ** TRUE.
  62768. */
  62769. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  62770. u8 op;
  62771. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  62772. op = p->op;
  62773. if( op==TK_REGISTER ) op = p->op2;
  62774. switch( op ){
  62775. case TK_INTEGER:
  62776. case TK_STRING:
  62777. case TK_FLOAT:
  62778. case TK_BLOB:
  62779. return 0;
  62780. default:
  62781. return 1;
  62782. }
  62783. }
  62784. /*
  62785. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  62786. ** to location iDest if the value in iReg is NULL. The value in iReg
  62787. ** was computed by pExpr. If we can look at pExpr at compile-time and
  62788. ** determine that it can never generate a NULL, then the OP_IsNull operation
  62789. ** can be omitted.
  62790. */
  62791. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  62792. Vdbe *v, /* The VDBE under construction */
  62793. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  62794. int iReg, /* Test the value in this register for NULL */
  62795. int iDest /* Jump here if the value is null */
  62796. ){
  62797. if( sqlite3ExprCanBeNull(pExpr) ){
  62798. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  62799. }
  62800. }
  62801. /*
  62802. ** Return TRUE if the given expression is a constant which would be
  62803. ** unchanged by OP_Affinity with the affinity given in the second
  62804. ** argument.
  62805. **
  62806. ** This routine is used to determine if the OP_Affinity operation
  62807. ** can be omitted. When in doubt return FALSE. A false negative
  62808. ** is harmless. A false positive, however, can result in the wrong
  62809. ** answer.
  62810. */
  62811. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  62812. u8 op;
  62813. if( aff==SQLITE_AFF_NONE ) return 1;
  62814. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  62815. op = p->op;
  62816. if( op==TK_REGISTER ) op = p->op2;
  62817. switch( op ){
  62818. case TK_INTEGER: {
  62819. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  62820. }
  62821. case TK_FLOAT: {
  62822. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  62823. }
  62824. case TK_STRING: {
  62825. return aff==SQLITE_AFF_TEXT;
  62826. }
  62827. case TK_BLOB: {
  62828. return 1;
  62829. }
  62830. case TK_COLUMN: {
  62831. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  62832. return p->iColumn<0
  62833. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  62834. }
  62835. default: {
  62836. return 0;
  62837. }
  62838. }
  62839. }
  62840. /*
  62841. ** Return TRUE if the given string is a row-id column name.
  62842. */
  62843. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  62844. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  62845. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  62846. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  62847. return 0;
  62848. }
  62849. /*
  62850. ** Return true if we are able to the IN operator optimization on a
  62851. ** query of the form
  62852. **
  62853. ** x IN (SELECT ...)
  62854. **
  62855. ** Where the SELECT... clause is as specified by the parameter to this
  62856. ** routine.
  62857. **
  62858. ** The Select object passed in has already been preprocessed and no
  62859. ** errors have been found.
  62860. */
  62861. #ifndef SQLITE_OMIT_SUBQUERY
  62862. static int isCandidateForInOpt(Select *p){
  62863. SrcList *pSrc;
  62864. ExprList *pEList;
  62865. Table *pTab;
  62866. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  62867. if( p->pPrior ) return 0; /* Not a compound SELECT */
  62868. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  62869. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  62870. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  62871. return 0; /* No DISTINCT keyword and no aggregate functions */
  62872. }
  62873. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  62874. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  62875. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  62876. if( p->pWhere ) return 0; /* Has no WHERE clause */
  62877. pSrc = p->pSrc;
  62878. assert( pSrc!=0 );
  62879. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  62880. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  62881. pTab = pSrc->a[0].pTab;
  62882. if( NEVER(pTab==0) ) return 0;
  62883. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  62884. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  62885. pEList = p->pEList;
  62886. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  62887. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  62888. return 1;
  62889. }
  62890. #endif /* SQLITE_OMIT_SUBQUERY */
  62891. /*
  62892. ** Code an OP_Once instruction and allocate space for its flag. Return the
  62893. ** address of the new instruction.
  62894. */
  62895. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  62896. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  62897. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  62898. }
  62899. /*
  62900. ** This function is used by the implementation of the IN (...) operator.
  62901. ** The pX parameter is the expression on the RHS of the IN operator, which
  62902. ** might be either a list of expressions or a subquery.
  62903. **
  62904. ** The job of this routine is to find or create a b-tree object that can
  62905. ** be used either to test for membership in the RHS set or to iterate through
  62906. ** all members of the RHS set, skipping duplicates.
  62907. **
  62908. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  62909. ** and pX->iTable is set to the index of that cursor.
  62910. **
  62911. ** The returned value of this function indicates the b-tree type, as follows:
  62912. **
  62913. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  62914. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  62915. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  62916. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  62917. ** populated epheremal table.
  62918. **
  62919. ** An existing b-tree might be used if the RHS expression pX is a simple
  62920. ** subquery such as:
  62921. **
  62922. ** SELECT <column> FROM <table>
  62923. **
  62924. ** If the RHS of the IN operator is a list or a more complex subquery, then
  62925. ** an ephemeral table might need to be generated from the RHS and then
  62926. ** pX->iTable made to point to the ephermeral table instead of an
  62927. ** existing table.
  62928. **
  62929. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  62930. ** through the set members, skipping any duplicates. In this case an
  62931. ** epheremal table must be used unless the selected <column> is guaranteed
  62932. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  62933. ** has a UNIQUE constraint or UNIQUE index.
  62934. **
  62935. ** If the prNotFound parameter is not 0, then the b-tree will be used
  62936. ** for fast set membership tests. In this case an epheremal table must
  62937. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  62938. ** be found with <column> as its left-most column.
  62939. **
  62940. ** When the b-tree is being used for membership tests, the calling function
  62941. ** needs to know whether or not the structure contains an SQL NULL
  62942. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  62943. ** If there is any chance that the (...) might contain a NULL value at
  62944. ** runtime, then a register is allocated and the register number written
  62945. ** to *prNotFound. If there is no chance that the (...) contains a
  62946. ** NULL value, then *prNotFound is left unchanged.
  62947. **
  62948. ** If a register is allocated and its location stored in *prNotFound, then
  62949. ** its initial value is NULL. If the (...) does not remain constant
  62950. ** for the duration of the query (i.e. the SELECT within the (...)
  62951. ** is a correlated subquery) then the value of the allocated register is
  62952. ** reset to NULL each time the subquery is rerun. This allows the
  62953. ** caller to use vdbe code equivalent to the following:
  62954. **
  62955. ** if( register==NULL ){
  62956. ** has_null = <test if data structure contains null>
  62957. ** register = 1
  62958. ** }
  62959. **
  62960. ** in order to avoid running the <test if data structure contains null>
  62961. ** test more often than is necessary.
  62962. */
  62963. #ifndef SQLITE_OMIT_SUBQUERY
  62964. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  62965. Select *p; /* SELECT to the right of IN operator */
  62966. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  62967. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  62968. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  62969. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  62970. assert( pX->op==TK_IN );
  62971. /* Check to see if an existing table or index can be used to
  62972. ** satisfy the query. This is preferable to generating a new
  62973. ** ephemeral table.
  62974. */
  62975. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  62976. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  62977. sqlite3 *db = pParse->db; /* Database connection */
  62978. Table *pTab; /* Table <table>. */
  62979. Expr *pExpr; /* Expression <column> */
  62980. int iCol; /* Index of column <column> */
  62981. int iDb; /* Database idx for pTab */
  62982. assert( p ); /* Because of isCandidateForInOpt(p) */
  62983. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  62984. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  62985. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  62986. pTab = p->pSrc->a[0].pTab;
  62987. pExpr = p->pEList->a[0].pExpr;
  62988. iCol = pExpr->iColumn;
  62989. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  62990. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  62991. sqlite3CodeVerifySchema(pParse, iDb);
  62992. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  62993. /* This function is only called from two places. In both cases the vdbe
  62994. ** has already been allocated. So assume sqlite3GetVdbe() is always
  62995. ** successful here.
  62996. */
  62997. assert(v);
  62998. if( iCol<0 ){
  62999. int iAddr;
  63000. iAddr = sqlite3CodeOnce(pParse);
  63001. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  63002. eType = IN_INDEX_ROWID;
  63003. sqlite3VdbeJumpHere(v, iAddr);
  63004. }else{
  63005. Index *pIdx; /* Iterator variable */
  63006. /* The collation sequence used by the comparison. If an index is to
  63007. ** be used in place of a temp-table, it must be ordered according
  63008. ** to this collation sequence. */
  63009. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  63010. /* Check that the affinity that will be used to perform the
  63011. ** comparison is the same as the affinity of the column. If
  63012. ** it is not, it is not possible to use any index.
  63013. */
  63014. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  63015. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  63016. if( (pIdx->aiColumn[0]==iCol)
  63017. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  63018. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  63019. ){
  63020. int iAddr;
  63021. char *pKey;
  63022. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  63023. iAddr = sqlite3CodeOnce(pParse);
  63024. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  63025. pKey,P4_KEYINFO_HANDOFF);
  63026. VdbeComment((v, "%s", pIdx->zName));
  63027. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  63028. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  63029. sqlite3VdbeJumpHere(v, iAddr);
  63030. if( prNotFound && !pTab->aCol[iCol].notNull ){
  63031. *prNotFound = ++pParse->nMem;
  63032. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  63033. }
  63034. }
  63035. }
  63036. }
  63037. }
  63038. if( eType==0 ){
  63039. /* Could not found an existing table or index to use as the RHS b-tree.
  63040. ** We will have to generate an ephemeral table to do the job.
  63041. */
  63042. u32 savedNQueryLoop = pParse->nQueryLoop;
  63043. int rMayHaveNull = 0;
  63044. eType = IN_INDEX_EPH;
  63045. if( prNotFound ){
  63046. *prNotFound = rMayHaveNull = ++pParse->nMem;
  63047. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  63048. }else{
  63049. testcase( pParse->nQueryLoop>0 );
  63050. pParse->nQueryLoop = 0;
  63051. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  63052. eType = IN_INDEX_ROWID;
  63053. }
  63054. }
  63055. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  63056. pParse->nQueryLoop = savedNQueryLoop;
  63057. }else{
  63058. pX->iTable = iTab;
  63059. }
  63060. return eType;
  63061. }
  63062. #endif
  63063. /*
  63064. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  63065. ** or IN operators. Examples:
  63066. **
  63067. ** (SELECT a FROM b) -- subquery
  63068. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  63069. ** x IN (4,5,11) -- IN operator with list on right-hand side
  63070. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  63071. **
  63072. ** The pExpr parameter describes the expression that contains the IN
  63073. ** operator or subquery.
  63074. **
  63075. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  63076. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  63077. ** to some integer key column of a table B-Tree. In this case, use an
  63078. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  63079. ** (slower) variable length keys B-Tree.
  63080. **
  63081. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  63082. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  63083. ** Furthermore, the IN is in a WHERE clause and that we really want
  63084. ** to iterate over the RHS of the IN operator in order to quickly locate
  63085. ** all corresponding LHS elements. All this routine does is initialize
  63086. ** the register given by rMayHaveNull to NULL. Calling routines will take
  63087. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  63088. **
  63089. ** If rMayHaveNull is zero, that means that the subquery is being used
  63090. ** for membership testing only. There is no need to initialize any
  63091. ** registers to indicate the presence or absence of NULLs on the RHS.
  63092. **
  63093. ** For a SELECT or EXISTS operator, return the register that holds the
  63094. ** result. For IN operators or if an error occurs, the return value is 0.
  63095. */
  63096. #ifndef SQLITE_OMIT_SUBQUERY
  63097. SQLITE_PRIVATE int sqlite3CodeSubselect(
  63098. Parse *pParse, /* Parsing context */
  63099. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  63100. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  63101. int isRowid /* If true, LHS of IN operator is a rowid */
  63102. ){
  63103. int testAddr = -1; /* One-time test address */
  63104. int rReg = 0; /* Register storing resulting */
  63105. Vdbe *v = sqlite3GetVdbe(pParse);
  63106. if( NEVER(v==0) ) return 0;
  63107. sqlite3ExprCachePush(pParse);
  63108. /* This code must be run in its entirety every time it is encountered
  63109. ** if any of the following is true:
  63110. **
  63111. ** * The right-hand side is a correlated subquery
  63112. ** * The right-hand side is an expression list containing variables
  63113. ** * We are inside a trigger
  63114. **
  63115. ** If all of the above are false, then we can run this code just once
  63116. ** save the results, and reuse the same result on subsequent invocations.
  63117. */
  63118. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  63119. testAddr = sqlite3CodeOnce(pParse);
  63120. }
  63121. #ifndef SQLITE_OMIT_EXPLAIN
  63122. if( pParse->explain==2 ){
  63123. char *zMsg = sqlite3MPrintf(
  63124. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  63125. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  63126. );
  63127. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  63128. }
  63129. #endif
  63130. switch( pExpr->op ){
  63131. case TK_IN: {
  63132. char affinity; /* Affinity of the LHS of the IN */
  63133. int addr; /* Address of OP_OpenEphemeral instruction */
  63134. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  63135. KeyInfo *pKeyInfo = 0; /* Key information */
  63136. if( rMayHaveNull ){
  63137. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  63138. }
  63139. affinity = sqlite3ExprAffinity(pLeft);
  63140. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  63141. ** expression it is handled the same way. An ephemeral table is
  63142. ** filled with single-field index keys representing the results
  63143. ** from the SELECT or the <exprlist>.
  63144. **
  63145. ** If the 'x' expression is a column value, or the SELECT...
  63146. ** statement returns a column value, then the affinity of that
  63147. ** column is used to build the index keys. If both 'x' and the
  63148. ** SELECT... statement are columns, then numeric affinity is used
  63149. ** if either column has NUMERIC or INTEGER affinity. If neither
  63150. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  63151. ** is used.
  63152. */
  63153. pExpr->iTable = pParse->nTab++;
  63154. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  63155. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  63156. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  63157. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  63158. /* Case 1: expr IN (SELECT ...)
  63159. **
  63160. ** Generate code to write the results of the select into the temporary
  63161. ** table allocated and opened above.
  63162. */
  63163. SelectDest dest;
  63164. ExprList *pEList;
  63165. assert( !isRowid );
  63166. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  63167. dest.affSdst = (u8)affinity;
  63168. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  63169. pExpr->x.pSelect->iLimit = 0;
  63170. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  63171. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  63172. sqlite3DbFree(pParse->db, pKeyInfo);
  63173. return 0;
  63174. }
  63175. pEList = pExpr->x.pSelect->pEList;
  63176. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  63177. assert( pEList!=0 );
  63178. assert( pEList->nExpr>0 );
  63179. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  63180. pEList->a[0].pExpr);
  63181. }else if( ALWAYS(pExpr->x.pList!=0) ){
  63182. /* Case 2: expr IN (exprlist)
  63183. **
  63184. ** For each expression, build an index key from the evaluation and
  63185. ** store it in the temporary table. If <expr> is a column, then use
  63186. ** that columns affinity when building index keys. If <expr> is not
  63187. ** a column, use numeric affinity.
  63188. */
  63189. int i;
  63190. ExprList *pList = pExpr->x.pList;
  63191. struct ExprList_item *pItem;
  63192. int r1, r2, r3;
  63193. if( !affinity ){
  63194. affinity = SQLITE_AFF_NONE;
  63195. }
  63196. if( pKeyInfo ){
  63197. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  63198. }
  63199. /* Loop through each expression in <exprlist>. */
  63200. r1 = sqlite3GetTempReg(pParse);
  63201. r2 = sqlite3GetTempReg(pParse);
  63202. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  63203. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  63204. Expr *pE2 = pItem->pExpr;
  63205. int iValToIns;
  63206. /* If the expression is not constant then we will need to
  63207. ** disable the test that was generated above that makes sure
  63208. ** this code only executes once. Because for a non-constant
  63209. ** expression we need to rerun this code each time.
  63210. */
  63211. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  63212. sqlite3VdbeChangeToNoop(v, testAddr);
  63213. testAddr = -1;
  63214. }
  63215. /* Evaluate the expression and insert it into the temp table */
  63216. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  63217. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  63218. }else{
  63219. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  63220. if( isRowid ){
  63221. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  63222. sqlite3VdbeCurrentAddr(v)+2);
  63223. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  63224. }else{
  63225. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  63226. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  63227. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  63228. }
  63229. }
  63230. }
  63231. sqlite3ReleaseTempReg(pParse, r1);
  63232. sqlite3ReleaseTempReg(pParse, r2);
  63233. }
  63234. if( pKeyInfo ){
  63235. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  63236. }
  63237. break;
  63238. }
  63239. case TK_EXISTS:
  63240. case TK_SELECT:
  63241. default: {
  63242. /* If this has to be a scalar SELECT. Generate code to put the
  63243. ** value of this select in a memory cell and record the number
  63244. ** of the memory cell in iColumn. If this is an EXISTS, write
  63245. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  63246. ** and record that memory cell in iColumn.
  63247. */
  63248. Select *pSel; /* SELECT statement to encode */
  63249. SelectDest dest; /* How to deal with SELECt result */
  63250. testcase( pExpr->op==TK_EXISTS );
  63251. testcase( pExpr->op==TK_SELECT );
  63252. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  63253. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  63254. pSel = pExpr->x.pSelect;
  63255. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  63256. if( pExpr->op==TK_SELECT ){
  63257. dest.eDest = SRT_Mem;
  63258. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  63259. VdbeComment((v, "Init subquery result"));
  63260. }else{
  63261. dest.eDest = SRT_Exists;
  63262. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  63263. VdbeComment((v, "Init EXISTS result"));
  63264. }
  63265. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  63266. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  63267. &sqlite3IntTokens[1]);
  63268. pSel->iLimit = 0;
  63269. if( sqlite3Select(pParse, pSel, &dest) ){
  63270. return 0;
  63271. }
  63272. rReg = dest.iSDParm;
  63273. ExprSetVVAProperty(pExpr, EP_NoReduce);
  63274. break;
  63275. }
  63276. }
  63277. if( testAddr>=0 ){
  63278. sqlite3VdbeJumpHere(v, testAddr);
  63279. }
  63280. sqlite3ExprCachePop(pParse, 1);
  63281. return rReg;
  63282. }
  63283. #endif /* SQLITE_OMIT_SUBQUERY */
  63284. #ifndef SQLITE_OMIT_SUBQUERY
  63285. /*
  63286. ** Generate code for an IN expression.
  63287. **
  63288. ** x IN (SELECT ...)
  63289. ** x IN (value, value, ...)
  63290. **
  63291. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  63292. ** is an array of zero or more values. The expression is true if the LHS is
  63293. ** contained within the RHS. The value of the expression is unknown (NULL)
  63294. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  63295. ** RHS contains one or more NULL values.
  63296. **
  63297. ** This routine generates code will jump to destIfFalse if the LHS is not
  63298. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  63299. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  63300. ** within the RHS then fall through.
  63301. */
  63302. static void sqlite3ExprCodeIN(
  63303. Parse *pParse, /* Parsing and code generating context */
  63304. Expr *pExpr, /* The IN expression */
  63305. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  63306. int destIfNull /* Jump here if the results are unknown due to NULLs */
  63307. ){
  63308. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  63309. char affinity; /* Comparison affinity to use */
  63310. int eType; /* Type of the RHS */
  63311. int r1; /* Temporary use register */
  63312. Vdbe *v; /* Statement under construction */
  63313. /* Compute the RHS. After this step, the table with cursor
  63314. ** pExpr->iTable will contains the values that make up the RHS.
  63315. */
  63316. v = pParse->pVdbe;
  63317. assert( v!=0 ); /* OOM detected prior to this routine */
  63318. VdbeNoopComment((v, "begin IN expr"));
  63319. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  63320. /* Figure out the affinity to use to create a key from the results
  63321. ** of the expression. affinityStr stores a static string suitable for
  63322. ** P4 of OP_MakeRecord.
  63323. */
  63324. affinity = comparisonAffinity(pExpr);
  63325. /* Code the LHS, the <expr> from "<expr> IN (...)".
  63326. */
  63327. sqlite3ExprCachePush(pParse);
  63328. r1 = sqlite3GetTempReg(pParse);
  63329. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  63330. /* If the LHS is NULL, then the result is either false or NULL depending
  63331. ** on whether the RHS is empty or not, respectively.
  63332. */
  63333. if( destIfNull==destIfFalse ){
  63334. /* Shortcut for the common case where the false and NULL outcomes are
  63335. ** the same. */
  63336. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  63337. }else{
  63338. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  63339. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  63340. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  63341. sqlite3VdbeJumpHere(v, addr1);
  63342. }
  63343. if( eType==IN_INDEX_ROWID ){
  63344. /* In this case, the RHS is the ROWID of table b-tree
  63345. */
  63346. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  63347. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  63348. }else{
  63349. /* In this case, the RHS is an index b-tree.
  63350. */
  63351. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  63352. /* If the set membership test fails, then the result of the
  63353. ** "x IN (...)" expression must be either 0 or NULL. If the set
  63354. ** contains no NULL values, then the result is 0. If the set
  63355. ** contains one or more NULL values, then the result of the
  63356. ** expression is also NULL.
  63357. */
  63358. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  63359. /* This branch runs if it is known at compile time that the RHS
  63360. ** cannot contain NULL values. This happens as the result
  63361. ** of a "NOT NULL" constraint in the database schema.
  63362. **
  63363. ** Also run this branch if NULL is equivalent to FALSE
  63364. ** for this particular IN operator.
  63365. */
  63366. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  63367. }else{
  63368. /* In this branch, the RHS of the IN might contain a NULL and
  63369. ** the presence of a NULL on the RHS makes a difference in the
  63370. ** outcome.
  63371. */
  63372. int j1, j2, j3;
  63373. /* First check to see if the LHS is contained in the RHS. If so,
  63374. ** then the presence of NULLs in the RHS does not matter, so jump
  63375. ** over all of the code that follows.
  63376. */
  63377. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  63378. /* Here we begin generating code that runs if the LHS is not
  63379. ** contained within the RHS. Generate additional code that
  63380. ** tests the RHS for NULLs. If the RHS contains a NULL then
  63381. ** jump to destIfNull. If there are no NULLs in the RHS then
  63382. ** jump to destIfFalse.
  63383. */
  63384. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  63385. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  63386. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  63387. sqlite3VdbeJumpHere(v, j3);
  63388. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  63389. sqlite3VdbeJumpHere(v, j2);
  63390. /* Jump to the appropriate target depending on whether or not
  63391. ** the RHS contains a NULL
  63392. */
  63393. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  63394. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  63395. /* The OP_Found at the top of this branch jumps here when true,
  63396. ** causing the overall IN expression evaluation to fall through.
  63397. */
  63398. sqlite3VdbeJumpHere(v, j1);
  63399. }
  63400. }
  63401. sqlite3ReleaseTempReg(pParse, r1);
  63402. sqlite3ExprCachePop(pParse, 1);
  63403. VdbeComment((v, "end IN expr"));
  63404. }
  63405. #endif /* SQLITE_OMIT_SUBQUERY */
  63406. /*
  63407. ** Duplicate an 8-byte value
  63408. */
  63409. static char *dup8bytes(Vdbe *v, const char *in){
  63410. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  63411. if( out ){
  63412. memcpy(out, in, 8);
  63413. }
  63414. return out;
  63415. }
  63416. #ifndef SQLITE_OMIT_FLOATING_POINT
  63417. /*
  63418. ** Generate an instruction that will put the floating point
  63419. ** value described by z[0..n-1] into register iMem.
  63420. **
  63421. ** The z[] string will probably not be zero-terminated. But the
  63422. ** z[n] character is guaranteed to be something that does not look
  63423. ** like the continuation of the number.
  63424. */
  63425. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  63426. if( ALWAYS(z!=0) ){
  63427. double value;
  63428. char *zV;
  63429. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  63430. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  63431. if( negateFlag ) value = -value;
  63432. zV = dup8bytes(v, (char*)&value);
  63433. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  63434. }
  63435. }
  63436. #endif
  63437. /*
  63438. ** Generate an instruction that will put the integer describe by
  63439. ** text z[0..n-1] into register iMem.
  63440. **
  63441. ** Expr.u.zToken is always UTF8 and zero-terminated.
  63442. */
  63443. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  63444. Vdbe *v = pParse->pVdbe;
  63445. if( pExpr->flags & EP_IntValue ){
  63446. int i = pExpr->u.iValue;
  63447. assert( i>=0 );
  63448. if( negFlag ) i = -i;
  63449. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  63450. }else{
  63451. int c;
  63452. i64 value;
  63453. const char *z = pExpr->u.zToken;
  63454. assert( z!=0 );
  63455. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  63456. if( c==0 || (c==2 && negFlag) ){
  63457. char *zV;
  63458. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  63459. zV = dup8bytes(v, (char*)&value);
  63460. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  63461. }else{
  63462. #ifdef SQLITE_OMIT_FLOATING_POINT
  63463. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  63464. #else
  63465. codeReal(v, z, negFlag, iMem);
  63466. #endif
  63467. }
  63468. }
  63469. }
  63470. /*
  63471. ** Clear a cache entry.
  63472. */
  63473. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  63474. if( p->tempReg ){
  63475. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  63476. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  63477. }
  63478. p->tempReg = 0;
  63479. }
  63480. }
  63481. /*
  63482. ** Record in the column cache that a particular column from a
  63483. ** particular table is stored in a particular register.
  63484. */
  63485. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  63486. int i;
  63487. int minLru;
  63488. int idxLru;
  63489. struct yColCache *p;
  63490. assert( iReg>0 ); /* Register numbers are always positive */
  63491. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  63492. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  63493. ** for testing only - to verify that SQLite always gets the same answer
  63494. ** with and without the column cache.
  63495. */
  63496. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  63497. /* First replace any existing entry.
  63498. **
  63499. ** Actually, the way the column cache is currently used, we are guaranteed
  63500. ** that the object will never already be in cache. Verify this guarantee.
  63501. */
  63502. #ifndef NDEBUG
  63503. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63504. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  63505. }
  63506. #endif
  63507. /* Find an empty slot and replace it */
  63508. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63509. if( p->iReg==0 ){
  63510. p->iLevel = pParse->iCacheLevel;
  63511. p->iTable = iTab;
  63512. p->iColumn = iCol;
  63513. p->iReg = iReg;
  63514. p->tempReg = 0;
  63515. p->lru = pParse->iCacheCnt++;
  63516. return;
  63517. }
  63518. }
  63519. /* Replace the last recently used */
  63520. minLru = 0x7fffffff;
  63521. idxLru = -1;
  63522. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63523. if( p->lru<minLru ){
  63524. idxLru = i;
  63525. minLru = p->lru;
  63526. }
  63527. }
  63528. if( ALWAYS(idxLru>=0) ){
  63529. p = &pParse->aColCache[idxLru];
  63530. p->iLevel = pParse->iCacheLevel;
  63531. p->iTable = iTab;
  63532. p->iColumn = iCol;
  63533. p->iReg = iReg;
  63534. p->tempReg = 0;
  63535. p->lru = pParse->iCacheCnt++;
  63536. return;
  63537. }
  63538. }
  63539. /*
  63540. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  63541. ** Purge the range of registers from the column cache.
  63542. */
  63543. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  63544. int i;
  63545. int iLast = iReg + nReg - 1;
  63546. struct yColCache *p;
  63547. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63548. int r = p->iReg;
  63549. if( r>=iReg && r<=iLast ){
  63550. cacheEntryClear(pParse, p);
  63551. p->iReg = 0;
  63552. }
  63553. }
  63554. }
  63555. /*
  63556. ** Remember the current column cache context. Any new entries added
  63557. ** added to the column cache after this call are removed when the
  63558. ** corresponding pop occurs.
  63559. */
  63560. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  63561. pParse->iCacheLevel++;
  63562. }
  63563. /*
  63564. ** Remove from the column cache any entries that were added since the
  63565. ** the previous N Push operations. In other words, restore the cache
  63566. ** to the state it was in N Pushes ago.
  63567. */
  63568. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  63569. int i;
  63570. struct yColCache *p;
  63571. assert( N>0 );
  63572. assert( pParse->iCacheLevel>=N );
  63573. pParse->iCacheLevel -= N;
  63574. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63575. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  63576. cacheEntryClear(pParse, p);
  63577. p->iReg = 0;
  63578. }
  63579. }
  63580. }
  63581. /*
  63582. ** When a cached column is reused, make sure that its register is
  63583. ** no longer available as a temp register. ticket #3879: that same
  63584. ** register might be in the cache in multiple places, so be sure to
  63585. ** get them all.
  63586. */
  63587. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  63588. int i;
  63589. struct yColCache *p;
  63590. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63591. if( p->iReg==iReg ){
  63592. p->tempReg = 0;
  63593. }
  63594. }
  63595. }
  63596. /*
  63597. ** Generate code to extract the value of the iCol-th column of a table.
  63598. */
  63599. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  63600. Vdbe *v, /* The VDBE under construction */
  63601. Table *pTab, /* The table containing the value */
  63602. int iTabCur, /* The cursor for this table */
  63603. int iCol, /* Index of the column to extract */
  63604. int regOut /* Extract the valud into this register */
  63605. ){
  63606. if( iCol<0 || iCol==pTab->iPKey ){
  63607. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  63608. }else{
  63609. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  63610. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  63611. }
  63612. if( iCol>=0 ){
  63613. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  63614. }
  63615. }
  63616. /*
  63617. ** Generate code that will extract the iColumn-th column from
  63618. ** table pTab and store the column value in a register. An effort
  63619. ** is made to store the column value in register iReg, but this is
  63620. ** not guaranteed. The location of the column value is returned.
  63621. **
  63622. ** There must be an open cursor to pTab in iTable when this routine
  63623. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  63624. */
  63625. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  63626. Parse *pParse, /* Parsing and code generating context */
  63627. Table *pTab, /* Description of the table we are reading from */
  63628. int iColumn, /* Index of the table column */
  63629. int iTable, /* The cursor pointing to the table */
  63630. int iReg, /* Store results here */
  63631. u8 p5 /* P5 value for OP_Column */
  63632. ){
  63633. Vdbe *v = pParse->pVdbe;
  63634. int i;
  63635. struct yColCache *p;
  63636. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63637. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  63638. p->lru = pParse->iCacheCnt++;
  63639. sqlite3ExprCachePinRegister(pParse, p->iReg);
  63640. return p->iReg;
  63641. }
  63642. }
  63643. assert( v!=0 );
  63644. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  63645. if( p5 ){
  63646. sqlite3VdbeChangeP5(v, p5);
  63647. }else{
  63648. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  63649. }
  63650. return iReg;
  63651. }
  63652. /*
  63653. ** Clear all column cache entries.
  63654. */
  63655. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  63656. int i;
  63657. struct yColCache *p;
  63658. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63659. if( p->iReg ){
  63660. cacheEntryClear(pParse, p);
  63661. p->iReg = 0;
  63662. }
  63663. }
  63664. }
  63665. /*
  63666. ** Record the fact that an affinity change has occurred on iCount
  63667. ** registers starting with iStart.
  63668. */
  63669. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  63670. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  63671. }
  63672. /*
  63673. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  63674. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  63675. */
  63676. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  63677. int i;
  63678. struct yColCache *p;
  63679. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  63680. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  63681. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63682. int x = p->iReg;
  63683. if( x>=iFrom && x<iFrom+nReg ){
  63684. p->iReg += iTo-iFrom;
  63685. }
  63686. }
  63687. }
  63688. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  63689. /*
  63690. ** Return true if any register in the range iFrom..iTo (inclusive)
  63691. ** is used as part of the column cache.
  63692. **
  63693. ** This routine is used within assert() and testcase() macros only
  63694. ** and does not appear in a normal build.
  63695. */
  63696. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  63697. int i;
  63698. struct yColCache *p;
  63699. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63700. int r = p->iReg;
  63701. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  63702. }
  63703. return 0;
  63704. }
  63705. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  63706. /*
  63707. ** Convert an expression node to a TK_REGISTER
  63708. */
  63709. static void exprToRegister(Expr *p, int iReg){
  63710. p->op2 = p->op;
  63711. p->op = TK_REGISTER;
  63712. p->iTable = iReg;
  63713. ExprClearProperty(p, EP_Skip);
  63714. }
  63715. /*
  63716. ** Generate code into the current Vdbe to evaluate the given
  63717. ** expression. Attempt to store the results in register "target".
  63718. ** Return the register where results are stored.
  63719. **
  63720. ** With this routine, there is no guarantee that results will
  63721. ** be stored in target. The result might be stored in some other
  63722. ** register if it is convenient to do so. The calling function
  63723. ** must check the return code and move the results to the desired
  63724. ** register.
  63725. */
  63726. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  63727. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  63728. int op; /* The opcode being coded */
  63729. int inReg = target; /* Results stored in register inReg */
  63730. int regFree1 = 0; /* If non-zero free this temporary register */
  63731. int regFree2 = 0; /* If non-zero free this temporary register */
  63732. int r1, r2, r3, r4; /* Various register numbers */
  63733. sqlite3 *db = pParse->db; /* The database connection */
  63734. assert( target>0 && target<=pParse->nMem );
  63735. if( v==0 ){
  63736. assert( pParse->db->mallocFailed );
  63737. return 0;
  63738. }
  63739. if( pExpr==0 ){
  63740. op = TK_NULL;
  63741. }else{
  63742. op = pExpr->op;
  63743. }
  63744. switch( op ){
  63745. case TK_AGG_COLUMN: {
  63746. AggInfo *pAggInfo = pExpr->pAggInfo;
  63747. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  63748. if( !pAggInfo->directMode ){
  63749. assert( pCol->iMem>0 );
  63750. inReg = pCol->iMem;
  63751. break;
  63752. }else if( pAggInfo->useSortingIdx ){
  63753. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  63754. pCol->iSorterColumn, target);
  63755. break;
  63756. }
  63757. /* Otherwise, fall thru into the TK_COLUMN case */
  63758. }
  63759. case TK_COLUMN: {
  63760. int iTab = pExpr->iTable;
  63761. if( iTab<0 ){
  63762. if( pParse->ckBase>0 ){
  63763. /* Generating CHECK constraints or inserting into partial index */
  63764. inReg = pExpr->iColumn + pParse->ckBase;
  63765. break;
  63766. }else{
  63767. /* Deleting from a partial index */
  63768. iTab = pParse->iPartIdxTab;
  63769. }
  63770. }
  63771. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  63772. pExpr->iColumn, iTab, target,
  63773. pExpr->op2);
  63774. break;
  63775. }
  63776. case TK_INTEGER: {
  63777. codeInteger(pParse, pExpr, 0, target);
  63778. break;
  63779. }
  63780. #ifndef SQLITE_OMIT_FLOATING_POINT
  63781. case TK_FLOAT: {
  63782. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63783. codeReal(v, pExpr->u.zToken, 0, target);
  63784. break;
  63785. }
  63786. #endif
  63787. case TK_STRING: {
  63788. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63789. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  63790. break;
  63791. }
  63792. case TK_NULL: {
  63793. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  63794. break;
  63795. }
  63796. #ifndef SQLITE_OMIT_BLOB_LITERAL
  63797. case TK_BLOB: {
  63798. int n;
  63799. const char *z;
  63800. char *zBlob;
  63801. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63802. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  63803. assert( pExpr->u.zToken[1]=='\'' );
  63804. z = &pExpr->u.zToken[2];
  63805. n = sqlite3Strlen30(z) - 1;
  63806. assert( z[n]=='\'' );
  63807. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  63808. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  63809. break;
  63810. }
  63811. #endif
  63812. case TK_VARIABLE: {
  63813. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63814. assert( pExpr->u.zToken!=0 );
  63815. assert( pExpr->u.zToken[0]!=0 );
  63816. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  63817. if( pExpr->u.zToken[1]!=0 ){
  63818. assert( pExpr->u.zToken[0]=='?'
  63819. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  63820. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  63821. }
  63822. break;
  63823. }
  63824. case TK_REGISTER: {
  63825. inReg = pExpr->iTable;
  63826. break;
  63827. }
  63828. case TK_AS: {
  63829. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  63830. break;
  63831. }
  63832. #ifndef SQLITE_OMIT_CAST
  63833. case TK_CAST: {
  63834. /* Expressions of the form: CAST(pLeft AS token) */
  63835. int aff, to_op;
  63836. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  63837. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63838. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  63839. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  63840. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  63841. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  63842. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  63843. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  63844. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  63845. testcase( to_op==OP_ToText );
  63846. testcase( to_op==OP_ToBlob );
  63847. testcase( to_op==OP_ToNumeric );
  63848. testcase( to_op==OP_ToInt );
  63849. testcase( to_op==OP_ToReal );
  63850. if( inReg!=target ){
  63851. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  63852. inReg = target;
  63853. }
  63854. sqlite3VdbeAddOp1(v, to_op, inReg);
  63855. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  63856. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  63857. break;
  63858. }
  63859. #endif /* SQLITE_OMIT_CAST */
  63860. case TK_LT:
  63861. case TK_LE:
  63862. case TK_GT:
  63863. case TK_GE:
  63864. case TK_NE:
  63865. case TK_EQ: {
  63866. assert( TK_LT==OP_Lt );
  63867. assert( TK_LE==OP_Le );
  63868. assert( TK_GT==OP_Gt );
  63869. assert( TK_GE==OP_Ge );
  63870. assert( TK_EQ==OP_Eq );
  63871. assert( TK_NE==OP_Ne );
  63872. testcase( op==TK_LT );
  63873. testcase( op==TK_LE );
  63874. testcase( op==TK_GT );
  63875. testcase( op==TK_GE );
  63876. testcase( op==TK_EQ );
  63877. testcase( op==TK_NE );
  63878. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63879. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63880. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  63881. r1, r2, inReg, SQLITE_STOREP2);
  63882. testcase( regFree1==0 );
  63883. testcase( regFree2==0 );
  63884. break;
  63885. }
  63886. case TK_IS:
  63887. case TK_ISNOT: {
  63888. testcase( op==TK_IS );
  63889. testcase( op==TK_ISNOT );
  63890. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63891. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63892. op = (op==TK_IS) ? TK_EQ : TK_NE;
  63893. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  63894. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  63895. testcase( regFree1==0 );
  63896. testcase( regFree2==0 );
  63897. break;
  63898. }
  63899. case TK_AND:
  63900. case TK_OR:
  63901. case TK_PLUS:
  63902. case TK_STAR:
  63903. case TK_MINUS:
  63904. case TK_REM:
  63905. case TK_BITAND:
  63906. case TK_BITOR:
  63907. case TK_SLASH:
  63908. case TK_LSHIFT:
  63909. case TK_RSHIFT:
  63910. case TK_CONCAT: {
  63911. assert( TK_AND==OP_And );
  63912. assert( TK_OR==OP_Or );
  63913. assert( TK_PLUS==OP_Add );
  63914. assert( TK_MINUS==OP_Subtract );
  63915. assert( TK_REM==OP_Remainder );
  63916. assert( TK_BITAND==OP_BitAnd );
  63917. assert( TK_BITOR==OP_BitOr );
  63918. assert( TK_SLASH==OP_Divide );
  63919. assert( TK_LSHIFT==OP_ShiftLeft );
  63920. assert( TK_RSHIFT==OP_ShiftRight );
  63921. assert( TK_CONCAT==OP_Concat );
  63922. testcase( op==TK_AND );
  63923. testcase( op==TK_OR );
  63924. testcase( op==TK_PLUS );
  63925. testcase( op==TK_MINUS );
  63926. testcase( op==TK_REM );
  63927. testcase( op==TK_BITAND );
  63928. testcase( op==TK_BITOR );
  63929. testcase( op==TK_SLASH );
  63930. testcase( op==TK_LSHIFT );
  63931. testcase( op==TK_RSHIFT );
  63932. testcase( op==TK_CONCAT );
  63933. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63934. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63935. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  63936. testcase( regFree1==0 );
  63937. testcase( regFree2==0 );
  63938. break;
  63939. }
  63940. case TK_UMINUS: {
  63941. Expr *pLeft = pExpr->pLeft;
  63942. assert( pLeft );
  63943. if( pLeft->op==TK_INTEGER ){
  63944. codeInteger(pParse, pLeft, 1, target);
  63945. #ifndef SQLITE_OMIT_FLOATING_POINT
  63946. }else if( pLeft->op==TK_FLOAT ){
  63947. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63948. codeReal(v, pLeft->u.zToken, 1, target);
  63949. #endif
  63950. }else{
  63951. regFree1 = r1 = sqlite3GetTempReg(pParse);
  63952. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  63953. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  63954. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  63955. testcase( regFree2==0 );
  63956. }
  63957. inReg = target;
  63958. break;
  63959. }
  63960. case TK_BITNOT:
  63961. case TK_NOT: {
  63962. assert( TK_BITNOT==OP_BitNot );
  63963. assert( TK_NOT==OP_Not );
  63964. testcase( op==TK_BITNOT );
  63965. testcase( op==TK_NOT );
  63966. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63967. testcase( regFree1==0 );
  63968. inReg = target;
  63969. sqlite3VdbeAddOp2(v, op, r1, inReg);
  63970. break;
  63971. }
  63972. case TK_ISNULL:
  63973. case TK_NOTNULL: {
  63974. int addr;
  63975. assert( TK_ISNULL==OP_IsNull );
  63976. assert( TK_NOTNULL==OP_NotNull );
  63977. testcase( op==TK_ISNULL );
  63978. testcase( op==TK_NOTNULL );
  63979. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  63980. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63981. testcase( regFree1==0 );
  63982. addr = sqlite3VdbeAddOp1(v, op, r1);
  63983. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  63984. sqlite3VdbeJumpHere(v, addr);
  63985. break;
  63986. }
  63987. case TK_AGG_FUNCTION: {
  63988. AggInfo *pInfo = pExpr->pAggInfo;
  63989. if( pInfo==0 ){
  63990. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63991. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  63992. }else{
  63993. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  63994. }
  63995. break;
  63996. }
  63997. case TK_CONST_FUNC:
  63998. case TK_FUNCTION: {
  63999. ExprList *pFarg; /* List of function arguments */
  64000. int nFarg; /* Number of function arguments */
  64001. FuncDef *pDef; /* The function definition object */
  64002. int nId; /* Length of the function name in bytes */
  64003. const char *zId; /* The function name */
  64004. int constMask = 0; /* Mask of function arguments that are constant */
  64005. int i; /* Loop counter */
  64006. u8 enc = ENC(db); /* The text encoding used by this database */
  64007. CollSeq *pColl = 0; /* A collating sequence */
  64008. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64009. testcase( op==TK_CONST_FUNC );
  64010. testcase( op==TK_FUNCTION );
  64011. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  64012. pFarg = 0;
  64013. }else{
  64014. pFarg = pExpr->x.pList;
  64015. }
  64016. nFarg = pFarg ? pFarg->nExpr : 0;
  64017. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  64018. zId = pExpr->u.zToken;
  64019. nId = sqlite3Strlen30(zId);
  64020. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  64021. if( pDef==0 ){
  64022. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  64023. break;
  64024. }
  64025. /* Attempt a direct implementation of the built-in COALESCE() and
  64026. ** IFNULL() functions. This avoids unnecessary evalation of
  64027. ** arguments past the first non-NULL argument.
  64028. */
  64029. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  64030. int endCoalesce = sqlite3VdbeMakeLabel(v);
  64031. assert( nFarg>=2 );
  64032. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  64033. for(i=1; i<nFarg; i++){
  64034. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  64035. sqlite3ExprCacheRemove(pParse, target, 1);
  64036. sqlite3ExprCachePush(pParse);
  64037. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  64038. sqlite3ExprCachePop(pParse, 1);
  64039. }
  64040. sqlite3VdbeResolveLabel(v, endCoalesce);
  64041. break;
  64042. }
  64043. /* The UNLIKELY() function is a no-op. The result is the value
  64044. ** of the first argument.
  64045. */
  64046. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  64047. assert( nFarg>=1 );
  64048. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  64049. break;
  64050. }
  64051. if( pFarg ){
  64052. r1 = sqlite3GetTempRange(pParse, nFarg);
  64053. /* For length() and typeof() functions with a column argument,
  64054. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  64055. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  64056. ** loading.
  64057. */
  64058. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  64059. u8 exprOp;
  64060. assert( nFarg==1 );
  64061. assert( pFarg->a[0].pExpr!=0 );
  64062. exprOp = pFarg->a[0].pExpr->op;
  64063. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  64064. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  64065. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  64066. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  64067. ==SQLITE_FUNC_LENGTH );
  64068. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  64069. }
  64070. }
  64071. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  64072. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  64073. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  64074. }else{
  64075. r1 = 0;
  64076. }
  64077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64078. /* Possibly overload the function if the first argument is
  64079. ** a virtual table column.
  64080. **
  64081. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  64082. ** second argument, not the first, as the argument to test to
  64083. ** see if it is a column in a virtual table. This is done because
  64084. ** the left operand of infix functions (the operand we want to
  64085. ** control overloading) ends up as the second argument to the
  64086. ** function. The expression "A glob B" is equivalent to
  64087. ** "glob(B,A). We want to use the A in "A glob B" to test
  64088. ** for function overloading. But we use the B term in "glob(B,A)".
  64089. */
  64090. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  64091. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  64092. }else if( nFarg>0 ){
  64093. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  64094. }
  64095. #endif
  64096. for(i=0; i<nFarg; i++){
  64097. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  64098. constMask |= (1<<i);
  64099. }
  64100. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  64101. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  64102. }
  64103. }
  64104. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  64105. if( !pColl ) pColl = db->pDfltColl;
  64106. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  64107. }
  64108. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  64109. (char*)pDef, P4_FUNCDEF);
  64110. sqlite3VdbeChangeP5(v, (u8)nFarg);
  64111. if( nFarg ){
  64112. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  64113. }
  64114. break;
  64115. }
  64116. #ifndef SQLITE_OMIT_SUBQUERY
  64117. case TK_EXISTS:
  64118. case TK_SELECT: {
  64119. testcase( op==TK_EXISTS );
  64120. testcase( op==TK_SELECT );
  64121. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  64122. break;
  64123. }
  64124. case TK_IN: {
  64125. int destIfFalse = sqlite3VdbeMakeLabel(v);
  64126. int destIfNull = sqlite3VdbeMakeLabel(v);
  64127. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  64128. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  64129. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  64130. sqlite3VdbeResolveLabel(v, destIfFalse);
  64131. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  64132. sqlite3VdbeResolveLabel(v, destIfNull);
  64133. break;
  64134. }
  64135. #endif /* SQLITE_OMIT_SUBQUERY */
  64136. /*
  64137. ** x BETWEEN y AND z
  64138. **
  64139. ** This is equivalent to
  64140. **
  64141. ** x>=y AND x<=z
  64142. **
  64143. ** X is stored in pExpr->pLeft.
  64144. ** Y is stored in pExpr->pList->a[0].pExpr.
  64145. ** Z is stored in pExpr->pList->a[1].pExpr.
  64146. */
  64147. case TK_BETWEEN: {
  64148. Expr *pLeft = pExpr->pLeft;
  64149. struct ExprList_item *pLItem = pExpr->x.pList->a;
  64150. Expr *pRight = pLItem->pExpr;
  64151. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  64152. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  64153. testcase( regFree1==0 );
  64154. testcase( regFree2==0 );
  64155. r3 = sqlite3GetTempReg(pParse);
  64156. r4 = sqlite3GetTempReg(pParse);
  64157. codeCompare(pParse, pLeft, pRight, OP_Ge,
  64158. r1, r2, r3, SQLITE_STOREP2);
  64159. pLItem++;
  64160. pRight = pLItem->pExpr;
  64161. sqlite3ReleaseTempReg(pParse, regFree2);
  64162. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  64163. testcase( regFree2==0 );
  64164. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  64165. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  64166. sqlite3ReleaseTempReg(pParse, r3);
  64167. sqlite3ReleaseTempReg(pParse, r4);
  64168. break;
  64169. }
  64170. case TK_COLLATE:
  64171. case TK_UPLUS: {
  64172. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  64173. break;
  64174. }
  64175. case TK_TRIGGER: {
  64176. /* If the opcode is TK_TRIGGER, then the expression is a reference
  64177. ** to a column in the new.* or old.* pseudo-tables available to
  64178. ** trigger programs. In this case Expr.iTable is set to 1 for the
  64179. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  64180. ** is set to the column of the pseudo-table to read, or to -1 to
  64181. ** read the rowid field.
  64182. **
  64183. ** The expression is implemented using an OP_Param opcode. The p1
  64184. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  64185. ** to reference another column of the old.* pseudo-table, where
  64186. ** i is the index of the column. For a new.rowid reference, p1 is
  64187. ** set to (n+1), where n is the number of columns in each pseudo-table.
  64188. ** For a reference to any other column in the new.* pseudo-table, p1
  64189. ** is set to (n+2+i), where n and i are as defined previously. For
  64190. ** example, if the table on which triggers are being fired is
  64191. ** declared as:
  64192. **
  64193. ** CREATE TABLE t1(a, b);
  64194. **
  64195. ** Then p1 is interpreted as follows:
  64196. **
  64197. ** p1==0 -> old.rowid p1==3 -> new.rowid
  64198. ** p1==1 -> old.a p1==4 -> new.a
  64199. ** p1==2 -> old.b p1==5 -> new.b
  64200. */
  64201. Table *pTab = pExpr->pTab;
  64202. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  64203. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  64204. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  64205. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  64206. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  64207. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  64208. VdbeComment((v, "%s.%s -> $%d",
  64209. (pExpr->iTable ? "new" : "old"),
  64210. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  64211. target
  64212. ));
  64213. #ifndef SQLITE_OMIT_FLOATING_POINT
  64214. /* If the column has REAL affinity, it may currently be stored as an
  64215. ** integer. Use OP_RealAffinity to make sure it is really real. */
  64216. if( pExpr->iColumn>=0
  64217. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  64218. ){
  64219. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  64220. }
  64221. #endif
  64222. break;
  64223. }
  64224. /*
  64225. ** Form A:
  64226. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  64227. **
  64228. ** Form B:
  64229. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  64230. **
  64231. ** Form A is can be transformed into the equivalent form B as follows:
  64232. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  64233. ** WHEN x=eN THEN rN ELSE y END
  64234. **
  64235. ** X (if it exists) is in pExpr->pLeft.
  64236. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  64237. ** odd. The Y is also optional. If the number of elements in x.pList
  64238. ** is even, then Y is omitted and the "otherwise" result is NULL.
  64239. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  64240. **
  64241. ** The result of the expression is the Ri for the first matching Ei,
  64242. ** or if there is no matching Ei, the ELSE term Y, or if there is
  64243. ** no ELSE term, NULL.
  64244. */
  64245. default: assert( op==TK_CASE ); {
  64246. int endLabel; /* GOTO label for end of CASE stmt */
  64247. int nextCase; /* GOTO label for next WHEN clause */
  64248. int nExpr; /* 2x number of WHEN terms */
  64249. int i; /* Loop counter */
  64250. ExprList *pEList; /* List of WHEN terms */
  64251. struct ExprList_item *aListelem; /* Array of WHEN terms */
  64252. Expr opCompare; /* The X==Ei expression */
  64253. Expr cacheX; /* Cached expression X */
  64254. Expr *pX; /* The X expression */
  64255. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  64256. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  64257. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  64258. assert(pExpr->x.pList->nExpr > 0);
  64259. pEList = pExpr->x.pList;
  64260. aListelem = pEList->a;
  64261. nExpr = pEList->nExpr;
  64262. endLabel = sqlite3VdbeMakeLabel(v);
  64263. if( (pX = pExpr->pLeft)!=0 ){
  64264. cacheX = *pX;
  64265. testcase( pX->op==TK_COLUMN );
  64266. testcase( pX->op==TK_REGISTER );
  64267. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  64268. testcase( regFree1==0 );
  64269. opCompare.op = TK_EQ;
  64270. opCompare.pLeft = &cacheX;
  64271. pTest = &opCompare;
  64272. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  64273. ** The value in regFree1 might get SCopy-ed into the file result.
  64274. ** So make sure that the regFree1 register is not reused for other
  64275. ** purposes and possibly overwritten. */
  64276. regFree1 = 0;
  64277. }
  64278. for(i=0; i<nExpr-1; i=i+2){
  64279. sqlite3ExprCachePush(pParse);
  64280. if( pX ){
  64281. assert( pTest!=0 );
  64282. opCompare.pRight = aListelem[i].pExpr;
  64283. }else{
  64284. pTest = aListelem[i].pExpr;
  64285. }
  64286. nextCase = sqlite3VdbeMakeLabel(v);
  64287. testcase( pTest->op==TK_COLUMN );
  64288. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  64289. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  64290. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  64291. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  64292. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  64293. sqlite3ExprCachePop(pParse, 1);
  64294. sqlite3VdbeResolveLabel(v, nextCase);
  64295. }
  64296. if( (nExpr&1)!=0 ){
  64297. sqlite3ExprCachePush(pParse);
  64298. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  64299. sqlite3ExprCachePop(pParse, 1);
  64300. }else{
  64301. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  64302. }
  64303. assert( db->mallocFailed || pParse->nErr>0
  64304. || pParse->iCacheLevel==iCacheLevel );
  64305. sqlite3VdbeResolveLabel(v, endLabel);
  64306. break;
  64307. }
  64308. #ifndef SQLITE_OMIT_TRIGGER
  64309. case TK_RAISE: {
  64310. assert( pExpr->affinity==OE_Rollback
  64311. || pExpr->affinity==OE_Abort
  64312. || pExpr->affinity==OE_Fail
  64313. || pExpr->affinity==OE_Ignore
  64314. );
  64315. if( !pParse->pTriggerTab ){
  64316. sqlite3ErrorMsg(pParse,
  64317. "RAISE() may only be used within a trigger-program");
  64318. return 0;
  64319. }
  64320. if( pExpr->affinity==OE_Abort ){
  64321. sqlite3MayAbort(pParse);
  64322. }
  64323. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  64324. if( pExpr->affinity==OE_Ignore ){
  64325. sqlite3VdbeAddOp4(
  64326. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  64327. }else{
  64328. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  64329. pExpr->affinity, pExpr->u.zToken, 0);
  64330. }
  64331. break;
  64332. }
  64333. #endif
  64334. }
  64335. sqlite3ReleaseTempReg(pParse, regFree1);
  64336. sqlite3ReleaseTempReg(pParse, regFree2);
  64337. return inReg;
  64338. }
  64339. /*
  64340. ** Generate code to evaluate an expression and store the results
  64341. ** into a register. Return the register number where the results
  64342. ** are stored.
  64343. **
  64344. ** If the register is a temporary register that can be deallocated,
  64345. ** then write its number into *pReg. If the result register is not
  64346. ** a temporary, then set *pReg to zero.
  64347. */
  64348. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  64349. int r1 = sqlite3GetTempReg(pParse);
  64350. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  64351. if( r2==r1 ){
  64352. *pReg = r1;
  64353. }else{
  64354. sqlite3ReleaseTempReg(pParse, r1);
  64355. *pReg = 0;
  64356. }
  64357. return r2;
  64358. }
  64359. /*
  64360. ** Generate code that will evaluate expression pExpr and store the
  64361. ** results in register target. The results are guaranteed to appear
  64362. ** in register target.
  64363. */
  64364. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  64365. int inReg;
  64366. assert( target>0 && target<=pParse->nMem );
  64367. if( pExpr && pExpr->op==TK_REGISTER ){
  64368. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  64369. }else{
  64370. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  64371. assert( pParse->pVdbe || pParse->db->mallocFailed );
  64372. if( inReg!=target && pParse->pVdbe ){
  64373. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  64374. }
  64375. }
  64376. return target;
  64377. }
  64378. /*
  64379. ** Generate code that evalutes the given expression and puts the result
  64380. ** in register target.
  64381. **
  64382. ** Also make a copy of the expression results into another "cache" register
  64383. ** and modify the expression so that the next time it is evaluated,
  64384. ** the result is a copy of the cache register.
  64385. **
  64386. ** This routine is used for expressions that are used multiple
  64387. ** times. They are evaluated once and the results of the expression
  64388. ** are reused.
  64389. */
  64390. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  64391. Vdbe *v = pParse->pVdbe;
  64392. int inReg;
  64393. inReg = sqlite3ExprCode(pParse, pExpr, target);
  64394. assert( target>0 );
  64395. /* This routine is called for terms to INSERT or UPDATE. And the only
  64396. ** other place where expressions can be converted into TK_REGISTER is
  64397. ** in WHERE clause processing. So as currently implemented, there is
  64398. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  64399. ** keep the ALWAYS() in case the conditions above change with future
  64400. ** modifications or enhancements. */
  64401. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  64402. int iMem;
  64403. iMem = ++pParse->nMem;
  64404. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  64405. exprToRegister(pExpr, iMem);
  64406. }
  64407. return inReg;
  64408. }
  64409. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64410. /*
  64411. ** Generate a human-readable explanation of an expression tree.
  64412. */
  64413. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  64414. int op; /* The opcode being coded */
  64415. const char *zBinOp = 0; /* Binary operator */
  64416. const char *zUniOp = 0; /* Unary operator */
  64417. if( pExpr==0 ){
  64418. op = TK_NULL;
  64419. }else{
  64420. op = pExpr->op;
  64421. }
  64422. switch( op ){
  64423. case TK_AGG_COLUMN: {
  64424. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  64425. pExpr->iTable, pExpr->iColumn);
  64426. break;
  64427. }
  64428. case TK_COLUMN: {
  64429. if( pExpr->iTable<0 ){
  64430. /* This only happens when coding check constraints */
  64431. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  64432. }else{
  64433. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  64434. pExpr->iTable, pExpr->iColumn);
  64435. }
  64436. break;
  64437. }
  64438. case TK_INTEGER: {
  64439. if( pExpr->flags & EP_IntValue ){
  64440. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  64441. }else{
  64442. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  64443. }
  64444. break;
  64445. }
  64446. #ifndef SQLITE_OMIT_FLOATING_POINT
  64447. case TK_FLOAT: {
  64448. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  64449. break;
  64450. }
  64451. #endif
  64452. case TK_STRING: {
  64453. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  64454. break;
  64455. }
  64456. case TK_NULL: {
  64457. sqlite3ExplainPrintf(pOut,"NULL");
  64458. break;
  64459. }
  64460. #ifndef SQLITE_OMIT_BLOB_LITERAL
  64461. case TK_BLOB: {
  64462. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  64463. break;
  64464. }
  64465. #endif
  64466. case TK_VARIABLE: {
  64467. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  64468. pExpr->u.zToken, pExpr->iColumn);
  64469. break;
  64470. }
  64471. case TK_REGISTER: {
  64472. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  64473. break;
  64474. }
  64475. case TK_AS: {
  64476. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64477. break;
  64478. }
  64479. #ifndef SQLITE_OMIT_CAST
  64480. case TK_CAST: {
  64481. /* Expressions of the form: CAST(pLeft AS token) */
  64482. const char *zAff = "unk";
  64483. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  64484. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  64485. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  64486. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  64487. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  64488. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  64489. }
  64490. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  64491. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64492. sqlite3ExplainPrintf(pOut, ")");
  64493. break;
  64494. }
  64495. #endif /* SQLITE_OMIT_CAST */
  64496. case TK_LT: zBinOp = "LT"; break;
  64497. case TK_LE: zBinOp = "LE"; break;
  64498. case TK_GT: zBinOp = "GT"; break;
  64499. case TK_GE: zBinOp = "GE"; break;
  64500. case TK_NE: zBinOp = "NE"; break;
  64501. case TK_EQ: zBinOp = "EQ"; break;
  64502. case TK_IS: zBinOp = "IS"; break;
  64503. case TK_ISNOT: zBinOp = "ISNOT"; break;
  64504. case TK_AND: zBinOp = "AND"; break;
  64505. case TK_OR: zBinOp = "OR"; break;
  64506. case TK_PLUS: zBinOp = "ADD"; break;
  64507. case TK_STAR: zBinOp = "MUL"; break;
  64508. case TK_MINUS: zBinOp = "SUB"; break;
  64509. case TK_REM: zBinOp = "REM"; break;
  64510. case TK_BITAND: zBinOp = "BITAND"; break;
  64511. case TK_BITOR: zBinOp = "BITOR"; break;
  64512. case TK_SLASH: zBinOp = "DIV"; break;
  64513. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  64514. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  64515. case TK_CONCAT: zBinOp = "CONCAT"; break;
  64516. case TK_UMINUS: zUniOp = "UMINUS"; break;
  64517. case TK_UPLUS: zUniOp = "UPLUS"; break;
  64518. case TK_BITNOT: zUniOp = "BITNOT"; break;
  64519. case TK_NOT: zUniOp = "NOT"; break;
  64520. case TK_ISNULL: zUniOp = "ISNULL"; break;
  64521. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  64522. case TK_COLLATE: {
  64523. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64524. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  64525. break;
  64526. }
  64527. case TK_AGG_FUNCTION:
  64528. case TK_CONST_FUNC:
  64529. case TK_FUNCTION: {
  64530. ExprList *pFarg; /* List of function arguments */
  64531. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  64532. pFarg = 0;
  64533. }else{
  64534. pFarg = pExpr->x.pList;
  64535. }
  64536. if( op==TK_AGG_FUNCTION ){
  64537. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  64538. pExpr->op2, pExpr->u.zToken);
  64539. }else{
  64540. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  64541. }
  64542. if( pFarg ){
  64543. sqlite3ExplainExprList(pOut, pFarg);
  64544. }
  64545. sqlite3ExplainPrintf(pOut, ")");
  64546. break;
  64547. }
  64548. #ifndef SQLITE_OMIT_SUBQUERY
  64549. case TK_EXISTS: {
  64550. sqlite3ExplainPrintf(pOut, "EXISTS(");
  64551. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64552. sqlite3ExplainPrintf(pOut,")");
  64553. break;
  64554. }
  64555. case TK_SELECT: {
  64556. sqlite3ExplainPrintf(pOut, "(");
  64557. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64558. sqlite3ExplainPrintf(pOut, ")");
  64559. break;
  64560. }
  64561. case TK_IN: {
  64562. sqlite3ExplainPrintf(pOut, "IN(");
  64563. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64564. sqlite3ExplainPrintf(pOut, ",");
  64565. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  64566. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64567. }else{
  64568. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  64569. }
  64570. sqlite3ExplainPrintf(pOut, ")");
  64571. break;
  64572. }
  64573. #endif /* SQLITE_OMIT_SUBQUERY */
  64574. /*
  64575. ** x BETWEEN y AND z
  64576. **
  64577. ** This is equivalent to
  64578. **
  64579. ** x>=y AND x<=z
  64580. **
  64581. ** X is stored in pExpr->pLeft.
  64582. ** Y is stored in pExpr->pList->a[0].pExpr.
  64583. ** Z is stored in pExpr->pList->a[1].pExpr.
  64584. */
  64585. case TK_BETWEEN: {
  64586. Expr *pX = pExpr->pLeft;
  64587. Expr *pY = pExpr->x.pList->a[0].pExpr;
  64588. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  64589. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  64590. sqlite3ExplainExpr(pOut, pX);
  64591. sqlite3ExplainPrintf(pOut, ",");
  64592. sqlite3ExplainExpr(pOut, pY);
  64593. sqlite3ExplainPrintf(pOut, ",");
  64594. sqlite3ExplainExpr(pOut, pZ);
  64595. sqlite3ExplainPrintf(pOut, ")");
  64596. break;
  64597. }
  64598. case TK_TRIGGER: {
  64599. /* If the opcode is TK_TRIGGER, then the expression is a reference
  64600. ** to a column in the new.* or old.* pseudo-tables available to
  64601. ** trigger programs. In this case Expr.iTable is set to 1 for the
  64602. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  64603. ** is set to the column of the pseudo-table to read, or to -1 to
  64604. ** read the rowid field.
  64605. */
  64606. sqlite3ExplainPrintf(pOut, "%s(%d)",
  64607. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  64608. break;
  64609. }
  64610. case TK_CASE: {
  64611. sqlite3ExplainPrintf(pOut, "CASE(");
  64612. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64613. sqlite3ExplainPrintf(pOut, ",");
  64614. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  64615. break;
  64616. }
  64617. #ifndef SQLITE_OMIT_TRIGGER
  64618. case TK_RAISE: {
  64619. const char *zType = "unk";
  64620. switch( pExpr->affinity ){
  64621. case OE_Rollback: zType = "rollback"; break;
  64622. case OE_Abort: zType = "abort"; break;
  64623. case OE_Fail: zType = "fail"; break;
  64624. case OE_Ignore: zType = "ignore"; break;
  64625. }
  64626. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  64627. break;
  64628. }
  64629. #endif
  64630. }
  64631. if( zBinOp ){
  64632. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  64633. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64634. sqlite3ExplainPrintf(pOut,",");
  64635. sqlite3ExplainExpr(pOut, pExpr->pRight);
  64636. sqlite3ExplainPrintf(pOut,")");
  64637. }else if( zUniOp ){
  64638. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  64639. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64640. sqlite3ExplainPrintf(pOut,")");
  64641. }
  64642. }
  64643. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  64644. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64645. /*
  64646. ** Generate a human-readable explanation of an expression list.
  64647. */
  64648. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  64649. int i;
  64650. if( pList==0 || pList->nExpr==0 ){
  64651. sqlite3ExplainPrintf(pOut, "(empty-list)");
  64652. return;
  64653. }else if( pList->nExpr==1 ){
  64654. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  64655. }else{
  64656. sqlite3ExplainPush(pOut);
  64657. for(i=0; i<pList->nExpr; i++){
  64658. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  64659. sqlite3ExplainPush(pOut);
  64660. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  64661. sqlite3ExplainPop(pOut);
  64662. if( pList->a[i].zName ){
  64663. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  64664. }
  64665. if( pList->a[i].bSpanIsTab ){
  64666. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  64667. }
  64668. if( i<pList->nExpr-1 ){
  64669. sqlite3ExplainNL(pOut);
  64670. }
  64671. }
  64672. sqlite3ExplainPop(pOut);
  64673. }
  64674. }
  64675. #endif /* SQLITE_DEBUG */
  64676. /*
  64677. ** Return TRUE if pExpr is an constant expression that is appropriate
  64678. ** for factoring out of a loop. Appropriate expressions are:
  64679. **
  64680. ** * Any expression that evaluates to two or more opcodes.
  64681. **
  64682. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  64683. ** or OP_Variable that does not need to be placed in a
  64684. ** specific register.
  64685. **
  64686. ** There is no point in factoring out single-instruction constant
  64687. ** expressions that need to be placed in a particular register.
  64688. ** We could factor them out, but then we would end up adding an
  64689. ** OP_SCopy instruction to move the value into the correct register
  64690. ** later. We might as well just use the original instruction and
  64691. ** avoid the OP_SCopy.
  64692. */
  64693. static int isAppropriateForFactoring(Expr *p){
  64694. if( !sqlite3ExprIsConstantNotJoin(p) ){
  64695. return 0; /* Only constant expressions are appropriate for factoring */
  64696. }
  64697. if( (p->flags & EP_FixedDest)==0 ){
  64698. return 1; /* Any constant without a fixed destination is appropriate */
  64699. }
  64700. while( p->op==TK_UPLUS ) p = p->pLeft;
  64701. switch( p->op ){
  64702. #ifndef SQLITE_OMIT_BLOB_LITERAL
  64703. case TK_BLOB:
  64704. #endif
  64705. case TK_VARIABLE:
  64706. case TK_INTEGER:
  64707. case TK_FLOAT:
  64708. case TK_NULL:
  64709. case TK_STRING: {
  64710. testcase( p->op==TK_BLOB );
  64711. testcase( p->op==TK_VARIABLE );
  64712. testcase( p->op==TK_INTEGER );
  64713. testcase( p->op==TK_FLOAT );
  64714. testcase( p->op==TK_NULL );
  64715. testcase( p->op==TK_STRING );
  64716. /* Single-instruction constants with a fixed destination are
  64717. ** better done in-line. If we factor them, they will just end
  64718. ** up generating an OP_SCopy to move the value to the destination
  64719. ** register. */
  64720. return 0;
  64721. }
  64722. case TK_UMINUS: {
  64723. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  64724. return 0;
  64725. }
  64726. break;
  64727. }
  64728. default: {
  64729. break;
  64730. }
  64731. }
  64732. return 1;
  64733. }
  64734. /*
  64735. ** If pExpr is a constant expression that is appropriate for
  64736. ** factoring out of a loop, then evaluate the expression
  64737. ** into a register and convert the expression into a TK_REGISTER
  64738. ** expression.
  64739. */
  64740. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  64741. Parse *pParse = pWalker->pParse;
  64742. switch( pExpr->op ){
  64743. case TK_IN:
  64744. case TK_REGISTER: {
  64745. return WRC_Prune;
  64746. }
  64747. case TK_COLLATE: {
  64748. return WRC_Continue;
  64749. }
  64750. case TK_FUNCTION:
  64751. case TK_AGG_FUNCTION:
  64752. case TK_CONST_FUNC: {
  64753. /* The arguments to a function have a fixed destination.
  64754. ** Mark them this way to avoid generated unneeded OP_SCopy
  64755. ** instructions.
  64756. */
  64757. ExprList *pList = pExpr->x.pList;
  64758. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64759. if( pList ){
  64760. int i = pList->nExpr;
  64761. struct ExprList_item *pItem = pList->a;
  64762. for(; i>0; i--, pItem++){
  64763. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  64764. }
  64765. }
  64766. break;
  64767. }
  64768. }
  64769. if( isAppropriateForFactoring(pExpr) ){
  64770. int r1 = ++pParse->nMem;
  64771. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  64772. /* If r2!=r1, it means that register r1 is never used. That is harmless
  64773. ** but suboptimal, so we want to know about the situation to fix it.
  64774. ** Hence the following assert: */
  64775. assert( r2==r1 );
  64776. exprToRegister(pExpr, r2);
  64777. return WRC_Prune;
  64778. }
  64779. return WRC_Continue;
  64780. }
  64781. /*
  64782. ** Preevaluate constant subexpressions within pExpr and store the
  64783. ** results in registers. Modify pExpr so that the constant subexpresions
  64784. ** are TK_REGISTER opcodes that refer to the precomputed values.
  64785. **
  64786. ** This routine is a no-op if the jump to the cookie-check code has
  64787. ** already occur. Since the cookie-check jump is generated prior to
  64788. ** any other serious processing, this check ensures that there is no
  64789. ** way to accidently bypass the constant initializations.
  64790. **
  64791. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  64792. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  64793. ** interface. This allows test logic to verify that the same answer is
  64794. ** obtained for queries regardless of whether or not constants are
  64795. ** precomputed into registers or if they are inserted in-line.
  64796. */
  64797. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  64798. Walker w;
  64799. if( pParse->cookieGoto ) return;
  64800. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  64801. memset(&w, 0, sizeof(w));
  64802. w.xExprCallback = evalConstExpr;
  64803. w.pParse = pParse;
  64804. sqlite3WalkExpr(&w, pExpr);
  64805. }
  64806. /*
  64807. ** Generate code that pushes the value of every element of the given
  64808. ** expression list into a sequence of registers beginning at target.
  64809. **
  64810. ** Return the number of elements evaluated.
  64811. */
  64812. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  64813. Parse *pParse, /* Parsing context */
  64814. ExprList *pList, /* The expression list to be coded */
  64815. int target, /* Where to write results */
  64816. int doHardCopy /* Make a hard copy of every element */
  64817. ){
  64818. struct ExprList_item *pItem;
  64819. int i, n;
  64820. assert( pList!=0 );
  64821. assert( target>0 );
  64822. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  64823. n = pList->nExpr;
  64824. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  64825. Expr *pExpr = pItem->pExpr;
  64826. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  64827. if( inReg!=target+i ){
  64828. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  64829. inReg, target+i);
  64830. }
  64831. }
  64832. return n;
  64833. }
  64834. /*
  64835. ** Generate code for a BETWEEN operator.
  64836. **
  64837. ** x BETWEEN y AND z
  64838. **
  64839. ** The above is equivalent to
  64840. **
  64841. ** x>=y AND x<=z
  64842. **
  64843. ** Code it as such, taking care to do the common subexpression
  64844. ** elementation of x.
  64845. */
  64846. static void exprCodeBetween(
  64847. Parse *pParse, /* Parsing and code generating context */
  64848. Expr *pExpr, /* The BETWEEN expression */
  64849. int dest, /* Jump here if the jump is taken */
  64850. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  64851. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  64852. ){
  64853. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  64854. Expr compLeft; /* The x>=y term */
  64855. Expr compRight; /* The x<=z term */
  64856. Expr exprX; /* The x subexpression */
  64857. int regFree1 = 0; /* Temporary use register */
  64858. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64859. exprX = *pExpr->pLeft;
  64860. exprAnd.op = TK_AND;
  64861. exprAnd.pLeft = &compLeft;
  64862. exprAnd.pRight = &compRight;
  64863. compLeft.op = TK_GE;
  64864. compLeft.pLeft = &exprX;
  64865. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  64866. compRight.op = TK_LE;
  64867. compRight.pLeft = &exprX;
  64868. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  64869. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  64870. if( jumpIfTrue ){
  64871. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  64872. }else{
  64873. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  64874. }
  64875. sqlite3ReleaseTempReg(pParse, regFree1);
  64876. /* Ensure adequate test coverage */
  64877. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  64878. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  64879. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  64880. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  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. }
  64886. /*
  64887. ** Generate code for a boolean expression such that a jump is made
  64888. ** to the label "dest" if the expression is true but execution
  64889. ** continues straight thru if the expression is false.
  64890. **
  64891. ** If the expression evaluates to NULL (neither true nor false), then
  64892. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  64893. **
  64894. ** This code depends on the fact that certain token values (ex: TK_EQ)
  64895. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  64896. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  64897. ** the make process cause these values to align. Assert()s in the code
  64898. ** below verify that the numbers are aligned correctly.
  64899. */
  64900. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  64901. Vdbe *v = pParse->pVdbe;
  64902. int op = 0;
  64903. int regFree1 = 0;
  64904. int regFree2 = 0;
  64905. int r1, r2;
  64906. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  64907. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  64908. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  64909. op = pExpr->op;
  64910. switch( op ){
  64911. case TK_AND: {
  64912. int d2 = sqlite3VdbeMakeLabel(v);
  64913. testcase( jumpIfNull==0 );
  64914. sqlite3ExprCachePush(pParse);
  64915. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  64916. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  64917. sqlite3VdbeResolveLabel(v, d2);
  64918. sqlite3ExprCachePop(pParse, 1);
  64919. break;
  64920. }
  64921. case TK_OR: {
  64922. testcase( jumpIfNull==0 );
  64923. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  64924. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  64925. break;
  64926. }
  64927. case TK_NOT: {
  64928. testcase( jumpIfNull==0 );
  64929. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  64930. break;
  64931. }
  64932. case TK_LT:
  64933. case TK_LE:
  64934. case TK_GT:
  64935. case TK_GE:
  64936. case TK_NE:
  64937. case TK_EQ: {
  64938. assert( TK_LT==OP_Lt );
  64939. assert( TK_LE==OP_Le );
  64940. assert( TK_GT==OP_Gt );
  64941. assert( TK_GE==OP_Ge );
  64942. assert( TK_EQ==OP_Eq );
  64943. assert( TK_NE==OP_Ne );
  64944. testcase( op==TK_LT );
  64945. testcase( op==TK_LE );
  64946. testcase( op==TK_GT );
  64947. testcase( op==TK_GE );
  64948. testcase( op==TK_EQ );
  64949. testcase( op==TK_NE );
  64950. testcase( jumpIfNull==0 );
  64951. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64952. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  64953. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  64954. r1, r2, dest, jumpIfNull);
  64955. testcase( regFree1==0 );
  64956. testcase( regFree2==0 );
  64957. break;
  64958. }
  64959. case TK_IS:
  64960. case TK_ISNOT: {
  64961. testcase( op==TK_IS );
  64962. testcase( op==TK_ISNOT );
  64963. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64964. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  64965. op = (op==TK_IS) ? TK_EQ : TK_NE;
  64966. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  64967. r1, r2, dest, SQLITE_NULLEQ);
  64968. testcase( regFree1==0 );
  64969. testcase( regFree2==0 );
  64970. break;
  64971. }
  64972. case TK_ISNULL:
  64973. case TK_NOTNULL: {
  64974. assert( TK_ISNULL==OP_IsNull );
  64975. assert( TK_NOTNULL==OP_NotNull );
  64976. testcase( op==TK_ISNULL );
  64977. testcase( op==TK_NOTNULL );
  64978. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64979. sqlite3VdbeAddOp2(v, op, r1, dest);
  64980. testcase( regFree1==0 );
  64981. break;
  64982. }
  64983. case TK_BETWEEN: {
  64984. testcase( jumpIfNull==0 );
  64985. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  64986. break;
  64987. }
  64988. #ifndef SQLITE_OMIT_SUBQUERY
  64989. case TK_IN: {
  64990. int destIfFalse = sqlite3VdbeMakeLabel(v);
  64991. int destIfNull = jumpIfNull ? dest : destIfFalse;
  64992. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  64993. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  64994. sqlite3VdbeResolveLabel(v, destIfFalse);
  64995. break;
  64996. }
  64997. #endif
  64998. default: {
  64999. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  65000. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  65001. testcase( regFree1==0 );
  65002. testcase( jumpIfNull==0 );
  65003. break;
  65004. }
  65005. }
  65006. sqlite3ReleaseTempReg(pParse, regFree1);
  65007. sqlite3ReleaseTempReg(pParse, regFree2);
  65008. }
  65009. /*
  65010. ** Generate code for a boolean expression such that a jump is made
  65011. ** to the label "dest" if the expression is false but execution
  65012. ** continues straight thru if the expression is true.
  65013. **
  65014. ** If the expression evaluates to NULL (neither true nor false) then
  65015. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  65016. ** is 0.
  65017. */
  65018. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  65019. Vdbe *v = pParse->pVdbe;
  65020. int op = 0;
  65021. int regFree1 = 0;
  65022. int regFree2 = 0;
  65023. int r1, r2;
  65024. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  65025. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  65026. if( pExpr==0 ) return;
  65027. /* The value of pExpr->op and op are related as follows:
  65028. **
  65029. ** pExpr->op op
  65030. ** --------- ----------
  65031. ** TK_ISNULL OP_NotNull
  65032. ** TK_NOTNULL OP_IsNull
  65033. ** TK_NE OP_Eq
  65034. ** TK_EQ OP_Ne
  65035. ** TK_GT OP_Le
  65036. ** TK_LE OP_Gt
  65037. ** TK_GE OP_Lt
  65038. ** TK_LT OP_Ge
  65039. **
  65040. ** For other values of pExpr->op, op is undefined and unused.
  65041. ** The value of TK_ and OP_ constants are arranged such that we
  65042. ** can compute the mapping above using the following expression.
  65043. ** Assert()s verify that the computation is correct.
  65044. */
  65045. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  65046. /* Verify correct alignment of TK_ and OP_ constants
  65047. */
  65048. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  65049. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  65050. assert( pExpr->op!=TK_NE || op==OP_Eq );
  65051. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  65052. assert( pExpr->op!=TK_LT || op==OP_Ge );
  65053. assert( pExpr->op!=TK_LE || op==OP_Gt );
  65054. assert( pExpr->op!=TK_GT || op==OP_Le );
  65055. assert( pExpr->op!=TK_GE || op==OP_Lt );
  65056. switch( pExpr->op ){
  65057. case TK_AND: {
  65058. testcase( jumpIfNull==0 );
  65059. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  65060. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  65061. break;
  65062. }
  65063. case TK_OR: {
  65064. int d2 = sqlite3VdbeMakeLabel(v);
  65065. testcase( jumpIfNull==0 );
  65066. sqlite3ExprCachePush(pParse);
  65067. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  65068. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  65069. sqlite3VdbeResolveLabel(v, d2);
  65070. sqlite3ExprCachePop(pParse, 1);
  65071. break;
  65072. }
  65073. case TK_NOT: {
  65074. testcase( jumpIfNull==0 );
  65075. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  65076. break;
  65077. }
  65078. case TK_LT:
  65079. case TK_LE:
  65080. case TK_GT:
  65081. case TK_GE:
  65082. case TK_NE:
  65083. case TK_EQ: {
  65084. testcase( op==TK_LT );
  65085. testcase( op==TK_LE );
  65086. testcase( op==TK_GT );
  65087. testcase( op==TK_GE );
  65088. testcase( op==TK_EQ );
  65089. testcase( op==TK_NE );
  65090. testcase( jumpIfNull==0 );
  65091. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65092. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  65093. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  65094. r1, r2, dest, jumpIfNull);
  65095. testcase( regFree1==0 );
  65096. testcase( regFree2==0 );
  65097. break;
  65098. }
  65099. case TK_IS:
  65100. case TK_ISNOT: {
  65101. testcase( pExpr->op==TK_IS );
  65102. testcase( pExpr->op==TK_ISNOT );
  65103. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65104. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  65105. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  65106. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  65107. r1, r2, dest, SQLITE_NULLEQ);
  65108. testcase( regFree1==0 );
  65109. testcase( regFree2==0 );
  65110. break;
  65111. }
  65112. case TK_ISNULL:
  65113. case TK_NOTNULL: {
  65114. testcase( op==TK_ISNULL );
  65115. testcase( op==TK_NOTNULL );
  65116. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65117. sqlite3VdbeAddOp2(v, op, r1, dest);
  65118. testcase( regFree1==0 );
  65119. break;
  65120. }
  65121. case TK_BETWEEN: {
  65122. testcase( jumpIfNull==0 );
  65123. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  65124. break;
  65125. }
  65126. #ifndef SQLITE_OMIT_SUBQUERY
  65127. case TK_IN: {
  65128. if( jumpIfNull ){
  65129. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  65130. }else{
  65131. int destIfNull = sqlite3VdbeMakeLabel(v);
  65132. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  65133. sqlite3VdbeResolveLabel(v, destIfNull);
  65134. }
  65135. break;
  65136. }
  65137. #endif
  65138. default: {
  65139. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  65140. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  65141. testcase( regFree1==0 );
  65142. testcase( jumpIfNull==0 );
  65143. break;
  65144. }
  65145. }
  65146. sqlite3ReleaseTempReg(pParse, regFree1);
  65147. sqlite3ReleaseTempReg(pParse, regFree2);
  65148. }
  65149. /*
  65150. ** Do a deep comparison of two expression trees. Return 0 if the two
  65151. ** expressions are completely identical. Return 1 if they differ only
  65152. ** by a COLLATE operator at the top level. Return 2 if there are differences
  65153. ** other than the top-level COLLATE operator.
  65154. **
  65155. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  65156. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  65157. **
  65158. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  65159. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  65160. **
  65161. ** Sometimes this routine will return 2 even if the two expressions
  65162. ** really are equivalent. If we cannot prove that the expressions are
  65163. ** identical, we return 2 just to be safe. So if this routine
  65164. ** returns 2, then you do not really know for certain if the two
  65165. ** expressions are the same. But if you get a 0 or 1 return, then you
  65166. ** can be sure the expressions are the same. In the places where
  65167. ** this routine is used, it does not hurt to get an extra 2 - that
  65168. ** just might result in some slightly slower code. But returning
  65169. ** an incorrect 0 or 1 could lead to a malfunction.
  65170. */
  65171. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  65172. if( pA==0||pB==0 ){
  65173. return pB==pA ? 0 : 2;
  65174. }
  65175. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  65176. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  65177. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  65178. return 2;
  65179. }
  65180. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  65181. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  65182. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  65183. return 1;
  65184. }
  65185. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  65186. return 1;
  65187. }
  65188. return 2;
  65189. }
  65190. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  65191. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  65192. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  65193. if( pA->iColumn!=pB->iColumn ) return 2;
  65194. if( pA->iTable!=pB->iTable
  65195. && pA->op!=TK_REGISTER
  65196. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  65197. if( ExprHasProperty(pA, EP_IntValue) ){
  65198. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  65199. return 2;
  65200. }
  65201. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  65202. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  65203. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  65204. return pA->op==TK_COLLATE ? 1 : 2;
  65205. }
  65206. }
  65207. return 0;
  65208. }
  65209. /*
  65210. ** Compare two ExprList objects. Return 0 if they are identical and
  65211. ** non-zero if they differ in any way.
  65212. **
  65213. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  65214. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  65215. **
  65216. ** This routine might return non-zero for equivalent ExprLists. The
  65217. ** only consequence will be disabled optimizations. But this routine
  65218. ** must never return 0 if the two ExprList objects are different, or
  65219. ** a malfunction will result.
  65220. **
  65221. ** Two NULL pointers are considered to be the same. But a NULL pointer
  65222. ** always differs from a non-NULL pointer.
  65223. */
  65224. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  65225. int i;
  65226. if( pA==0 && pB==0 ) return 0;
  65227. if( pA==0 || pB==0 ) return 1;
  65228. if( pA->nExpr!=pB->nExpr ) return 1;
  65229. for(i=0; i<pA->nExpr; i++){
  65230. Expr *pExprA = pA->a[i].pExpr;
  65231. Expr *pExprB = pB->a[i].pExpr;
  65232. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  65233. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  65234. }
  65235. return 0;
  65236. }
  65237. /*
  65238. ** Return true if we can prove the pE2 will always be true if pE1 is
  65239. ** true. Return false if we cannot complete the proof or if pE2 might
  65240. ** be false. Examples:
  65241. **
  65242. ** pE1: x==5 pE2: x==5 Result: true
  65243. ** pE1: x>0 pE2: x==5 Result: false
  65244. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  65245. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  65246. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  65247. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  65248. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  65249. **
  65250. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  65251. ** Expr.iTable<0 then assume a table number given by iTab.
  65252. **
  65253. ** When in doubt, return false. Returning true might give a performance
  65254. ** improvement. Returning false might cause a performance reduction, but
  65255. ** it will always give the correct answer and is hence always safe.
  65256. */
  65257. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  65258. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  65259. return 1;
  65260. }
  65261. if( pE2->op==TK_OR
  65262. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  65263. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  65264. ){
  65265. return 1;
  65266. }
  65267. if( pE2->op==TK_NOTNULL
  65268. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  65269. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  65270. ){
  65271. return 1;
  65272. }
  65273. return 0;
  65274. }
  65275. /*
  65276. ** An instance of the following structure is used by the tree walker
  65277. ** to count references to table columns in the arguments of an
  65278. ** aggregate function, in order to implement the
  65279. ** sqlite3FunctionThisSrc() routine.
  65280. */
  65281. struct SrcCount {
  65282. SrcList *pSrc; /* One particular FROM clause in a nested query */
  65283. int nThis; /* Number of references to columns in pSrcList */
  65284. int nOther; /* Number of references to columns in other FROM clauses */
  65285. };
  65286. /*
  65287. ** Count the number of references to columns.
  65288. */
  65289. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  65290. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  65291. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  65292. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  65293. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  65294. ** NEVER() will need to be removed. */
  65295. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  65296. int i;
  65297. struct SrcCount *p = pWalker->u.pSrcCount;
  65298. SrcList *pSrc = p->pSrc;
  65299. for(i=0; i<pSrc->nSrc; i++){
  65300. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  65301. }
  65302. if( i<pSrc->nSrc ){
  65303. p->nThis++;
  65304. }else{
  65305. p->nOther++;
  65306. }
  65307. }
  65308. return WRC_Continue;
  65309. }
  65310. /*
  65311. ** Determine if any of the arguments to the pExpr Function reference
  65312. ** pSrcList. Return true if they do. Also return true if the function
  65313. ** has no arguments or has only constant arguments. Return false if pExpr
  65314. ** references columns but not columns of tables found in pSrcList.
  65315. */
  65316. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  65317. Walker w;
  65318. struct SrcCount cnt;
  65319. assert( pExpr->op==TK_AGG_FUNCTION );
  65320. memset(&w, 0, sizeof(w));
  65321. w.xExprCallback = exprSrcCount;
  65322. w.u.pSrcCount = &cnt;
  65323. cnt.pSrc = pSrcList;
  65324. cnt.nThis = 0;
  65325. cnt.nOther = 0;
  65326. sqlite3WalkExprList(&w, pExpr->x.pList);
  65327. return cnt.nThis>0 || cnt.nOther==0;
  65328. }
  65329. /*
  65330. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  65331. ** the new element. Return a negative number if malloc fails.
  65332. */
  65333. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  65334. int i;
  65335. pInfo->aCol = sqlite3ArrayAllocate(
  65336. db,
  65337. pInfo->aCol,
  65338. sizeof(pInfo->aCol[0]),
  65339. &pInfo->nColumn,
  65340. &i
  65341. );
  65342. return i;
  65343. }
  65344. /*
  65345. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  65346. ** the new element. Return a negative number if malloc fails.
  65347. */
  65348. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  65349. int i;
  65350. pInfo->aFunc = sqlite3ArrayAllocate(
  65351. db,
  65352. pInfo->aFunc,
  65353. sizeof(pInfo->aFunc[0]),
  65354. &pInfo->nFunc,
  65355. &i
  65356. );
  65357. return i;
  65358. }
  65359. /*
  65360. ** This is the xExprCallback for a tree walker. It is used to
  65361. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  65362. ** for additional information.
  65363. */
  65364. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  65365. int i;
  65366. NameContext *pNC = pWalker->u.pNC;
  65367. Parse *pParse = pNC->pParse;
  65368. SrcList *pSrcList = pNC->pSrcList;
  65369. AggInfo *pAggInfo = pNC->pAggInfo;
  65370. switch( pExpr->op ){
  65371. case TK_AGG_COLUMN:
  65372. case TK_COLUMN: {
  65373. testcase( pExpr->op==TK_AGG_COLUMN );
  65374. testcase( pExpr->op==TK_COLUMN );
  65375. /* Check to see if the column is in one of the tables in the FROM
  65376. ** clause of the aggregate query */
  65377. if( ALWAYS(pSrcList!=0) ){
  65378. struct SrcList_item *pItem = pSrcList->a;
  65379. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  65380. struct AggInfo_col *pCol;
  65381. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  65382. if( pExpr->iTable==pItem->iCursor ){
  65383. /* If we reach this point, it means that pExpr refers to a table
  65384. ** that is in the FROM clause of the aggregate query.
  65385. **
  65386. ** Make an entry for the column in pAggInfo->aCol[] if there
  65387. ** is not an entry there already.
  65388. */
  65389. int k;
  65390. pCol = pAggInfo->aCol;
  65391. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  65392. if( pCol->iTable==pExpr->iTable &&
  65393. pCol->iColumn==pExpr->iColumn ){
  65394. break;
  65395. }
  65396. }
  65397. if( (k>=pAggInfo->nColumn)
  65398. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  65399. ){
  65400. pCol = &pAggInfo->aCol[k];
  65401. pCol->pTab = pExpr->pTab;
  65402. pCol->iTable = pExpr->iTable;
  65403. pCol->iColumn = pExpr->iColumn;
  65404. pCol->iMem = ++pParse->nMem;
  65405. pCol->iSorterColumn = -1;
  65406. pCol->pExpr = pExpr;
  65407. if( pAggInfo->pGroupBy ){
  65408. int j, n;
  65409. ExprList *pGB = pAggInfo->pGroupBy;
  65410. struct ExprList_item *pTerm = pGB->a;
  65411. n = pGB->nExpr;
  65412. for(j=0; j<n; j++, pTerm++){
  65413. Expr *pE = pTerm->pExpr;
  65414. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  65415. pE->iColumn==pExpr->iColumn ){
  65416. pCol->iSorterColumn = j;
  65417. break;
  65418. }
  65419. }
  65420. }
  65421. if( pCol->iSorterColumn<0 ){
  65422. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  65423. }
  65424. }
  65425. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  65426. ** because it was there before or because we just created it).
  65427. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  65428. ** pAggInfo->aCol[] entry.
  65429. */
  65430. ExprSetVVAProperty(pExpr, EP_NoReduce);
  65431. pExpr->pAggInfo = pAggInfo;
  65432. pExpr->op = TK_AGG_COLUMN;
  65433. pExpr->iAgg = (i16)k;
  65434. break;
  65435. } /* endif pExpr->iTable==pItem->iCursor */
  65436. } /* end loop over pSrcList */
  65437. }
  65438. return WRC_Prune;
  65439. }
  65440. case TK_AGG_FUNCTION: {
  65441. if( (pNC->ncFlags & NC_InAggFunc)==0
  65442. && pWalker->walkerDepth==pExpr->op2
  65443. ){
  65444. /* Check to see if pExpr is a duplicate of another aggregate
  65445. ** function that is already in the pAggInfo structure
  65446. */
  65447. struct AggInfo_func *pItem = pAggInfo->aFunc;
  65448. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  65449. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  65450. break;
  65451. }
  65452. }
  65453. if( i>=pAggInfo->nFunc ){
  65454. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  65455. */
  65456. u8 enc = ENC(pParse->db);
  65457. i = addAggInfoFunc(pParse->db, pAggInfo);
  65458. if( i>=0 ){
  65459. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  65460. pItem = &pAggInfo->aFunc[i];
  65461. pItem->pExpr = pExpr;
  65462. pItem->iMem = ++pParse->nMem;
  65463. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  65464. pItem->pFunc = sqlite3FindFunction(pParse->db,
  65465. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  65466. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  65467. if( pExpr->flags & EP_Distinct ){
  65468. pItem->iDistinct = pParse->nTab++;
  65469. }else{
  65470. pItem->iDistinct = -1;
  65471. }
  65472. }
  65473. }
  65474. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  65475. */
  65476. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  65477. ExprSetVVAProperty(pExpr, EP_NoReduce);
  65478. pExpr->iAgg = (i16)i;
  65479. pExpr->pAggInfo = pAggInfo;
  65480. return WRC_Prune;
  65481. }else{
  65482. return WRC_Continue;
  65483. }
  65484. }
  65485. }
  65486. return WRC_Continue;
  65487. }
  65488. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  65489. UNUSED_PARAMETER(pWalker);
  65490. UNUSED_PARAMETER(pSelect);
  65491. return WRC_Continue;
  65492. }
  65493. /*
  65494. ** Analyze the pExpr expression looking for aggregate functions and
  65495. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  65496. ** points to. Additional entries are made on the AggInfo object as
  65497. ** necessary.
  65498. **
  65499. ** This routine should only be called after the expression has been
  65500. ** analyzed by sqlite3ResolveExprNames().
  65501. */
  65502. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  65503. Walker w;
  65504. memset(&w, 0, sizeof(w));
  65505. w.xExprCallback = analyzeAggregate;
  65506. w.xSelectCallback = analyzeAggregatesInSelect;
  65507. w.u.pNC = pNC;
  65508. assert( pNC->pSrcList!=0 );
  65509. sqlite3WalkExpr(&w, pExpr);
  65510. }
  65511. /*
  65512. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  65513. ** expression list. Return the number of errors.
  65514. **
  65515. ** If an error is found, the analysis is cut short.
  65516. */
  65517. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  65518. struct ExprList_item *pItem;
  65519. int i;
  65520. if( pList ){
  65521. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  65522. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  65523. }
  65524. }
  65525. }
  65526. /*
  65527. ** Allocate a single new register for use to hold some intermediate result.
  65528. */
  65529. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  65530. if( pParse->nTempReg==0 ){
  65531. return ++pParse->nMem;
  65532. }
  65533. return pParse->aTempReg[--pParse->nTempReg];
  65534. }
  65535. /*
  65536. ** Deallocate a register, making available for reuse for some other
  65537. ** purpose.
  65538. **
  65539. ** If a register is currently being used by the column cache, then
  65540. ** the dallocation is deferred until the column cache line that uses
  65541. ** the register becomes stale.
  65542. */
  65543. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  65544. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  65545. int i;
  65546. struct yColCache *p;
  65547. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  65548. if( p->iReg==iReg ){
  65549. p->tempReg = 1;
  65550. return;
  65551. }
  65552. }
  65553. pParse->aTempReg[pParse->nTempReg++] = iReg;
  65554. }
  65555. }
  65556. /*
  65557. ** Allocate or deallocate a block of nReg consecutive registers
  65558. */
  65559. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  65560. int i, n;
  65561. i = pParse->iRangeReg;
  65562. n = pParse->nRangeReg;
  65563. if( nReg<=n ){
  65564. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  65565. pParse->iRangeReg += nReg;
  65566. pParse->nRangeReg -= nReg;
  65567. }else{
  65568. i = pParse->nMem+1;
  65569. pParse->nMem += nReg;
  65570. }
  65571. return i;
  65572. }
  65573. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  65574. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  65575. if( nReg>pParse->nRangeReg ){
  65576. pParse->nRangeReg = nReg;
  65577. pParse->iRangeReg = iReg;
  65578. }
  65579. }
  65580. /*
  65581. ** Mark all temporary registers as being unavailable for reuse.
  65582. */
  65583. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  65584. pParse->nTempReg = 0;
  65585. pParse->nRangeReg = 0;
  65586. }
  65587. /************** End of expr.c ************************************************/
  65588. /************** Begin file alter.c *******************************************/
  65589. /*
  65590. ** 2005 February 15
  65591. **
  65592. ** The author disclaims copyright to this source code. In place of
  65593. ** a legal notice, here is a blessing:
  65594. **
  65595. ** May you do good and not evil.
  65596. ** May you find forgiveness for yourself and forgive others.
  65597. ** May you share freely, never taking more than you give.
  65598. **
  65599. *************************************************************************
  65600. ** This file contains C code routines that used to generate VDBE code
  65601. ** that implements the ALTER TABLE command.
  65602. */
  65603. /*
  65604. ** The code in this file only exists if we are not omitting the
  65605. ** ALTER TABLE logic from the build.
  65606. */
  65607. #ifndef SQLITE_OMIT_ALTERTABLE
  65608. /*
  65609. ** This function is used by SQL generated to implement the
  65610. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  65611. ** CREATE INDEX command. The second is a table name. The table name in
  65612. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  65613. ** argument and the result returned. Examples:
  65614. **
  65615. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  65616. ** -> 'CREATE TABLE def(a, b, c)'
  65617. **
  65618. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  65619. ** -> 'CREATE INDEX i ON def(a, b, c)'
  65620. */
  65621. static void renameTableFunc(
  65622. sqlite3_context *context,
  65623. int NotUsed,
  65624. sqlite3_value **argv
  65625. ){
  65626. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  65627. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  65628. int token;
  65629. Token tname;
  65630. unsigned char const *zCsr = zSql;
  65631. int len = 0;
  65632. char *zRet;
  65633. sqlite3 *db = sqlite3_context_db_handle(context);
  65634. UNUSED_PARAMETER(NotUsed);
  65635. /* The principle used to locate the table name in the CREATE TABLE
  65636. ** statement is that the table name is the first non-space token that
  65637. ** is immediately followed by a TK_LP or TK_USING token.
  65638. */
  65639. if( zSql ){
  65640. do {
  65641. if( !*zCsr ){
  65642. /* Ran out of input before finding an opening bracket. Return NULL. */
  65643. return;
  65644. }
  65645. /* Store the token that zCsr points to in tname. */
  65646. tname.z = (char*)zCsr;
  65647. tname.n = len;
  65648. /* Advance zCsr to the next token. Store that token type in 'token',
  65649. ** and its length in 'len' (to be used next iteration of this loop).
  65650. */
  65651. do {
  65652. zCsr += len;
  65653. len = sqlite3GetToken(zCsr, &token);
  65654. } while( token==TK_SPACE );
  65655. assert( len>0 );
  65656. } while( token!=TK_LP && token!=TK_USING );
  65657. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  65658. zTableName, tname.z+tname.n);
  65659. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  65660. }
  65661. }
  65662. /*
  65663. ** This C function implements an SQL user function that is used by SQL code
  65664. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  65665. ** of any foreign key constraints that use the table being renamed as the
  65666. ** parent table. It is passed three arguments:
  65667. **
  65668. ** 1) The complete text of the CREATE TABLE statement being modified,
  65669. ** 2) The old name of the table being renamed, and
  65670. ** 3) The new name of the table being renamed.
  65671. **
  65672. ** It returns the new CREATE TABLE statement. For example:
  65673. **
  65674. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  65675. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  65676. */
  65677. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65678. static void renameParentFunc(
  65679. sqlite3_context *context,
  65680. int NotUsed,
  65681. sqlite3_value **argv
  65682. ){
  65683. sqlite3 *db = sqlite3_context_db_handle(context);
  65684. char *zOutput = 0;
  65685. char *zResult;
  65686. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  65687. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  65688. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  65689. unsigned const char *z; /* Pointer to token */
  65690. int n; /* Length of token z */
  65691. int token; /* Type of token */
  65692. UNUSED_PARAMETER(NotUsed);
  65693. for(z=zInput; *z; z=z+n){
  65694. n = sqlite3GetToken(z, &token);
  65695. if( token==TK_REFERENCES ){
  65696. char *zParent;
  65697. do {
  65698. z += n;
  65699. n = sqlite3GetToken(z, &token);
  65700. }while( token==TK_SPACE );
  65701. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  65702. if( zParent==0 ) break;
  65703. sqlite3Dequote(zParent);
  65704. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  65705. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  65706. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  65707. );
  65708. sqlite3DbFree(db, zOutput);
  65709. zOutput = zOut;
  65710. zInput = &z[n];
  65711. }
  65712. sqlite3DbFree(db, zParent);
  65713. }
  65714. }
  65715. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  65716. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  65717. sqlite3DbFree(db, zOutput);
  65718. }
  65719. #endif
  65720. #ifndef SQLITE_OMIT_TRIGGER
  65721. /* This function is used by SQL generated to implement the
  65722. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  65723. ** statement. The second is a table name. The table name in the CREATE
  65724. ** TRIGGER statement is replaced with the third argument and the result
  65725. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  65726. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  65727. */
  65728. static void renameTriggerFunc(
  65729. sqlite3_context *context,
  65730. int NotUsed,
  65731. sqlite3_value **argv
  65732. ){
  65733. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  65734. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  65735. int token;
  65736. Token tname;
  65737. int dist = 3;
  65738. unsigned char const *zCsr = zSql;
  65739. int len = 0;
  65740. char *zRet;
  65741. sqlite3 *db = sqlite3_context_db_handle(context);
  65742. UNUSED_PARAMETER(NotUsed);
  65743. /* The principle used to locate the table name in the CREATE TRIGGER
  65744. ** statement is that the table name is the first token that is immediatedly
  65745. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  65746. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  65747. */
  65748. if( zSql ){
  65749. do {
  65750. if( !*zCsr ){
  65751. /* Ran out of input before finding the table name. Return NULL. */
  65752. return;
  65753. }
  65754. /* Store the token that zCsr points to in tname. */
  65755. tname.z = (char*)zCsr;
  65756. tname.n = len;
  65757. /* Advance zCsr to the next token. Store that token type in 'token',
  65758. ** and its length in 'len' (to be used next iteration of this loop).
  65759. */
  65760. do {
  65761. zCsr += len;
  65762. len = sqlite3GetToken(zCsr, &token);
  65763. }while( token==TK_SPACE );
  65764. assert( len>0 );
  65765. /* Variable 'dist' stores the number of tokens read since the most
  65766. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  65767. ** token is read and 'dist' equals 2, the condition stated above
  65768. ** to be met.
  65769. **
  65770. ** Note that ON cannot be a database, table or column name, so
  65771. ** there is no need to worry about syntax like
  65772. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  65773. */
  65774. dist++;
  65775. if( token==TK_DOT || token==TK_ON ){
  65776. dist = 0;
  65777. }
  65778. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  65779. /* Variable tname now contains the token that is the old table-name
  65780. ** in the CREATE TRIGGER statement.
  65781. */
  65782. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  65783. zTableName, tname.z+tname.n);
  65784. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  65785. }
  65786. }
  65787. #endif /* !SQLITE_OMIT_TRIGGER */
  65788. /*
  65789. ** Register built-in functions used to help implement ALTER TABLE
  65790. */
  65791. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  65792. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  65793. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  65794. #ifndef SQLITE_OMIT_TRIGGER
  65795. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  65796. #endif
  65797. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65798. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  65799. #endif
  65800. };
  65801. int i;
  65802. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  65803. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  65804. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  65805. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  65806. }
  65807. }
  65808. /*
  65809. ** This function is used to create the text of expressions of the form:
  65810. **
  65811. ** name=<constant1> OR name=<constant2> OR ...
  65812. **
  65813. ** If argument zWhere is NULL, then a pointer string containing the text
  65814. ** "name=<constant>" is returned, where <constant> is the quoted version
  65815. ** of the string passed as argument zConstant. The returned buffer is
  65816. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  65817. ** caller to ensure that it is eventually freed.
  65818. **
  65819. ** If argument zWhere is not NULL, then the string returned is
  65820. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  65821. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  65822. **
  65823. */
  65824. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  65825. char *zNew;
  65826. if( !zWhere ){
  65827. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  65828. }else{
  65829. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  65830. sqlite3DbFree(db, zWhere);
  65831. }
  65832. return zNew;
  65833. }
  65834. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  65835. /*
  65836. ** Generate the text of a WHERE expression which can be used to select all
  65837. ** tables that have foreign key constraints that refer to table pTab (i.e.
  65838. ** constraints for which pTab is the parent table) from the sqlite_master
  65839. ** table.
  65840. */
  65841. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  65842. FKey *p;
  65843. char *zWhere = 0;
  65844. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  65845. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  65846. }
  65847. return zWhere;
  65848. }
  65849. #endif
  65850. /*
  65851. ** Generate the text of a WHERE expression which can be used to select all
  65852. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  65853. ** table pTab has no temporary triggers, or is itself stored in the
  65854. ** temporary database, NULL is returned.
  65855. */
  65856. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  65857. Trigger *pTrig;
  65858. char *zWhere = 0;
  65859. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  65860. /* If the table is not located in the temp-db (in which case NULL is
  65861. ** returned, loop through the tables list of triggers. For each trigger
  65862. ** that is not part of the temp-db schema, add a clause to the WHERE
  65863. ** expression being built up in zWhere.
  65864. */
  65865. if( pTab->pSchema!=pTempSchema ){
  65866. sqlite3 *db = pParse->db;
  65867. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  65868. if( pTrig->pSchema==pTempSchema ){
  65869. zWhere = whereOrName(db, zWhere, pTrig->zName);
  65870. }
  65871. }
  65872. }
  65873. if( zWhere ){
  65874. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  65875. sqlite3DbFree(pParse->db, zWhere);
  65876. zWhere = zNew;
  65877. }
  65878. return zWhere;
  65879. }
  65880. /*
  65881. ** Generate code to drop and reload the internal representation of table
  65882. ** pTab from the database, including triggers and temporary triggers.
  65883. ** Argument zName is the name of the table in the database schema at
  65884. ** the time the generated code is executed. This can be different from
  65885. ** pTab->zName if this function is being called to code part of an
  65886. ** "ALTER TABLE RENAME TO" statement.
  65887. */
  65888. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  65889. Vdbe *v;
  65890. char *zWhere;
  65891. int iDb; /* Index of database containing pTab */
  65892. #ifndef SQLITE_OMIT_TRIGGER
  65893. Trigger *pTrig;
  65894. #endif
  65895. v = sqlite3GetVdbe(pParse);
  65896. if( NEVER(v==0) ) return;
  65897. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  65898. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  65899. assert( iDb>=0 );
  65900. #ifndef SQLITE_OMIT_TRIGGER
  65901. /* Drop any table triggers from the internal schema. */
  65902. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  65903. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  65904. assert( iTrigDb==iDb || iTrigDb==1 );
  65905. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  65906. }
  65907. #endif
  65908. /* Drop the table and index from the internal schema. */
  65909. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  65910. /* Reload the table, index and permanent trigger schemas. */
  65911. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  65912. if( !zWhere ) return;
  65913. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  65914. #ifndef SQLITE_OMIT_TRIGGER
  65915. /* Now, if the table is not stored in the temp database, reload any temp
  65916. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  65917. */
  65918. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  65919. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  65920. }
  65921. #endif
  65922. }
  65923. /*
  65924. ** Parameter zName is the name of a table that is about to be altered
  65925. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  65926. ** If the table is a system table, this function leaves an error message
  65927. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  65928. **
  65929. ** Or, if zName is not a system table, zero is returned.
  65930. */
  65931. static int isSystemTable(Parse *pParse, const char *zName){
  65932. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  65933. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  65934. return 1;
  65935. }
  65936. return 0;
  65937. }
  65938. /*
  65939. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  65940. ** command.
  65941. */
  65942. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  65943. Parse *pParse, /* Parser context. */
  65944. SrcList *pSrc, /* The table to rename. */
  65945. Token *pName /* The new table name. */
  65946. ){
  65947. int iDb; /* Database that contains the table */
  65948. char *zDb; /* Name of database iDb */
  65949. Table *pTab; /* Table being renamed */
  65950. char *zName = 0; /* NULL-terminated version of pName */
  65951. sqlite3 *db = pParse->db; /* Database connection */
  65952. int nTabName; /* Number of UTF-8 characters in zTabName */
  65953. const char *zTabName; /* Original name of the table */
  65954. Vdbe *v;
  65955. #ifndef SQLITE_OMIT_TRIGGER
  65956. char *zWhere = 0; /* Where clause to locate temp triggers */
  65957. #endif
  65958. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  65959. int savedDbFlags; /* Saved value of db->flags */
  65960. savedDbFlags = db->flags;
  65961. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  65962. assert( pSrc->nSrc==1 );
  65963. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  65964. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  65965. if( !pTab ) goto exit_rename_table;
  65966. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  65967. zDb = db->aDb[iDb].zName;
  65968. db->flags |= SQLITE_PreferBuiltin;
  65969. /* Get a NULL terminated version of the new table name. */
  65970. zName = sqlite3NameFromToken(db, pName);
  65971. if( !zName ) goto exit_rename_table;
  65972. /* Check that a table or index named 'zName' does not already exist
  65973. ** in database iDb. If so, this is an error.
  65974. */
  65975. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  65976. sqlite3ErrorMsg(pParse,
  65977. "there is already another table or index with this name: %s", zName);
  65978. goto exit_rename_table;
  65979. }
  65980. /* Make sure it is not a system table being altered, or a reserved name
  65981. ** that the table is being renamed to.
  65982. */
  65983. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  65984. goto exit_rename_table;
  65985. }
  65986. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  65987. exit_rename_table;
  65988. }
  65989. #ifndef SQLITE_OMIT_VIEW
  65990. if( pTab->pSelect ){
  65991. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  65992. goto exit_rename_table;
  65993. }
  65994. #endif
  65995. #ifndef SQLITE_OMIT_AUTHORIZATION
  65996. /* Invoke the authorization callback. */
  65997. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  65998. goto exit_rename_table;
  65999. }
  66000. #endif
  66001. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66002. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  66003. goto exit_rename_table;
  66004. }
  66005. if( IsVirtual(pTab) ){
  66006. pVTab = sqlite3GetVTable(db, pTab);
  66007. if( pVTab->pVtab->pModule->xRename==0 ){
  66008. pVTab = 0;
  66009. }
  66010. }
  66011. #endif
  66012. /* Begin a transaction and code the VerifyCookie for database iDb.
  66013. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  66014. ** schema). Open a statement transaction if the table is a virtual
  66015. ** table.
  66016. */
  66017. v = sqlite3GetVdbe(pParse);
  66018. if( v==0 ){
  66019. goto exit_rename_table;
  66020. }
  66021. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  66022. sqlite3ChangeCookie(pParse, iDb);
  66023. /* If this is a virtual table, invoke the xRename() function if
  66024. ** one is defined. The xRename() callback will modify the names
  66025. ** of any resources used by the v-table implementation (including other
  66026. ** SQLite tables) that are identified by the name of the virtual table.
  66027. */
  66028. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66029. if( pVTab ){
  66030. int i = ++pParse->nMem;
  66031. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  66032. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  66033. sqlite3MayAbort(pParse);
  66034. }
  66035. #endif
  66036. /* figure out how many UTF-8 characters are in zName */
  66037. zTabName = pTab->zName;
  66038. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  66039. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  66040. if( db->flags&SQLITE_ForeignKeys ){
  66041. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  66042. ** statements corresponding to all child tables of foreign key constraints
  66043. ** for which the renamed table is the parent table. */
  66044. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  66045. sqlite3NestedParse(pParse,
  66046. "UPDATE \"%w\".%s SET "
  66047. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  66048. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  66049. sqlite3DbFree(db, zWhere);
  66050. }
  66051. }
  66052. #endif
  66053. /* Modify the sqlite_master table to use the new table name. */
  66054. sqlite3NestedParse(pParse,
  66055. "UPDATE %Q.%s SET "
  66056. #ifdef SQLITE_OMIT_TRIGGER
  66057. "sql = sqlite_rename_table(sql, %Q), "
  66058. #else
  66059. "sql = CASE "
  66060. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  66061. "ELSE sqlite_rename_table(sql, %Q) END, "
  66062. #endif
  66063. "tbl_name = %Q, "
  66064. "name = CASE "
  66065. "WHEN type='table' THEN %Q "
  66066. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  66067. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  66068. "ELSE name END "
  66069. "WHERE tbl_name=%Q COLLATE nocase AND "
  66070. "(type='table' OR type='index' OR type='trigger');",
  66071. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  66072. #ifndef SQLITE_OMIT_TRIGGER
  66073. zName,
  66074. #endif
  66075. zName, nTabName, zTabName
  66076. );
  66077. #ifndef SQLITE_OMIT_AUTOINCREMENT
  66078. /* If the sqlite_sequence table exists in this database, then update
  66079. ** it with the new table name.
  66080. */
  66081. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  66082. sqlite3NestedParse(pParse,
  66083. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  66084. zDb, zName, pTab->zName);
  66085. }
  66086. #endif
  66087. #ifndef SQLITE_OMIT_TRIGGER
  66088. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  66089. ** table. Don't do this if the table being ALTERed is itself located in
  66090. ** the temp database.
  66091. */
  66092. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  66093. sqlite3NestedParse(pParse,
  66094. "UPDATE sqlite_temp_master SET "
  66095. "sql = sqlite_rename_trigger(sql, %Q), "
  66096. "tbl_name = %Q "
  66097. "WHERE %s;", zName, zName, zWhere);
  66098. sqlite3DbFree(db, zWhere);
  66099. }
  66100. #endif
  66101. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  66102. if( db->flags&SQLITE_ForeignKeys ){
  66103. FKey *p;
  66104. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  66105. Table *pFrom = p->pFrom;
  66106. if( pFrom!=pTab ){
  66107. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  66108. }
  66109. }
  66110. }
  66111. #endif
  66112. /* Drop and reload the internal table schema. */
  66113. reloadTableSchema(pParse, pTab, zName);
  66114. exit_rename_table:
  66115. sqlite3SrcListDelete(db, pSrc);
  66116. sqlite3DbFree(db, zName);
  66117. db->flags = savedDbFlags;
  66118. }
  66119. /*
  66120. ** Generate code to make sure the file format number is at least minFormat.
  66121. ** The generated code will increase the file format number if necessary.
  66122. */
  66123. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  66124. Vdbe *v;
  66125. v = sqlite3GetVdbe(pParse);
  66126. /* The VDBE should have been allocated before this routine is called.
  66127. ** If that allocation failed, we would have quit before reaching this
  66128. ** point */
  66129. if( ALWAYS(v) ){
  66130. int r1 = sqlite3GetTempReg(pParse);
  66131. int r2 = sqlite3GetTempReg(pParse);
  66132. int j1;
  66133. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  66134. sqlite3VdbeUsesBtree(v, iDb);
  66135. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  66136. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  66137. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  66138. sqlite3VdbeJumpHere(v, j1);
  66139. sqlite3ReleaseTempReg(pParse, r1);
  66140. sqlite3ReleaseTempReg(pParse, r2);
  66141. }
  66142. }
  66143. /*
  66144. ** This function is called after an "ALTER TABLE ... ADD" statement
  66145. ** has been parsed. Argument pColDef contains the text of the new
  66146. ** column definition.
  66147. **
  66148. ** The Table structure pParse->pNewTable was extended to include
  66149. ** the new column during parsing.
  66150. */
  66151. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  66152. Table *pNew; /* Copy of pParse->pNewTable */
  66153. Table *pTab; /* Table being altered */
  66154. int iDb; /* Database number */
  66155. const char *zDb; /* Database name */
  66156. const char *zTab; /* Table name */
  66157. char *zCol; /* Null-terminated column definition */
  66158. Column *pCol; /* The new column */
  66159. Expr *pDflt; /* Default value for the new column */
  66160. sqlite3 *db; /* The database connection; */
  66161. db = pParse->db;
  66162. if( pParse->nErr || db->mallocFailed ) return;
  66163. pNew = pParse->pNewTable;
  66164. assert( pNew );
  66165. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66166. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  66167. zDb = db->aDb[iDb].zName;
  66168. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  66169. pCol = &pNew->aCol[pNew->nCol-1];
  66170. pDflt = pCol->pDflt;
  66171. pTab = sqlite3FindTable(db, zTab, zDb);
  66172. assert( pTab );
  66173. #ifndef SQLITE_OMIT_AUTHORIZATION
  66174. /* Invoke the authorization callback. */
  66175. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  66176. return;
  66177. }
  66178. #endif
  66179. /* If the default value for the new column was specified with a
  66180. ** literal NULL, then set pDflt to 0. This simplifies checking
  66181. ** for an SQL NULL default below.
  66182. */
  66183. if( pDflt && pDflt->op==TK_NULL ){
  66184. pDflt = 0;
  66185. }
  66186. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  66187. ** If there is a NOT NULL constraint, then the default value for the
  66188. ** column must not be NULL.
  66189. */
  66190. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  66191. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  66192. return;
  66193. }
  66194. if( pNew->pIndex ){
  66195. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  66196. return;
  66197. }
  66198. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  66199. sqlite3ErrorMsg(pParse,
  66200. "Cannot add a REFERENCES column with non-NULL default value");
  66201. return;
  66202. }
  66203. if( pCol->notNull && !pDflt ){
  66204. sqlite3ErrorMsg(pParse,
  66205. "Cannot add a NOT NULL column with default value NULL");
  66206. return;
  66207. }
  66208. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  66209. ** can handle (i.e. not CURRENT_TIME etc.)
  66210. */
  66211. if( pDflt ){
  66212. sqlite3_value *pVal = 0;
  66213. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  66214. db->mallocFailed = 1;
  66215. return;
  66216. }
  66217. if( !pVal ){
  66218. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  66219. return;
  66220. }
  66221. sqlite3ValueFree(pVal);
  66222. }
  66223. /* Modify the CREATE TABLE statement. */
  66224. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  66225. if( zCol ){
  66226. char *zEnd = &zCol[pColDef->n-1];
  66227. int savedDbFlags = db->flags;
  66228. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  66229. *zEnd-- = '\0';
  66230. }
  66231. db->flags |= SQLITE_PreferBuiltin;
  66232. sqlite3NestedParse(pParse,
  66233. "UPDATE \"%w\".%s SET "
  66234. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  66235. "WHERE type = 'table' AND name = %Q",
  66236. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  66237. zTab
  66238. );
  66239. sqlite3DbFree(db, zCol);
  66240. db->flags = savedDbFlags;
  66241. }
  66242. /* If the default value of the new column is NULL, then set the file
  66243. ** format to 2. If the default value of the new column is not NULL,
  66244. ** the file format becomes 3.
  66245. */
  66246. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  66247. /* Reload the schema of the modified table. */
  66248. reloadTableSchema(pParse, pTab, pTab->zName);
  66249. }
  66250. /*
  66251. ** This function is called by the parser after the table-name in
  66252. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  66253. ** pSrc is the full-name of the table being altered.
  66254. **
  66255. ** This routine makes a (partial) copy of the Table structure
  66256. ** for the table being altered and sets Parse.pNewTable to point
  66257. ** to it. Routines called by the parser as the column definition
  66258. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  66259. ** the copy. The copy of the Table structure is deleted by tokenize.c
  66260. ** after parsing is finished.
  66261. **
  66262. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  66263. ** coding the "ALTER TABLE ... ADD" statement.
  66264. */
  66265. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  66266. Table *pNew;
  66267. Table *pTab;
  66268. Vdbe *v;
  66269. int iDb;
  66270. int i;
  66271. int nAlloc;
  66272. sqlite3 *db = pParse->db;
  66273. /* Look up the table being altered. */
  66274. assert( pParse->pNewTable==0 );
  66275. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66276. if( db->mallocFailed ) goto exit_begin_add_column;
  66277. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  66278. if( !pTab ) goto exit_begin_add_column;
  66279. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66280. if( IsVirtual(pTab) ){
  66281. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  66282. goto exit_begin_add_column;
  66283. }
  66284. #endif
  66285. /* Make sure this is not an attempt to ALTER a view. */
  66286. if( pTab->pSelect ){
  66287. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  66288. goto exit_begin_add_column;
  66289. }
  66290. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  66291. goto exit_begin_add_column;
  66292. }
  66293. assert( pTab->addColOffset>0 );
  66294. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  66295. /* Put a copy of the Table struct in Parse.pNewTable for the
  66296. ** sqlite3AddColumn() function and friends to modify. But modify
  66297. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  66298. ** prefix, we insure that the name will not collide with an existing
  66299. ** table because user table are not allowed to have the "sqlite_"
  66300. ** prefix on their name.
  66301. */
  66302. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  66303. if( !pNew ) goto exit_begin_add_column;
  66304. pParse->pNewTable = pNew;
  66305. pNew->nRef = 1;
  66306. pNew->nCol = pTab->nCol;
  66307. assert( pNew->nCol>0 );
  66308. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  66309. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  66310. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  66311. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  66312. if( !pNew->aCol || !pNew->zName ){
  66313. db->mallocFailed = 1;
  66314. goto exit_begin_add_column;
  66315. }
  66316. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  66317. for(i=0; i<pNew->nCol; i++){
  66318. Column *pCol = &pNew->aCol[i];
  66319. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  66320. pCol->zColl = 0;
  66321. pCol->zType = 0;
  66322. pCol->pDflt = 0;
  66323. pCol->zDflt = 0;
  66324. }
  66325. pNew->pSchema = db->aDb[iDb].pSchema;
  66326. pNew->addColOffset = pTab->addColOffset;
  66327. pNew->nRef = 1;
  66328. /* Begin a transaction and increment the schema cookie. */
  66329. sqlite3BeginWriteOperation(pParse, 0, iDb);
  66330. v = sqlite3GetVdbe(pParse);
  66331. if( !v ) goto exit_begin_add_column;
  66332. sqlite3ChangeCookie(pParse, iDb);
  66333. exit_begin_add_column:
  66334. sqlite3SrcListDelete(db, pSrc);
  66335. return;
  66336. }
  66337. #endif /* SQLITE_ALTER_TABLE */
  66338. /************** End of alter.c ***********************************************/
  66339. /************** Begin file analyze.c *****************************************/
  66340. /*
  66341. ** 2005-07-08
  66342. **
  66343. ** The author disclaims copyright to this source code. In place of
  66344. ** a legal notice, here is a blessing:
  66345. **
  66346. ** May you do good and not evil.
  66347. ** May you find forgiveness for yourself and forgive others.
  66348. ** May you share freely, never taking more than you give.
  66349. **
  66350. *************************************************************************
  66351. ** This file contains code associated with the ANALYZE command.
  66352. **
  66353. ** The ANALYZE command gather statistics about the content of tables
  66354. ** and indices. These statistics are made available to the query planner
  66355. ** to help it make better decisions about how to perform queries.
  66356. **
  66357. ** The following system tables are or have been supported:
  66358. **
  66359. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  66360. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  66361. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  66362. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  66363. **
  66364. ** Additional tables might be added in future releases of SQLite.
  66365. ** The sqlite_stat2 table is not created or used unless the SQLite version
  66366. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  66367. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  66368. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  66369. ** created and used by SQLite versions 3.7.9 and later and with
  66370. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  66371. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  66372. ** version of sqlite_stat3 and is only available when compiled with
  66373. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  66374. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  66375. ** are both enabled, then STAT4 takes precedence.
  66376. **
  66377. ** For most applications, sqlite_stat1 provides all the statisics required
  66378. ** for the query planner to make good choices.
  66379. **
  66380. ** Format of sqlite_stat1:
  66381. **
  66382. ** There is normally one row per index, with the index identified by the
  66383. ** name in the idx column. The tbl column is the name of the table to
  66384. ** which the index belongs. In each such row, the stat column will be
  66385. ** a string consisting of a list of integers. The first integer in this
  66386. ** list is the number of rows in the index. (This is the same as the
  66387. ** number of rows in the table, except for partial indices.) The second
  66388. ** integer is the average number of rows in the index that have the same
  66389. ** value in the first column of the index. The third integer is the average
  66390. ** number of rows in the index that have the same value for the first two
  66391. ** columns. The N-th integer (for N>1) is the average number of rows in
  66392. ** the index which have the same value for the first N-1 columns. For
  66393. ** a K-column index, there will be K+1 integers in the stat column. If
  66394. ** the index is unique, then the last integer will be 1.
  66395. **
  66396. ** The list of integers in the stat column can optionally be followed
  66397. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  66398. ** must be separated from the last integer by a single space. If the
  66399. ** "unordered" keyword is present, then the query planner assumes that
  66400. ** the index is unordered and will not use the index for a range query.
  66401. **
  66402. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  66403. ** column contains a single integer which is the (estimated) number of
  66404. ** rows in the table identified by sqlite_stat1.tbl.
  66405. **
  66406. ** Format of sqlite_stat2:
  66407. **
  66408. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  66409. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  66410. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  66411. ** about the distribution of keys within an index. The index is identified by
  66412. ** the "idx" column and the "tbl" column is the name of the table to which
  66413. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  66414. ** table for each index.
  66415. **
  66416. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  66417. ** inclusive are samples of the left-most key value in the index taken at
  66418. ** evenly spaced points along the index. Let the number of samples be S
  66419. ** (10 in the standard build) and let C be the number of rows in the index.
  66420. ** Then the sampled rows are given by:
  66421. **
  66422. ** rownumber = (i*C*2 + C)/(S*2)
  66423. **
  66424. ** For i between 0 and S-1. Conceptually, the index space is divided into
  66425. ** S uniform buckets and the samples are the middle row from each bucket.
  66426. **
  66427. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  66428. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  66429. ** writes the sqlite_stat2 table. This version of SQLite only supports
  66430. ** sqlite_stat3.
  66431. **
  66432. ** Format for sqlite_stat3:
  66433. **
  66434. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  66435. ** sqlite_stat4 format will be described first. Further information
  66436. ** about sqlite_stat3 follows the sqlite_stat4 description.
  66437. **
  66438. ** Format for sqlite_stat4:
  66439. **
  66440. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  66441. ** to aid the query planner in choosing good indices based on the values
  66442. ** that indexed columns are compared against in the WHERE clauses of
  66443. ** queries.
  66444. **
  66445. ** The sqlite_stat4 table contains multiple entries for each index.
  66446. ** The idx column names the index and the tbl column is the table of the
  66447. ** index. If the idx and tbl columns are the same, then the sample is
  66448. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  66449. ** binary encoding of a key from the index. The nEq column is a
  66450. ** list of integers. The first integer is the approximate number
  66451. ** of entries in the index whose left-most column exactly matches
  66452. ** the left-most column of the sample. The second integer in nEq
  66453. ** is the approximate number of entries in the index where the
  66454. ** first two columns match the first two columns of the sample.
  66455. ** And so forth. nLt is another list of integers that show the approximate
  66456. ** number of entries that are strictly less than the sample. The first
  66457. ** integer in nLt contains the number of entries in the index where the
  66458. ** left-most column is less than the left-most column of the sample.
  66459. ** The K-th integer in the nLt entry is the number of index entries
  66460. ** where the first K columns are less than the first K columns of the
  66461. ** sample. The nDLt column is like nLt except that it contains the
  66462. ** number of distinct entries in the index that are less than the
  66463. ** sample.
  66464. **
  66465. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  66466. ** The ANALYZE command will typically generate sqlite_stat4 tables
  66467. ** that contain between 10 and 40 samples which are distributed across
  66468. ** the key space, though not uniformly, and which include samples with
  66469. ** large nEq values.
  66470. **
  66471. ** Format for sqlite_stat3 redux:
  66472. **
  66473. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  66474. ** looks at the left-most column of the index. The sqlite_stat3.sample
  66475. ** column contains the actual value of the left-most column instead
  66476. ** of a blob encoding of the complete index key as is found in
  66477. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  66478. ** all contain just a single integer which is the same as the first
  66479. ** integer in the equivalent columns in sqlite_stat4.
  66480. */
  66481. #ifndef SQLITE_OMIT_ANALYZE
  66482. #if defined(SQLITE_ENABLE_STAT4)
  66483. # define IsStat4 1
  66484. # define IsStat3 0
  66485. #elif defined(SQLITE_ENABLE_STAT3)
  66486. # define IsStat4 0
  66487. # define IsStat3 1
  66488. #else
  66489. # define IsStat4 0
  66490. # define IsStat3 0
  66491. # undef SQLITE_STAT4_SAMPLES
  66492. # define SQLITE_STAT4_SAMPLES 1
  66493. #endif
  66494. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  66495. /*
  66496. ** This routine generates code that opens the sqlite_statN tables.
  66497. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  66498. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  66499. ** appropriate compile-time options are provided.
  66500. **
  66501. ** If the sqlite_statN tables do not previously exist, it is created.
  66502. **
  66503. ** Argument zWhere may be a pointer to a buffer containing a table name,
  66504. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  66505. ** the sqlite_statN tables associated with the named table are deleted.
  66506. ** If zWhere==0, then code is generated to delete all stat table entries.
  66507. */
  66508. static void openStatTable(
  66509. Parse *pParse, /* Parsing context */
  66510. int iDb, /* The database we are looking in */
  66511. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  66512. const char *zWhere, /* Delete entries for this table or index */
  66513. const char *zWhereType /* Either "tbl" or "idx" */
  66514. ){
  66515. static const struct {
  66516. const char *zName;
  66517. const char *zCols;
  66518. } aTable[] = {
  66519. { "sqlite_stat1", "tbl,idx,stat" },
  66520. #if defined(SQLITE_ENABLE_STAT4)
  66521. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  66522. { "sqlite_stat3", 0 },
  66523. #elif defined(SQLITE_ENABLE_STAT3)
  66524. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  66525. { "sqlite_stat4", 0 },
  66526. #else
  66527. { "sqlite_stat3", 0 },
  66528. { "sqlite_stat4", 0 },
  66529. #endif
  66530. };
  66531. int i;
  66532. sqlite3 *db = pParse->db;
  66533. Db *pDb;
  66534. Vdbe *v = sqlite3GetVdbe(pParse);
  66535. int aRoot[ArraySize(aTable)];
  66536. u8 aCreateTbl[ArraySize(aTable)];
  66537. if( v==0 ) return;
  66538. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66539. assert( sqlite3VdbeDb(v)==db );
  66540. pDb = &db->aDb[iDb];
  66541. /* Create new statistic tables if they do not exist, or clear them
  66542. ** if they do already exist.
  66543. */
  66544. for(i=0; i<ArraySize(aTable); i++){
  66545. const char *zTab = aTable[i].zName;
  66546. Table *pStat;
  66547. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  66548. if( aTable[i].zCols ){
  66549. /* The sqlite_statN table does not exist. Create it. Note that a
  66550. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  66551. ** of the new table in register pParse->regRoot. This is important
  66552. ** because the OpenWrite opcode below will be needing it. */
  66553. sqlite3NestedParse(pParse,
  66554. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  66555. );
  66556. aRoot[i] = pParse->regRoot;
  66557. aCreateTbl[i] = OPFLAG_P2ISREG;
  66558. }
  66559. }else{
  66560. /* The table already exists. If zWhere is not NULL, delete all entries
  66561. ** associated with the table zWhere. If zWhere is NULL, delete the
  66562. ** entire contents of the table. */
  66563. aRoot[i] = pStat->tnum;
  66564. aCreateTbl[i] = 0;
  66565. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  66566. if( zWhere ){
  66567. sqlite3NestedParse(pParse,
  66568. "DELETE FROM %Q.%s WHERE %s=%Q",
  66569. pDb->zName, zTab, zWhereType, zWhere
  66570. );
  66571. }else{
  66572. /* The sqlite_stat[134] table already exists. Delete all rows. */
  66573. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  66574. }
  66575. }
  66576. }
  66577. /* Open the sqlite_stat[134] tables for writing. */
  66578. for(i=0; aTable[i].zCols; i++){
  66579. assert( i<ArraySize(aTable) );
  66580. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  66581. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  66582. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  66583. }
  66584. }
  66585. /*
  66586. ** Recommended number of samples for sqlite_stat4
  66587. */
  66588. #ifndef SQLITE_STAT4_SAMPLES
  66589. # define SQLITE_STAT4_SAMPLES 24
  66590. #endif
  66591. /*
  66592. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  66593. ** share an instance of the following structure to hold their state
  66594. ** information.
  66595. */
  66596. typedef struct Stat4Accum Stat4Accum;
  66597. typedef struct Stat4Sample Stat4Sample;
  66598. struct Stat4Sample {
  66599. tRowcnt *anEq; /* sqlite_stat4.nEq */
  66600. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  66601. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66602. tRowcnt *anLt; /* sqlite_stat4.nLt */
  66603. i64 iRowid; /* Rowid in main table of the key */
  66604. u8 isPSample; /* True if a periodic sample */
  66605. int iCol; /* If !isPSample, the reason for inclusion */
  66606. u32 iHash; /* Tiebreaker hash */
  66607. #endif
  66608. };
  66609. struct Stat4Accum {
  66610. tRowcnt nRow; /* Number of rows in the entire table */
  66611. tRowcnt nPSample; /* How often to do a periodic sample */
  66612. int nCol; /* Number of columns in index + rowid */
  66613. int mxSample; /* Maximum number of samples to accumulate */
  66614. Stat4Sample current; /* Current row as a Stat4Sample */
  66615. u32 iPrn; /* Pseudo-random number used for sampling */
  66616. Stat4Sample *aBest; /* Array of (nCol-1) best samples */
  66617. int iMin; /* Index in a[] of entry with minimum score */
  66618. int nSample; /* Current number of samples */
  66619. int iGet; /* Index of current sample accessed by stat_get() */
  66620. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  66621. };
  66622. /*
  66623. ** Implementation of the stat_init(N,C) SQL function. The two parameters
  66624. ** are the number of rows in the table or index (C) and the number of columns
  66625. ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
  66626. **
  66627. ** This routine allocates the Stat4Accum object in heap memory. The return
  66628. ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
  66629. ** the size of the blob is sizeof(void*) bytes).
  66630. */
  66631. static void statInit(
  66632. sqlite3_context *context,
  66633. int argc,
  66634. sqlite3_value **argv
  66635. ){
  66636. Stat4Accum *p;
  66637. int nCol; /* Number of columns in index being sampled */
  66638. int nColUp; /* nCol rounded up for alignment */
  66639. int n; /* Bytes of space to allocate */
  66640. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66641. int mxSample = SQLITE_STAT4_SAMPLES;
  66642. #endif
  66643. /* Decode the three function arguments */
  66644. UNUSED_PARAMETER(argc);
  66645. nCol = sqlite3_value_int(argv[0]);
  66646. assert( nCol>1 ); /* >1 because it includes the rowid column */
  66647. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  66648. /* Allocate the space required for the Stat4Accum object */
  66649. n = sizeof(*p)
  66650. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  66651. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  66652. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66653. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  66654. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  66655. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  66656. #endif
  66657. ;
  66658. p = sqlite3MallocZero(n);
  66659. if( p==0 ){
  66660. sqlite3_result_error_nomem(context);
  66661. return;
  66662. }
  66663. p->nRow = 0;
  66664. p->nCol = nCol;
  66665. p->current.anDLt = (tRowcnt*)&p[1];
  66666. p->current.anEq = &p->current.anDLt[nColUp];
  66667. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66668. {
  66669. u8 *pSpace; /* Allocated space not yet assigned */
  66670. int i; /* Used to iterate through p->aSample[] */
  66671. p->iGet = -1;
  66672. p->mxSample = mxSample;
  66673. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
  66674. p->current.anLt = &p->current.anEq[nColUp];
  66675. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
  66676. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  66677. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  66678. p->aBest = &p->a[mxSample];
  66679. pSpace = (u8*)(&p->a[mxSample+nCol]);
  66680. for(i=0; i<(mxSample+nCol); i++){
  66681. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66682. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66683. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66684. }
  66685. assert( (pSpace - (u8*)p)==n );
  66686. for(i=0; i<nCol; i++){
  66687. p->aBest[i].iCol = i;
  66688. }
  66689. }
  66690. #endif
  66691. /* Return a pointer to the allocated object to the caller */
  66692. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  66693. }
  66694. static const FuncDef statInitFuncdef = {
  66695. 1+IsStat34, /* nArg */
  66696. SQLITE_UTF8, /* funcFlags */
  66697. 0, /* pUserData */
  66698. 0, /* pNext */
  66699. statInit, /* xFunc */
  66700. 0, /* xStep */
  66701. 0, /* xFinalize */
  66702. "stat_init", /* zName */
  66703. 0, /* pHash */
  66704. 0 /* pDestructor */
  66705. };
  66706. #ifdef SQLITE_ENABLE_STAT4
  66707. /*
  66708. ** pNew and pOld are both candidate non-periodic samples selected for
  66709. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  66710. ** considering only any trailing columns and the sample hash value, this
  66711. ** function returns true if sample pNew is to be preferred over pOld.
  66712. ** In other words, if we assume that the cardinalities of the selected
  66713. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  66714. **
  66715. ** This function assumes that for each argument sample, the contents of
  66716. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  66717. */
  66718. static int sampleIsBetterPost(
  66719. Stat4Accum *pAccum,
  66720. Stat4Sample *pNew,
  66721. Stat4Sample *pOld
  66722. ){
  66723. int nCol = pAccum->nCol;
  66724. int i;
  66725. assert( pNew->iCol==pOld->iCol );
  66726. for(i=pNew->iCol+1; i<nCol; i++){
  66727. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  66728. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  66729. }
  66730. if( pNew->iHash>pOld->iHash ) return 1;
  66731. return 0;
  66732. }
  66733. #endif
  66734. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66735. /*
  66736. ** Return true if pNew is to be preferred over pOld.
  66737. **
  66738. ** This function assumes that for each argument sample, the contents of
  66739. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  66740. */
  66741. static int sampleIsBetter(
  66742. Stat4Accum *pAccum,
  66743. Stat4Sample *pNew,
  66744. Stat4Sample *pOld
  66745. ){
  66746. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  66747. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  66748. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  66749. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  66750. if( (nEqNew>nEqOld) ) return 1;
  66751. #ifdef SQLITE_ENABLE_STAT4
  66752. if( nEqNew==nEqOld ){
  66753. if( pNew->iCol<pOld->iCol ) return 1;
  66754. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  66755. }
  66756. return 0;
  66757. #else
  66758. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  66759. #endif
  66760. }
  66761. /*
  66762. ** Copy the contents of object (*pFrom) into (*pTo).
  66763. */
  66764. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  66765. pTo->iRowid = pFrom->iRowid;
  66766. pTo->isPSample = pFrom->isPSample;
  66767. pTo->iCol = pFrom->iCol;
  66768. pTo->iHash = pFrom->iHash;
  66769. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  66770. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  66771. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  66772. }
  66773. /*
  66774. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  66775. ** remove the least desirable sample from p->a[] to make room.
  66776. */
  66777. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  66778. Stat4Sample *pSample;
  66779. int i;
  66780. assert( IsStat4 || nEqZero==0 );
  66781. #ifdef SQLITE_ENABLE_STAT4
  66782. if( pNew->isPSample==0 ){
  66783. Stat4Sample *pUpgrade = 0;
  66784. assert( pNew->anEq[pNew->iCol]>0 );
  66785. /* This sample is being added because the prefix that ends in column
  66786. ** iCol occurs many times in the table. However, if we have already
  66787. ** added a sample that shares this prefix, there is no need to add
  66788. ** this one. Instead, upgrade the priority of the highest priority
  66789. ** existing sample that shares this prefix. */
  66790. for(i=p->nSample-1; i>=0; i--){
  66791. Stat4Sample *pOld = &p->a[i];
  66792. if( pOld->anEq[pNew->iCol]==0 ){
  66793. if( pOld->isPSample ) return;
  66794. assert( pOld->iCol>pNew->iCol );
  66795. assert( sampleIsBetter(p, pNew, pOld) );
  66796. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  66797. pUpgrade = pOld;
  66798. }
  66799. }
  66800. }
  66801. if( pUpgrade ){
  66802. pUpgrade->iCol = pNew->iCol;
  66803. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  66804. goto find_new_min;
  66805. }
  66806. }
  66807. #endif
  66808. /* If necessary, remove sample iMin to make room for the new sample. */
  66809. if( p->nSample>=p->mxSample ){
  66810. Stat4Sample *pMin = &p->a[p->iMin];
  66811. tRowcnt *anEq = pMin->anEq;
  66812. tRowcnt *anLt = pMin->anLt;
  66813. tRowcnt *anDLt = pMin->anDLt;
  66814. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  66815. pSample = &p->a[p->nSample-1];
  66816. pSample->anEq = anEq;
  66817. pSample->anDLt = anDLt;
  66818. pSample->anLt = anLt;
  66819. p->nSample = p->mxSample-1;
  66820. }
  66821. /* The "rows less-than" for the rowid column must be greater than that
  66822. ** for the last sample in the p->a[] array. Otherwise, the samples would
  66823. ** be out of order. */
  66824. #ifdef SQLITE_ENABLE_STAT4
  66825. assert( p->nSample==0
  66826. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  66827. #endif
  66828. /* Insert the new sample */
  66829. pSample = &p->a[p->nSample];
  66830. sampleCopy(p, pSample, pNew);
  66831. p->nSample++;
  66832. /* Zero the first nEqZero entries in the anEq[] array. */
  66833. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  66834. #ifdef SQLITE_ENABLE_STAT4
  66835. find_new_min:
  66836. #endif
  66837. if( p->nSample>=p->mxSample ){
  66838. int iMin = -1;
  66839. for(i=0; i<p->mxSample; i++){
  66840. if( p->a[i].isPSample ) continue;
  66841. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  66842. iMin = i;
  66843. }
  66844. }
  66845. assert( iMin>=0 );
  66846. p->iMin = iMin;
  66847. }
  66848. }
  66849. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  66850. /*
  66851. ** Field iChng of the index being scanned has changed. So at this point
  66852. ** p->current contains a sample that reflects the previous row of the
  66853. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  66854. ** correct at this point.
  66855. */
  66856. static void samplePushPrevious(Stat4Accum *p, int iChng){
  66857. #ifdef SQLITE_ENABLE_STAT4
  66858. int i;
  66859. /* Check if any samples from the aBest[] array should be pushed
  66860. ** into IndexSample.a[] at this point. */
  66861. for(i=(p->nCol-2); i>=iChng; i--){
  66862. Stat4Sample *pBest = &p->aBest[i];
  66863. pBest->anEq[i] = p->current.anEq[i];
  66864. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  66865. sampleInsert(p, pBest, i);
  66866. }
  66867. }
  66868. /* Update the anEq[] fields of any samples already collected. */
  66869. for(i=p->nSample-1; i>=0; i--){
  66870. int j;
  66871. for(j=iChng; j<p->nCol; j++){
  66872. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  66873. }
  66874. }
  66875. #endif
  66876. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  66877. if( iChng==0 ){
  66878. tRowcnt nLt = p->current.anLt[0];
  66879. tRowcnt nEq = p->current.anEq[0];
  66880. /* Check if this is to be a periodic sample. If so, add it. */
  66881. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  66882. p->current.isPSample = 1;
  66883. sampleInsert(p, &p->current, 0);
  66884. p->current.isPSample = 0;
  66885. }else
  66886. /* Or if it is a non-periodic sample. Add it in this case too. */
  66887. if( p->nSample<p->mxSample
  66888. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  66889. ){
  66890. sampleInsert(p, &p->current, 0);
  66891. }
  66892. }
  66893. #endif
  66894. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  66895. UNUSED_PARAMETER( p );
  66896. UNUSED_PARAMETER( iChng );
  66897. #endif
  66898. }
  66899. /*
  66900. ** Implementation of the stat_push SQL function: stat_push(P,R,C)
  66901. ** Arguments:
  66902. **
  66903. ** P Pointer to the Stat4Accum object created by stat_init()
  66904. ** C Index of left-most column to differ from previous row
  66905. ** R Rowid for the current row
  66906. **
  66907. ** The SQL function always returns NULL.
  66908. **
  66909. ** The R parameter is only used for STAT3 and STAT4.
  66910. */
  66911. static void statPush(
  66912. sqlite3_context *context,
  66913. int argc,
  66914. sqlite3_value **argv
  66915. ){
  66916. int i;
  66917. /* The three function arguments */
  66918. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  66919. int iChng = sqlite3_value_int(argv[1]);
  66920. UNUSED_PARAMETER( argc );
  66921. UNUSED_PARAMETER( context );
  66922. assert( p->nCol>1 ); /* Includes rowid field */
  66923. assert( iChng<p->nCol );
  66924. if( p->nRow==0 ){
  66925. /* This is the first call to this function. Do initialization. */
  66926. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  66927. }else{
  66928. /* Second and subsequent calls get processed here */
  66929. samplePushPrevious(p, iChng);
  66930. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  66931. ** to the current row of the index. */
  66932. for(i=0; i<iChng; i++){
  66933. p->current.anEq[i]++;
  66934. }
  66935. for(i=iChng; i<p->nCol; i++){
  66936. p->current.anDLt[i]++;
  66937. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66938. p->current.anLt[i] += p->current.anEq[i];
  66939. #endif
  66940. p->current.anEq[i] = 1;
  66941. }
  66942. }
  66943. p->nRow++;
  66944. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66945. p->current.iRowid = sqlite3_value_int64(argv[2]);
  66946. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  66947. #endif
  66948. #ifdef SQLITE_ENABLE_STAT4
  66949. {
  66950. tRowcnt nLt = p->current.anLt[p->nCol-1];
  66951. /* Check if this is to be a periodic sample. If so, add it. */
  66952. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  66953. p->current.isPSample = 1;
  66954. p->current.iCol = 0;
  66955. sampleInsert(p, &p->current, p->nCol-1);
  66956. p->current.isPSample = 0;
  66957. }
  66958. /* Update the aBest[] array. */
  66959. for(i=0; i<(p->nCol-1); i++){
  66960. p->current.iCol = i;
  66961. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  66962. sampleCopy(p, &p->aBest[i], &p->current);
  66963. }
  66964. }
  66965. }
  66966. #endif
  66967. }
  66968. static const FuncDef statPushFuncdef = {
  66969. 2+IsStat34, /* nArg */
  66970. SQLITE_UTF8, /* funcFlags */
  66971. 0, /* pUserData */
  66972. 0, /* pNext */
  66973. statPush, /* xFunc */
  66974. 0, /* xStep */
  66975. 0, /* xFinalize */
  66976. "stat_push", /* zName */
  66977. 0, /* pHash */
  66978. 0 /* pDestructor */
  66979. };
  66980. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  66981. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  66982. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  66983. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  66984. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  66985. /*
  66986. ** Implementation of the stat_get(P,J) SQL function. This routine is
  66987. ** used to query the results. Content is returned for parameter J
  66988. ** which is one of the STAT_GET_xxxx values defined above.
  66989. **
  66990. ** If neither STAT3 nor STAT4 are enabled, then J is always
  66991. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  66992. ** a one-parameter function, stat_get(P), that always returns the
  66993. ** stat1 table entry information.
  66994. */
  66995. static void statGet(
  66996. sqlite3_context *context,
  66997. int argc,
  66998. sqlite3_value **argv
  66999. ){
  67000. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  67001. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67002. /* STAT3 and STAT4 have a parameter on this routine. */
  67003. int eCall = sqlite3_value_int(argv[1]);
  67004. assert( argc==2 );
  67005. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  67006. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  67007. || eCall==STAT_GET_NDLT
  67008. );
  67009. if( eCall==STAT_GET_STAT1 )
  67010. #else
  67011. assert( argc==1 );
  67012. #endif
  67013. {
  67014. /* Return the value to store in the "stat" column of the sqlite_stat1
  67015. ** table for this index.
  67016. **
  67017. ** The value is a string composed of a list of integers describing
  67018. ** the index. The first integer in the list is the total number of
  67019. ** entries in the index. There is one additional integer in the list
  67020. ** for each indexed column. This additional integer is an estimate of
  67021. ** the number of rows matched by a stabbing query on the index using
  67022. ** a key with the corresponding number of fields. In other words,
  67023. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  67024. ** "100 10 2", then SQLite estimates that:
  67025. **
  67026. ** * the index contains 100 rows,
  67027. ** * "WHERE a=?" matches 10 rows, and
  67028. ** * "WHERE a=? AND b=?" matches 2 rows.
  67029. **
  67030. ** If D is the count of distinct values and K is the total number of
  67031. ** rows, then each estimate is computed as:
  67032. **
  67033. ** I = (K+D-1)/D
  67034. */
  67035. char *z;
  67036. int i;
  67037. char *zRet = sqlite3MallocZero(p->nCol * 25);
  67038. if( zRet==0 ){
  67039. sqlite3_result_error_nomem(context);
  67040. return;
  67041. }
  67042. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  67043. z = zRet + sqlite3Strlen30(zRet);
  67044. for(i=0; i<(p->nCol-1); i++){
  67045. u64 nDistinct = p->current.anDLt[i] + 1;
  67046. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  67047. sqlite3_snprintf(24, z, " %llu", iVal);
  67048. z += sqlite3Strlen30(z);
  67049. assert( p->current.anEq[i] );
  67050. }
  67051. assert( z[0]=='\0' && z>zRet );
  67052. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  67053. }
  67054. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67055. else if( eCall==STAT_GET_ROWID ){
  67056. if( p->iGet<0 ){
  67057. samplePushPrevious(p, 0);
  67058. p->iGet = 0;
  67059. }
  67060. if( p->iGet<p->nSample ){
  67061. sqlite3_result_int64(context, p->a[p->iGet].iRowid);
  67062. }
  67063. }else{
  67064. tRowcnt *aCnt = 0;
  67065. assert( p->iGet<p->nSample );
  67066. switch( eCall ){
  67067. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  67068. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  67069. default: {
  67070. aCnt = p->a[p->iGet].anDLt;
  67071. p->iGet++;
  67072. break;
  67073. }
  67074. }
  67075. if( IsStat3 ){
  67076. sqlite3_result_int64(context, (i64)aCnt[0]);
  67077. }else{
  67078. char *zRet = sqlite3MallocZero(p->nCol * 25);
  67079. if( zRet==0 ){
  67080. sqlite3_result_error_nomem(context);
  67081. }else{
  67082. int i;
  67083. char *z = zRet;
  67084. for(i=0; i<p->nCol; i++){
  67085. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  67086. z += sqlite3Strlen30(z);
  67087. }
  67088. assert( z[0]=='\0' && z>zRet );
  67089. z[-1] = '\0';
  67090. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  67091. }
  67092. }
  67093. }
  67094. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67095. #ifndef SQLITE_DEBUG
  67096. UNUSED_PARAMETER( argc );
  67097. #endif
  67098. }
  67099. static const FuncDef statGetFuncdef = {
  67100. 1+IsStat34, /* nArg */
  67101. SQLITE_UTF8, /* funcFlags */
  67102. 0, /* pUserData */
  67103. 0, /* pNext */
  67104. statGet, /* xFunc */
  67105. 0, /* xStep */
  67106. 0, /* xFinalize */
  67107. "stat_get", /* zName */
  67108. 0, /* pHash */
  67109. 0 /* pDestructor */
  67110. };
  67111. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  67112. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  67113. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67114. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  67115. #elif SQLITE_DEBUG
  67116. assert( iParam==STAT_GET_STAT1 );
  67117. #else
  67118. UNUSED_PARAMETER( iParam );
  67119. #endif
  67120. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  67121. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  67122. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  67123. }
  67124. /*
  67125. ** Generate code to do an analysis of all indices associated with
  67126. ** a single table.
  67127. */
  67128. static void analyzeOneTable(
  67129. Parse *pParse, /* Parser context */
  67130. Table *pTab, /* Table whose indices are to be analyzed */
  67131. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  67132. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  67133. int iMem, /* Available memory locations begin here */
  67134. int iTab /* Next available cursor */
  67135. ){
  67136. sqlite3 *db = pParse->db; /* Database handle */
  67137. Index *pIdx; /* An index to being analyzed */
  67138. int iIdxCur; /* Cursor open on index being analyzed */
  67139. int iTabCur; /* Table cursor */
  67140. Vdbe *v; /* The virtual machine being built up */
  67141. int i; /* Loop counter */
  67142. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  67143. int iDb; /* Index of database containing pTab */
  67144. u8 needTableCnt = 1; /* True to count the table */
  67145. int regNewRowid = iMem++; /* Rowid for the inserted record */
  67146. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  67147. int regChng = iMem++; /* Index of changed index field */
  67148. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67149. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  67150. #endif
  67151. int regTemp = iMem++; /* Temporary use register */
  67152. int regTabname = iMem++; /* Register containing table name */
  67153. int regIdxname = iMem++; /* Register containing index name */
  67154. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  67155. int regPrev = iMem; /* MUST BE LAST (see below) */
  67156. pParse->nMem = MAX(pParse->nMem, iMem);
  67157. v = sqlite3GetVdbe(pParse);
  67158. if( v==0 || NEVER(pTab==0) ){
  67159. return;
  67160. }
  67161. if( pTab->tnum==0 ){
  67162. /* Do not gather statistics on views or virtual tables */
  67163. return;
  67164. }
  67165. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  67166. /* Do not gather statistics on system tables */
  67167. return;
  67168. }
  67169. assert( sqlite3BtreeHoldsAllMutexes(db) );
  67170. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67171. assert( iDb>=0 );
  67172. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67173. #ifndef SQLITE_OMIT_AUTHORIZATION
  67174. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  67175. db->aDb[iDb].zName ) ){
  67176. return;
  67177. }
  67178. #endif
  67179. /* Establish a read-lock on the table at the shared-cache level.
  67180. ** Open a read-only cursor on the table. Also allocate a cursor number
  67181. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  67182. ** this time though. */
  67183. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  67184. iTabCur = iTab++;
  67185. iIdxCur = iTab++;
  67186. pParse->nTab = MAX(pParse->nTab, iTab);
  67187. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  67188. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  67189. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  67190. int nCol; /* Number of columns indexed by pIdx */
  67191. KeyInfo *pKey; /* KeyInfo structure for pIdx */
  67192. int *aGotoChng; /* Array of jump instruction addresses */
  67193. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  67194. int addrGotoChng0; /* Address of "Goto addr_chng_0" */
  67195. int addrNextRow; /* Address of "next_row:" */
  67196. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  67197. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  67198. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  67199. nCol = pIdx->nColumn;
  67200. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
  67201. if( aGotoChng==0 ) continue;
  67202. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  67203. /* Populate the register containing the index name. */
  67204. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  67205. /*
  67206. ** Pseudo-code for loop that calls stat_push():
  67207. **
  67208. ** Rewind csr
  67209. ** if eof(csr) goto end_of_scan;
  67210. ** regChng = 0
  67211. ** goto chng_addr_0;
  67212. **
  67213. ** next_row:
  67214. ** regChng = 0
  67215. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  67216. ** regChng = 1
  67217. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  67218. ** ...
  67219. ** regChng = N
  67220. ** goto chng_addr_N
  67221. **
  67222. ** chng_addr_0:
  67223. ** regPrev(0) = idx(0)
  67224. ** chng_addr_1:
  67225. ** regPrev(1) = idx(1)
  67226. ** ...
  67227. **
  67228. ** chng_addr_N:
  67229. ** regRowid = idx(rowid)
  67230. ** stat_push(P, regChng, regRowid)
  67231. ** Next csr
  67232. ** if !eof(csr) goto next_row;
  67233. **
  67234. ** end_of_scan:
  67235. */
  67236. /* Make sure there are enough memory cells allocated to accommodate
  67237. ** the regPrev array and a trailing rowid (the rowid slot is required
  67238. ** when building a record to insert into the sample column of
  67239. ** the sqlite_stat4 table. */
  67240. pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
  67241. /* Open a read-only cursor on the index being analyzed. */
  67242. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  67243. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  67244. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  67245. VdbeComment((v, "%s", pIdx->zName));
  67246. /* Invoke the stat_init() function. The arguments are:
  67247. **
  67248. ** (1) the number of columns in the index including the rowid,
  67249. ** (2) the number of rows in the index,
  67250. **
  67251. ** The second argument is only used for STAT3 and STAT4
  67252. */
  67253. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67254. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
  67255. #endif
  67256. sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
  67257. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  67258. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  67259. sqlite3VdbeChangeP5(v, 1+IsStat34);
  67260. /* Implementation of the following:
  67261. **
  67262. ** Rewind csr
  67263. ** if eof(csr) goto end_of_scan;
  67264. ** regChng = 0
  67265. ** goto next_push_0;
  67266. **
  67267. */
  67268. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  67269. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  67270. addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  67271. /*
  67272. ** next_row:
  67273. ** regChng = 0
  67274. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  67275. ** regChng = 1
  67276. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  67277. ** ...
  67278. ** regChng = N
  67279. ** goto chng_addr_N
  67280. */
  67281. addrNextRow = sqlite3VdbeCurrentAddr(v);
  67282. for(i=0; i<nCol; i++){
  67283. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  67284. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  67285. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  67286. aGotoChng[i] =
  67287. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  67288. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  67289. }
  67290. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  67291. aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  67292. /*
  67293. ** chng_addr_0:
  67294. ** regPrev(0) = idx(0)
  67295. ** chng_addr_1:
  67296. ** regPrev(1) = idx(1)
  67297. ** ...
  67298. */
  67299. sqlite3VdbeJumpHere(v, addrGotoChng0);
  67300. for(i=0; i<nCol; i++){
  67301. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  67302. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  67303. }
  67304. /*
  67305. ** chng_addr_N:
  67306. ** regRowid = idx(rowid) // STAT34 only
  67307. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  67308. ** Next csr
  67309. ** if !eof(csr) goto next_row;
  67310. */
  67311. sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
  67312. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67313. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  67314. assert( regRowid==(regStat4+2) );
  67315. #endif
  67316. assert( regChng==(regStat4+1) );
  67317. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  67318. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  67319. sqlite3VdbeChangeP5(v, 2+IsStat34);
  67320. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
  67321. /* Add the entry to the stat1 table. */
  67322. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  67323. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  67324. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  67325. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  67326. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  67327. /* Add the entries to the stat3 or stat4 table. */
  67328. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67329. {
  67330. int regEq = regStat1;
  67331. int regLt = regStat1+1;
  67332. int regDLt = regStat1+2;
  67333. int regSample = regStat1+3;
  67334. int regCol = regStat1+4;
  67335. int regSampleRowid = regCol + nCol;
  67336. int addrNext;
  67337. int addrIsNull;
  67338. pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  67339. addrNext = sqlite3VdbeCurrentAddr(v);
  67340. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  67341. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  67342. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  67343. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  67344. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  67345. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
  67346. #ifdef SQLITE_ENABLE_STAT3
  67347. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  67348. pIdx->aiColumn[0], regSample);
  67349. #else
  67350. for(i=0; i<nCol; i++){
  67351. int iCol = pIdx->aiColumn[i];
  67352. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  67353. }
  67354. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  67355. #endif
  67356. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
  67357. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  67358. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  67359. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  67360. sqlite3VdbeJumpHere(v, addrIsNull);
  67361. }
  67362. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67363. /* End of analysis */
  67364. sqlite3VdbeJumpHere(v, addrRewind);
  67365. sqlite3DbFree(db, aGotoChng);
  67366. }
  67367. /* Create a single sqlite_stat1 entry containing NULL as the index
  67368. ** name and the row count as the content.
  67369. */
  67370. if( pOnlyIdx==0 && needTableCnt ){
  67371. VdbeComment((v, "%s", pTab->zName));
  67372. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  67373. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  67374. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  67375. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  67376. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  67377. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  67378. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  67379. sqlite3VdbeJumpHere(v, jZeroRows);
  67380. }
  67381. }
  67382. /*
  67383. ** Generate code that will cause the most recent index analysis to
  67384. ** be loaded into internal hash tables where is can be used.
  67385. */
  67386. static void loadAnalysis(Parse *pParse, int iDb){
  67387. Vdbe *v = sqlite3GetVdbe(pParse);
  67388. if( v ){
  67389. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  67390. }
  67391. }
  67392. /*
  67393. ** Generate code that will do an analysis of an entire database
  67394. */
  67395. static void analyzeDatabase(Parse *pParse, int iDb){
  67396. sqlite3 *db = pParse->db;
  67397. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  67398. HashElem *k;
  67399. int iStatCur;
  67400. int iMem;
  67401. int iTab;
  67402. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67403. iStatCur = pParse->nTab;
  67404. pParse->nTab += 3;
  67405. openStatTable(pParse, iDb, iStatCur, 0, 0);
  67406. iMem = pParse->nMem+1;
  67407. iTab = pParse->nTab;
  67408. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67409. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  67410. Table *pTab = (Table*)sqliteHashData(k);
  67411. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  67412. }
  67413. loadAnalysis(pParse, iDb);
  67414. }
  67415. /*
  67416. ** Generate code that will do an analysis of a single table in
  67417. ** a database. If pOnlyIdx is not NULL then it is a single index
  67418. ** in pTab that should be analyzed.
  67419. */
  67420. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  67421. int iDb;
  67422. int iStatCur;
  67423. assert( pTab!=0 );
  67424. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  67425. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  67426. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67427. iStatCur = pParse->nTab;
  67428. pParse->nTab += 3;
  67429. if( pOnlyIdx ){
  67430. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  67431. }else{
  67432. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  67433. }
  67434. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  67435. loadAnalysis(pParse, iDb);
  67436. }
  67437. /*
  67438. ** Generate code for the ANALYZE command. The parser calls this routine
  67439. ** when it recognizes an ANALYZE command.
  67440. **
  67441. ** ANALYZE -- 1
  67442. ** ANALYZE <database> -- 2
  67443. ** ANALYZE ?<database>.?<tablename> -- 3
  67444. **
  67445. ** Form 1 causes all indices in all attached databases to be analyzed.
  67446. ** Form 2 analyzes all indices the single database named.
  67447. ** Form 3 analyzes all indices associated with the named table.
  67448. */
  67449. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  67450. sqlite3 *db = pParse->db;
  67451. int iDb;
  67452. int i;
  67453. char *z, *zDb;
  67454. Table *pTab;
  67455. Index *pIdx;
  67456. Token *pTableName;
  67457. /* Read the database schema. If an error occurs, leave an error message
  67458. ** and code in pParse and return NULL. */
  67459. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  67460. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  67461. return;
  67462. }
  67463. assert( pName2!=0 || pName1==0 );
  67464. if( pName1==0 ){
  67465. /* Form 1: Analyze everything */
  67466. for(i=0; i<db->nDb; i++){
  67467. if( i==1 ) continue; /* Do not analyze the TEMP database */
  67468. analyzeDatabase(pParse, i);
  67469. }
  67470. }else if( pName2->n==0 ){
  67471. /* Form 2: Analyze the database or table named */
  67472. iDb = sqlite3FindDb(db, pName1);
  67473. if( iDb>=0 ){
  67474. analyzeDatabase(pParse, iDb);
  67475. }else{
  67476. z = sqlite3NameFromToken(db, pName1);
  67477. if( z ){
  67478. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  67479. analyzeTable(pParse, pIdx->pTable, pIdx);
  67480. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  67481. analyzeTable(pParse, pTab, 0);
  67482. }
  67483. sqlite3DbFree(db, z);
  67484. }
  67485. }
  67486. }else{
  67487. /* Form 3: Analyze the fully qualified table name */
  67488. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  67489. if( iDb>=0 ){
  67490. zDb = db->aDb[iDb].zName;
  67491. z = sqlite3NameFromToken(db, pTableName);
  67492. if( z ){
  67493. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  67494. analyzeTable(pParse, pIdx->pTable, pIdx);
  67495. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  67496. analyzeTable(pParse, pTab, 0);
  67497. }
  67498. sqlite3DbFree(db, z);
  67499. }
  67500. }
  67501. }
  67502. }
  67503. /*
  67504. ** Used to pass information from the analyzer reader through to the
  67505. ** callback routine.
  67506. */
  67507. typedef struct analysisInfo analysisInfo;
  67508. struct analysisInfo {
  67509. sqlite3 *db;
  67510. const char *zDatabase;
  67511. };
  67512. /*
  67513. ** The first argument points to a nul-terminated string containing a
  67514. ** list of space separated integers. Read the first nOut of these into
  67515. ** the array aOut[].
  67516. */
  67517. static void decodeIntArray(
  67518. char *zIntArray, /* String containing int array to decode */
  67519. int nOut, /* Number of slots in aOut[] */
  67520. tRowcnt *aOut, /* Store integers here */
  67521. Index *pIndex /* Handle extra flags for this index, if not NULL */
  67522. ){
  67523. char *z = zIntArray;
  67524. int c;
  67525. int i;
  67526. tRowcnt v;
  67527. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67528. if( z==0 ) z = "";
  67529. #else
  67530. if( NEVER(z==0) ) z = "";
  67531. #endif
  67532. for(i=0; *z && i<nOut; i++){
  67533. v = 0;
  67534. while( (c=z[0])>='0' && c<='9' ){
  67535. v = v*10 + c - '0';
  67536. z++;
  67537. }
  67538. aOut[i] = v;
  67539. if( *z==' ' ) z++;
  67540. }
  67541. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  67542. assert( pIndex!=0 );
  67543. #else
  67544. if( pIndex )
  67545. #endif
  67546. {
  67547. if( strcmp(z, "unordered")==0 ){
  67548. pIndex->bUnordered = 1;
  67549. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  67550. int v32 = 0;
  67551. sqlite3GetInt32(z+3, &v32);
  67552. pIndex->szIdxRow = sqlite3LogEst(v32);
  67553. }
  67554. }
  67555. }
  67556. /*
  67557. ** This callback is invoked once for each index when reading the
  67558. ** sqlite_stat1 table.
  67559. **
  67560. ** argv[0] = name of the table
  67561. ** argv[1] = name of the index (might be NULL)
  67562. ** argv[2] = results of analysis - on integer for each column
  67563. **
  67564. ** Entries for which argv[1]==NULL simply record the number of rows in
  67565. ** the table.
  67566. */
  67567. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  67568. analysisInfo *pInfo = (analysisInfo*)pData;
  67569. Index *pIndex;
  67570. Table *pTable;
  67571. const char *z;
  67572. assert( argc==3 );
  67573. UNUSED_PARAMETER2(NotUsed, argc);
  67574. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  67575. return 0;
  67576. }
  67577. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  67578. if( pTable==0 ){
  67579. return 0;
  67580. }
  67581. if( argv[1] ){
  67582. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  67583. }else{
  67584. pIndex = 0;
  67585. }
  67586. z = argv[2];
  67587. if( pIndex ){
  67588. decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
  67589. if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
  67590. }else{
  67591. Index fakeIdx;
  67592. fakeIdx.szIdxRow = pTable->szTabRow;
  67593. decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
  67594. pTable->szTabRow = fakeIdx.szIdxRow;
  67595. }
  67596. return 0;
  67597. }
  67598. /*
  67599. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  67600. ** and its contents.
  67601. */
  67602. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  67603. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67604. if( pIdx->aSample ){
  67605. int j;
  67606. for(j=0; j<pIdx->nSample; j++){
  67607. IndexSample *p = &pIdx->aSample[j];
  67608. sqlite3DbFree(db, p->p);
  67609. }
  67610. sqlite3DbFree(db, pIdx->aSample);
  67611. }
  67612. if( db && db->pnBytesFreed==0 ){
  67613. pIdx->nSample = 0;
  67614. pIdx->aSample = 0;
  67615. }
  67616. #else
  67617. UNUSED_PARAMETER(db);
  67618. UNUSED_PARAMETER(pIdx);
  67619. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67620. }
  67621. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67622. /*
  67623. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  67624. ** stored in pIdx->aSample[].
  67625. */
  67626. static void initAvgEq(Index *pIdx){
  67627. if( pIdx ){
  67628. IndexSample *aSample = pIdx->aSample;
  67629. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  67630. int iCol;
  67631. for(iCol=0; iCol<pIdx->nColumn; iCol++){
  67632. int i; /* Used to iterate through samples */
  67633. tRowcnt sumEq = 0; /* Sum of the nEq values */
  67634. tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
  67635. tRowcnt avgEq = 0;
  67636. tRowcnt nDLt = pFinal->anDLt[iCol];
  67637. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  67638. ** occur in the stat4 table for this index before pFinal. Set
  67639. ** sumEq to the sum of the nEq values for column iCol for the same
  67640. ** set (adding the value only once where there exist dupicate
  67641. ** prefixes). */
  67642. for(i=0; i<(pIdx->nSample-1); i++){
  67643. if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
  67644. sumEq += aSample[i].anEq[iCol];
  67645. nSum++;
  67646. }
  67647. }
  67648. if( nDLt>nSum ){
  67649. avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
  67650. }
  67651. if( avgEq==0 ) avgEq = 1;
  67652. pIdx->aAvgEq[iCol] = avgEq;
  67653. if( pIdx->nSampleCol==1 ) break;
  67654. }
  67655. }
  67656. }
  67657. /*
  67658. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  67659. ** into the relevant Index.aSample[] arrays.
  67660. **
  67661. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  67662. ** data equivalent to the following (statements are different for stat3,
  67663. ** see the caller of this function for details):
  67664. **
  67665. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  67666. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  67667. **
  67668. ** where %Q is replaced with the database name before the SQL is executed.
  67669. */
  67670. static int loadStatTbl(
  67671. sqlite3 *db, /* Database handle */
  67672. int bStat3, /* Assume single column records only */
  67673. const char *zSql1, /* SQL statement 1 (see above) */
  67674. const char *zSql2, /* SQL statement 2 (see above) */
  67675. const char *zDb /* Database name (e.g. "main") */
  67676. ){
  67677. int rc; /* Result codes from subroutines */
  67678. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  67679. char *zSql; /* Text of the SQL statement */
  67680. Index *pPrevIdx = 0; /* Previous index in the loop */
  67681. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  67682. assert( db->lookaside.bEnabled==0 );
  67683. zSql = sqlite3MPrintf(db, zSql1, zDb);
  67684. if( !zSql ){
  67685. return SQLITE_NOMEM;
  67686. }
  67687. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  67688. sqlite3DbFree(db, zSql);
  67689. if( rc ) return rc;
  67690. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  67691. int nIdxCol = 1; /* Number of columns in stat4 records */
  67692. int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
  67693. char *zIndex; /* Index name */
  67694. Index *pIdx; /* Pointer to the index object */
  67695. int nSample; /* Number of samples */
  67696. int nByte; /* Bytes of space required */
  67697. int i; /* Bytes of space required */
  67698. tRowcnt *pSpace;
  67699. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  67700. if( zIndex==0 ) continue;
  67701. nSample = sqlite3_column_int(pStmt, 1);
  67702. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  67703. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  67704. /* Index.nSample is non-zero at this point if data has already been
  67705. ** loaded from the stat4 table. In this case ignore stat3 data. */
  67706. if( pIdx==0 || pIdx->nSample ) continue;
  67707. if( bStat3==0 ){
  67708. nIdxCol = pIdx->nColumn+1;
  67709. nAvgCol = pIdx->nColumn;
  67710. }
  67711. pIdx->nSampleCol = nIdxCol;
  67712. nByte = sizeof(IndexSample) * nSample;
  67713. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  67714. nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  67715. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  67716. if( pIdx->aSample==0 ){
  67717. sqlite3_finalize(pStmt);
  67718. return SQLITE_NOMEM;
  67719. }
  67720. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  67721. pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
  67722. for(i=0; i<nSample; i++){
  67723. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  67724. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  67725. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  67726. }
  67727. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  67728. }
  67729. rc = sqlite3_finalize(pStmt);
  67730. if( rc ) return rc;
  67731. zSql = sqlite3MPrintf(db, zSql2, zDb);
  67732. if( !zSql ){
  67733. return SQLITE_NOMEM;
  67734. }
  67735. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  67736. sqlite3DbFree(db, zSql);
  67737. if( rc ) return rc;
  67738. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  67739. char *zIndex; /* Index name */
  67740. Index *pIdx; /* Pointer to the index object */
  67741. int nCol = 1; /* Number of columns in index */
  67742. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  67743. if( zIndex==0 ) continue;
  67744. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  67745. if( pIdx==0 ) continue;
  67746. /* This next condition is true if data has already been loaded from
  67747. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  67748. nCol = pIdx->nSampleCol;
  67749. if( bStat3 && nCol>1 ) continue;
  67750. if( pIdx!=pPrevIdx ){
  67751. initAvgEq(pPrevIdx);
  67752. pPrevIdx = pIdx;
  67753. }
  67754. pSample = &pIdx->aSample[pIdx->nSample];
  67755. decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
  67756. decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
  67757. decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
  67758. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  67759. ** This is in case the sample record is corrupted. In that case, the
  67760. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  67761. ** end of the allocated buffer before it realizes it is dealing with
  67762. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  67763. ** a buffer overread. */
  67764. pSample->n = sqlite3_column_bytes(pStmt, 4);
  67765. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  67766. if( pSample->p==0 ){
  67767. sqlite3_finalize(pStmt);
  67768. return SQLITE_NOMEM;
  67769. }
  67770. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  67771. pIdx->nSample++;
  67772. }
  67773. rc = sqlite3_finalize(pStmt);
  67774. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  67775. return rc;
  67776. }
  67777. /*
  67778. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  67779. ** the Index.aSample[] arrays of all indices.
  67780. */
  67781. static int loadStat4(sqlite3 *db, const char *zDb){
  67782. int rc = SQLITE_OK; /* Result codes from subroutines */
  67783. assert( db->lookaside.bEnabled==0 );
  67784. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  67785. rc = loadStatTbl(db, 0,
  67786. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  67787. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  67788. zDb
  67789. );
  67790. }
  67791. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  67792. rc = loadStatTbl(db, 1,
  67793. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  67794. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  67795. zDb
  67796. );
  67797. }
  67798. return rc;
  67799. }
  67800. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67801. /*
  67802. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  67803. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  67804. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  67805. ** Index.aSample[] arrays.
  67806. **
  67807. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  67808. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  67809. ** during compilation and the sqlite_stat3/4 table is present, no data is
  67810. ** read from it.
  67811. **
  67812. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  67813. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  67814. ** returned. However, in this case, data is read from the sqlite_stat1
  67815. ** table (if it is present) before returning.
  67816. **
  67817. ** If an OOM error occurs, this function always sets db->mallocFailed.
  67818. ** This means if the caller does not care about other errors, the return
  67819. ** code may be ignored.
  67820. */
  67821. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  67822. analysisInfo sInfo;
  67823. HashElem *i;
  67824. char *zSql;
  67825. int rc;
  67826. assert( iDb>=0 && iDb<db->nDb );
  67827. assert( db->aDb[iDb].pBt!=0 );
  67828. /* Clear any prior statistics */
  67829. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67830. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  67831. Index *pIdx = sqliteHashData(i);
  67832. sqlite3DefaultRowEst(pIdx);
  67833. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67834. sqlite3DeleteIndexSamples(db, pIdx);
  67835. pIdx->aSample = 0;
  67836. #endif
  67837. }
  67838. /* Check to make sure the sqlite_stat1 table exists */
  67839. sInfo.db = db;
  67840. sInfo.zDatabase = db->aDb[iDb].zName;
  67841. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  67842. return SQLITE_ERROR;
  67843. }
  67844. /* Load new statistics out of the sqlite_stat1 table */
  67845. zSql = sqlite3MPrintf(db,
  67846. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  67847. if( zSql==0 ){
  67848. rc = SQLITE_NOMEM;
  67849. }else{
  67850. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  67851. sqlite3DbFree(db, zSql);
  67852. }
  67853. /* Load the statistics from the sqlite_stat4 table. */
  67854. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67855. if( rc==SQLITE_OK ){
  67856. int lookasideEnabled = db->lookaside.bEnabled;
  67857. db->lookaside.bEnabled = 0;
  67858. rc = loadStat4(db, sInfo.zDatabase);
  67859. db->lookaside.bEnabled = lookasideEnabled;
  67860. }
  67861. #endif
  67862. if( rc==SQLITE_NOMEM ){
  67863. db->mallocFailed = 1;
  67864. }
  67865. return rc;
  67866. }
  67867. #endif /* SQLITE_OMIT_ANALYZE */
  67868. /************** End of analyze.c *********************************************/
  67869. /************** Begin file attach.c ******************************************/
  67870. /*
  67871. ** 2003 April 6
  67872. **
  67873. ** The author disclaims copyright to this source code. In place of
  67874. ** a legal notice, here is a blessing:
  67875. **
  67876. ** May you do good and not evil.
  67877. ** May you find forgiveness for yourself and forgive others.
  67878. ** May you share freely, never taking more than you give.
  67879. **
  67880. *************************************************************************
  67881. ** This file contains code used to implement the ATTACH and DETACH commands.
  67882. */
  67883. #ifndef SQLITE_OMIT_ATTACH
  67884. /*
  67885. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  67886. ** is slightly different from resolving a normal SQL expression, because simple
  67887. ** identifiers are treated as strings, not possible column names or aliases.
  67888. **
  67889. ** i.e. if the parser sees:
  67890. **
  67891. ** ATTACH DATABASE abc AS def
  67892. **
  67893. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  67894. ** looking for columns of the same name.
  67895. **
  67896. ** This only applies to the root node of pExpr, so the statement:
  67897. **
  67898. ** ATTACH DATABASE abc||def AS 'db2'
  67899. **
  67900. ** will fail because neither abc or def can be resolved.
  67901. */
  67902. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  67903. {
  67904. int rc = SQLITE_OK;
  67905. if( pExpr ){
  67906. if( pExpr->op!=TK_ID ){
  67907. rc = sqlite3ResolveExprNames(pName, pExpr);
  67908. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  67909. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  67910. return SQLITE_ERROR;
  67911. }
  67912. }else{
  67913. pExpr->op = TK_STRING;
  67914. }
  67915. }
  67916. return rc;
  67917. }
  67918. /*
  67919. ** An SQL user-function registered to do the work of an ATTACH statement. The
  67920. ** three arguments to the function come directly from an attach statement:
  67921. **
  67922. ** ATTACH DATABASE x AS y KEY z
  67923. **
  67924. ** SELECT sqlite_attach(x, y, z)
  67925. **
  67926. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  67927. ** third argument.
  67928. */
  67929. static void attachFunc(
  67930. sqlite3_context *context,
  67931. int NotUsed,
  67932. sqlite3_value **argv
  67933. ){
  67934. int i;
  67935. int rc = 0;
  67936. sqlite3 *db = sqlite3_context_db_handle(context);
  67937. const char *zName;
  67938. const char *zFile;
  67939. char *zPath = 0;
  67940. char *zErr = 0;
  67941. unsigned int flags;
  67942. Db *aNew;
  67943. char *zErrDyn = 0;
  67944. sqlite3_vfs *pVfs;
  67945. UNUSED_PARAMETER(NotUsed);
  67946. zFile = (const char *)sqlite3_value_text(argv[0]);
  67947. zName = (const char *)sqlite3_value_text(argv[1]);
  67948. if( zFile==0 ) zFile = "";
  67949. if( zName==0 ) zName = "";
  67950. /* Check for the following errors:
  67951. **
  67952. ** * Too many attached databases,
  67953. ** * Transaction currently open
  67954. ** * Specified database name already being used.
  67955. */
  67956. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  67957. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  67958. db->aLimit[SQLITE_LIMIT_ATTACHED]
  67959. );
  67960. goto attach_error;
  67961. }
  67962. if( !db->autoCommit ){
  67963. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  67964. goto attach_error;
  67965. }
  67966. for(i=0; i<db->nDb; i++){
  67967. char *z = db->aDb[i].zName;
  67968. assert( z && zName );
  67969. if( sqlite3StrICmp(z, zName)==0 ){
  67970. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  67971. goto attach_error;
  67972. }
  67973. }
  67974. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  67975. ** hash tables.
  67976. */
  67977. if( db->aDb==db->aDbStatic ){
  67978. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  67979. if( aNew==0 ) return;
  67980. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  67981. }else{
  67982. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  67983. if( aNew==0 ) return;
  67984. }
  67985. db->aDb = aNew;
  67986. aNew = &db->aDb[db->nDb];
  67987. memset(aNew, 0, sizeof(*aNew));
  67988. /* Open the database file. If the btree is successfully opened, use
  67989. ** it to obtain the database schema. At this point the schema may
  67990. ** or may not be initialized.
  67991. */
  67992. flags = db->openFlags;
  67993. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  67994. if( rc!=SQLITE_OK ){
  67995. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  67996. sqlite3_result_error(context, zErr, -1);
  67997. sqlite3_free(zErr);
  67998. return;
  67999. }
  68000. assert( pVfs );
  68001. flags |= SQLITE_OPEN_MAIN_DB;
  68002. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  68003. sqlite3_free( zPath );
  68004. db->nDb++;
  68005. if( rc==SQLITE_CONSTRAINT ){
  68006. rc = SQLITE_ERROR;
  68007. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  68008. }else if( rc==SQLITE_OK ){
  68009. Pager *pPager;
  68010. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  68011. if( !aNew->pSchema ){
  68012. rc = SQLITE_NOMEM;
  68013. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  68014. zErrDyn = sqlite3MPrintf(db,
  68015. "attached databases must use the same text encoding as main database");
  68016. rc = SQLITE_ERROR;
  68017. }
  68018. pPager = sqlite3BtreePager(aNew->pBt);
  68019. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  68020. sqlite3BtreeSecureDelete(aNew->pBt,
  68021. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  68022. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  68023. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  68024. #endif
  68025. }
  68026. aNew->safety_level = 3;
  68027. aNew->zName = sqlite3DbStrDup(db, zName);
  68028. if( rc==SQLITE_OK && aNew->zName==0 ){
  68029. rc = SQLITE_NOMEM;
  68030. }
  68031. #ifdef SQLITE_HAS_CODEC
  68032. if( rc==SQLITE_OK ){
  68033. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  68034. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  68035. int nKey;
  68036. char *zKey;
  68037. int t = sqlite3_value_type(argv[2]);
  68038. switch( t ){
  68039. case SQLITE_INTEGER:
  68040. case SQLITE_FLOAT:
  68041. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  68042. rc = SQLITE_ERROR;
  68043. break;
  68044. case SQLITE_TEXT:
  68045. case SQLITE_BLOB:
  68046. nKey = sqlite3_value_bytes(argv[2]);
  68047. zKey = (char *)sqlite3_value_blob(argv[2]);
  68048. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  68049. break;
  68050. case SQLITE_NULL:
  68051. /* No key specified. Use the key from the main database */
  68052. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  68053. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  68054. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  68055. }
  68056. break;
  68057. }
  68058. }
  68059. #endif
  68060. /* If the file was opened successfully, read the schema for the new database.
  68061. ** If this fails, or if opening the file failed, then close the file and
  68062. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  68063. ** we found it.
  68064. */
  68065. if( rc==SQLITE_OK ){
  68066. sqlite3BtreeEnterAll(db);
  68067. rc = sqlite3Init(db, &zErrDyn);
  68068. sqlite3BtreeLeaveAll(db);
  68069. }
  68070. if( rc ){
  68071. int iDb = db->nDb - 1;
  68072. assert( iDb>=2 );
  68073. if( db->aDb[iDb].pBt ){
  68074. sqlite3BtreeClose(db->aDb[iDb].pBt);
  68075. db->aDb[iDb].pBt = 0;
  68076. db->aDb[iDb].pSchema = 0;
  68077. }
  68078. sqlite3ResetAllSchemasOfConnection(db);
  68079. db->nDb = iDb;
  68080. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  68081. db->mallocFailed = 1;
  68082. sqlite3DbFree(db, zErrDyn);
  68083. zErrDyn = sqlite3MPrintf(db, "out of memory");
  68084. }else if( zErrDyn==0 ){
  68085. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  68086. }
  68087. goto attach_error;
  68088. }
  68089. return;
  68090. attach_error:
  68091. /* Return an error if we get here */
  68092. if( zErrDyn ){
  68093. sqlite3_result_error(context, zErrDyn, -1);
  68094. sqlite3DbFree(db, zErrDyn);
  68095. }
  68096. if( rc ) sqlite3_result_error_code(context, rc);
  68097. }
  68098. /*
  68099. ** An SQL user-function registered to do the work of an DETACH statement. The
  68100. ** three arguments to the function come directly from a detach statement:
  68101. **
  68102. ** DETACH DATABASE x
  68103. **
  68104. ** SELECT sqlite_detach(x)
  68105. */
  68106. static void detachFunc(
  68107. sqlite3_context *context,
  68108. int NotUsed,
  68109. sqlite3_value **argv
  68110. ){
  68111. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  68112. sqlite3 *db = sqlite3_context_db_handle(context);
  68113. int i;
  68114. Db *pDb = 0;
  68115. char zErr[128];
  68116. UNUSED_PARAMETER(NotUsed);
  68117. if( zName==0 ) zName = "";
  68118. for(i=0; i<db->nDb; i++){
  68119. pDb = &db->aDb[i];
  68120. if( pDb->pBt==0 ) continue;
  68121. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  68122. }
  68123. if( i>=db->nDb ){
  68124. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  68125. goto detach_error;
  68126. }
  68127. if( i<2 ){
  68128. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  68129. goto detach_error;
  68130. }
  68131. if( !db->autoCommit ){
  68132. sqlite3_snprintf(sizeof(zErr), zErr,
  68133. "cannot DETACH database within transaction");
  68134. goto detach_error;
  68135. }
  68136. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  68137. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  68138. goto detach_error;
  68139. }
  68140. sqlite3BtreeClose(pDb->pBt);
  68141. pDb->pBt = 0;
  68142. pDb->pSchema = 0;
  68143. sqlite3ResetAllSchemasOfConnection(db);
  68144. return;
  68145. detach_error:
  68146. sqlite3_result_error(context, zErr, -1);
  68147. }
  68148. /*
  68149. ** This procedure generates VDBE code for a single invocation of either the
  68150. ** sqlite_detach() or sqlite_attach() SQL user functions.
  68151. */
  68152. static void codeAttach(
  68153. Parse *pParse, /* The parser context */
  68154. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  68155. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  68156. Expr *pAuthArg, /* Expression to pass to authorization callback */
  68157. Expr *pFilename, /* Name of database file */
  68158. Expr *pDbname, /* Name of the database to use internally */
  68159. Expr *pKey /* Database key for encryption extension */
  68160. ){
  68161. int rc;
  68162. NameContext sName;
  68163. Vdbe *v;
  68164. sqlite3* db = pParse->db;
  68165. int regArgs;
  68166. memset(&sName, 0, sizeof(NameContext));
  68167. sName.pParse = pParse;
  68168. if(
  68169. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  68170. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  68171. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  68172. ){
  68173. pParse->nErr++;
  68174. goto attach_end;
  68175. }
  68176. #ifndef SQLITE_OMIT_AUTHORIZATION
  68177. if( pAuthArg ){
  68178. char *zAuthArg;
  68179. if( pAuthArg->op==TK_STRING ){
  68180. zAuthArg = pAuthArg->u.zToken;
  68181. }else{
  68182. zAuthArg = 0;
  68183. }
  68184. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  68185. if(rc!=SQLITE_OK ){
  68186. goto attach_end;
  68187. }
  68188. }
  68189. #endif /* SQLITE_OMIT_AUTHORIZATION */
  68190. v = sqlite3GetVdbe(pParse);
  68191. regArgs = sqlite3GetTempRange(pParse, 4);
  68192. sqlite3ExprCode(pParse, pFilename, regArgs);
  68193. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  68194. sqlite3ExprCode(pParse, pKey, regArgs+2);
  68195. assert( v || db->mallocFailed );
  68196. if( v ){
  68197. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  68198. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  68199. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  68200. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  68201. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  68202. ** statement only). For DETACH, set it to false (expire all existing
  68203. ** statements).
  68204. */
  68205. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  68206. }
  68207. attach_end:
  68208. sqlite3ExprDelete(db, pFilename);
  68209. sqlite3ExprDelete(db, pDbname);
  68210. sqlite3ExprDelete(db, pKey);
  68211. }
  68212. /*
  68213. ** Called by the parser to compile a DETACH statement.
  68214. **
  68215. ** DETACH pDbname
  68216. */
  68217. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  68218. static const FuncDef detach_func = {
  68219. 1, /* nArg */
  68220. SQLITE_UTF8, /* funcFlags */
  68221. 0, /* pUserData */
  68222. 0, /* pNext */
  68223. detachFunc, /* xFunc */
  68224. 0, /* xStep */
  68225. 0, /* xFinalize */
  68226. "sqlite_detach", /* zName */
  68227. 0, /* pHash */
  68228. 0 /* pDestructor */
  68229. };
  68230. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  68231. }
  68232. /*
  68233. ** Called by the parser to compile an ATTACH statement.
  68234. **
  68235. ** ATTACH p AS pDbname KEY pKey
  68236. */
  68237. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  68238. static const FuncDef attach_func = {
  68239. 3, /* nArg */
  68240. SQLITE_UTF8, /* funcFlags */
  68241. 0, /* pUserData */
  68242. 0, /* pNext */
  68243. attachFunc, /* xFunc */
  68244. 0, /* xStep */
  68245. 0, /* xFinalize */
  68246. "sqlite_attach", /* zName */
  68247. 0, /* pHash */
  68248. 0 /* pDestructor */
  68249. };
  68250. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  68251. }
  68252. #endif /* SQLITE_OMIT_ATTACH */
  68253. /*
  68254. ** Initialize a DbFixer structure. This routine must be called prior
  68255. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  68256. */
  68257. SQLITE_PRIVATE void sqlite3FixInit(
  68258. DbFixer *pFix, /* The fixer to be initialized */
  68259. Parse *pParse, /* Error messages will be written here */
  68260. int iDb, /* This is the database that must be used */
  68261. const char *zType, /* "view", "trigger", or "index" */
  68262. const Token *pName /* Name of the view, trigger, or index */
  68263. ){
  68264. sqlite3 *db;
  68265. db = pParse->db;
  68266. assert( db->nDb>iDb );
  68267. pFix->pParse = pParse;
  68268. pFix->zDb = db->aDb[iDb].zName;
  68269. pFix->pSchema = db->aDb[iDb].pSchema;
  68270. pFix->zType = zType;
  68271. pFix->pName = pName;
  68272. pFix->bVarOnly = (iDb==1);
  68273. }
  68274. /*
  68275. ** The following set of routines walk through the parse tree and assign
  68276. ** a specific database to all table references where the database name
  68277. ** was left unspecified in the original SQL statement. The pFix structure
  68278. ** must have been initialized by a prior call to sqlite3FixInit().
  68279. **
  68280. ** These routines are used to make sure that an index, trigger, or
  68281. ** view in one database does not refer to objects in a different database.
  68282. ** (Exception: indices, triggers, and views in the TEMP database are
  68283. ** allowed to refer to anything.) If a reference is explicitly made
  68284. ** to an object in a different database, an error message is added to
  68285. ** pParse->zErrMsg and these routines return non-zero. If everything
  68286. ** checks out, these routines return 0.
  68287. */
  68288. SQLITE_PRIVATE int sqlite3FixSrcList(
  68289. DbFixer *pFix, /* Context of the fixation */
  68290. SrcList *pList /* The Source list to check and modify */
  68291. ){
  68292. int i;
  68293. const char *zDb;
  68294. struct SrcList_item *pItem;
  68295. if( NEVER(pList==0) ) return 0;
  68296. zDb = pFix->zDb;
  68297. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  68298. if( pFix->bVarOnly==0 ){
  68299. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  68300. sqlite3ErrorMsg(pFix->pParse,
  68301. "%s %T cannot reference objects in database %s",
  68302. pFix->zType, pFix->pName, pItem->zDatabase);
  68303. return 1;
  68304. }
  68305. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  68306. pItem->zDatabase = 0;
  68307. pItem->pSchema = pFix->pSchema;
  68308. }
  68309. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  68310. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  68311. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  68312. #endif
  68313. }
  68314. return 0;
  68315. }
  68316. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  68317. SQLITE_PRIVATE int sqlite3FixSelect(
  68318. DbFixer *pFix, /* Context of the fixation */
  68319. Select *pSelect /* The SELECT statement to be fixed to one database */
  68320. ){
  68321. while( pSelect ){
  68322. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  68323. return 1;
  68324. }
  68325. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  68326. return 1;
  68327. }
  68328. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  68329. return 1;
  68330. }
  68331. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  68332. return 1;
  68333. }
  68334. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  68335. return 1;
  68336. }
  68337. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  68338. return 1;
  68339. }
  68340. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  68341. return 1;
  68342. }
  68343. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  68344. return 1;
  68345. }
  68346. pSelect = pSelect->pPrior;
  68347. }
  68348. return 0;
  68349. }
  68350. SQLITE_PRIVATE int sqlite3FixExpr(
  68351. DbFixer *pFix, /* Context of the fixation */
  68352. Expr *pExpr /* The expression to be fixed to one database */
  68353. ){
  68354. while( pExpr ){
  68355. if( pExpr->op==TK_VARIABLE ){
  68356. if( pFix->pParse->db->init.busy ){
  68357. pExpr->op = TK_NULL;
  68358. }else{
  68359. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  68360. return 1;
  68361. }
  68362. }
  68363. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  68364. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  68365. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  68366. }else{
  68367. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  68368. }
  68369. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  68370. return 1;
  68371. }
  68372. pExpr = pExpr->pLeft;
  68373. }
  68374. return 0;
  68375. }
  68376. SQLITE_PRIVATE int sqlite3FixExprList(
  68377. DbFixer *pFix, /* Context of the fixation */
  68378. ExprList *pList /* The expression to be fixed to one database */
  68379. ){
  68380. int i;
  68381. struct ExprList_item *pItem;
  68382. if( pList==0 ) return 0;
  68383. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  68384. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  68385. return 1;
  68386. }
  68387. }
  68388. return 0;
  68389. }
  68390. #endif
  68391. #ifndef SQLITE_OMIT_TRIGGER
  68392. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  68393. DbFixer *pFix, /* Context of the fixation */
  68394. TriggerStep *pStep /* The trigger step be fixed to one database */
  68395. ){
  68396. while( pStep ){
  68397. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  68398. return 1;
  68399. }
  68400. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  68401. return 1;
  68402. }
  68403. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  68404. return 1;
  68405. }
  68406. pStep = pStep->pNext;
  68407. }
  68408. return 0;
  68409. }
  68410. #endif
  68411. /************** End of attach.c **********************************************/
  68412. /************** Begin file auth.c ********************************************/
  68413. /*
  68414. ** 2003 January 11
  68415. **
  68416. ** The author disclaims copyright to this source code. In place of
  68417. ** a legal notice, here is a blessing:
  68418. **
  68419. ** May you do good and not evil.
  68420. ** May you find forgiveness for yourself and forgive others.
  68421. ** May you share freely, never taking more than you give.
  68422. **
  68423. *************************************************************************
  68424. ** This file contains code used to implement the sqlite3_set_authorizer()
  68425. ** API. This facility is an optional feature of the library. Embedded
  68426. ** systems that do not need this facility may omit it by recompiling
  68427. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  68428. */
  68429. /*
  68430. ** All of the code in this file may be omitted by defining a single
  68431. ** macro.
  68432. */
  68433. #ifndef SQLITE_OMIT_AUTHORIZATION
  68434. /*
  68435. ** Set or clear the access authorization function.
  68436. **
  68437. ** The access authorization function is be called during the compilation
  68438. ** phase to verify that the user has read and/or write access permission on
  68439. ** various fields of the database. The first argument to the auth function
  68440. ** is a copy of the 3rd argument to this routine. The second argument
  68441. ** to the auth function is one of these constants:
  68442. **
  68443. ** SQLITE_CREATE_INDEX
  68444. ** SQLITE_CREATE_TABLE
  68445. ** SQLITE_CREATE_TEMP_INDEX
  68446. ** SQLITE_CREATE_TEMP_TABLE
  68447. ** SQLITE_CREATE_TEMP_TRIGGER
  68448. ** SQLITE_CREATE_TEMP_VIEW
  68449. ** SQLITE_CREATE_TRIGGER
  68450. ** SQLITE_CREATE_VIEW
  68451. ** SQLITE_DELETE
  68452. ** SQLITE_DROP_INDEX
  68453. ** SQLITE_DROP_TABLE
  68454. ** SQLITE_DROP_TEMP_INDEX
  68455. ** SQLITE_DROP_TEMP_TABLE
  68456. ** SQLITE_DROP_TEMP_TRIGGER
  68457. ** SQLITE_DROP_TEMP_VIEW
  68458. ** SQLITE_DROP_TRIGGER
  68459. ** SQLITE_DROP_VIEW
  68460. ** SQLITE_INSERT
  68461. ** SQLITE_PRAGMA
  68462. ** SQLITE_READ
  68463. ** SQLITE_SELECT
  68464. ** SQLITE_TRANSACTION
  68465. ** SQLITE_UPDATE
  68466. **
  68467. ** The third and fourth arguments to the auth function are the name of
  68468. ** the table and the column that are being accessed. The auth function
  68469. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  68470. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  68471. ** means that the SQL statement will never-run - the sqlite3_exec() call
  68472. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  68473. ** should run but attempts to read the specified column will return NULL
  68474. ** and attempts to write the column will be ignored.
  68475. **
  68476. ** Setting the auth function to NULL disables this hook. The default
  68477. ** setting of the auth function is NULL.
  68478. */
  68479. SQLITE_API int sqlite3_set_authorizer(
  68480. sqlite3 *db,
  68481. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  68482. void *pArg
  68483. ){
  68484. sqlite3_mutex_enter(db->mutex);
  68485. db->xAuth = xAuth;
  68486. db->pAuthArg = pArg;
  68487. sqlite3ExpirePreparedStatements(db);
  68488. sqlite3_mutex_leave(db->mutex);
  68489. return SQLITE_OK;
  68490. }
  68491. /*
  68492. ** Write an error message into pParse->zErrMsg that explains that the
  68493. ** user-supplied authorization function returned an illegal value.
  68494. */
  68495. static void sqliteAuthBadReturnCode(Parse *pParse){
  68496. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  68497. pParse->rc = SQLITE_ERROR;
  68498. }
  68499. /*
  68500. ** Invoke the authorization callback for permission to read column zCol from
  68501. ** table zTab in database zDb. This function assumes that an authorization
  68502. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  68503. **
  68504. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  68505. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  68506. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  68507. */
  68508. SQLITE_PRIVATE int sqlite3AuthReadCol(
  68509. Parse *pParse, /* The parser context */
  68510. const char *zTab, /* Table name */
  68511. const char *zCol, /* Column name */
  68512. int iDb /* Index of containing database. */
  68513. ){
  68514. sqlite3 *db = pParse->db; /* Database handle */
  68515. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  68516. int rc; /* Auth callback return code */
  68517. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  68518. if( rc==SQLITE_DENY ){
  68519. if( db->nDb>2 || iDb!=0 ){
  68520. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  68521. }else{
  68522. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  68523. }
  68524. pParse->rc = SQLITE_AUTH;
  68525. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  68526. sqliteAuthBadReturnCode(pParse);
  68527. }
  68528. return rc;
  68529. }
  68530. /*
  68531. ** The pExpr should be a TK_COLUMN expression. The table referred to
  68532. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  68533. ** Check to see if it is OK to read this particular column.
  68534. **
  68535. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  68536. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  68537. ** then generate an error.
  68538. */
  68539. SQLITE_PRIVATE void sqlite3AuthRead(
  68540. Parse *pParse, /* The parser context */
  68541. Expr *pExpr, /* The expression to check authorization on */
  68542. Schema *pSchema, /* The schema of the expression */
  68543. SrcList *pTabList /* All table that pExpr might refer to */
  68544. ){
  68545. sqlite3 *db = pParse->db;
  68546. Table *pTab = 0; /* The table being read */
  68547. const char *zCol; /* Name of the column of the table */
  68548. int iSrc; /* Index in pTabList->a[] of table being read */
  68549. int iDb; /* The index of the database the expression refers to */
  68550. int iCol; /* Index of column in table */
  68551. if( db->xAuth==0 ) return;
  68552. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  68553. if( iDb<0 ){
  68554. /* An attempt to read a column out of a subquery or other
  68555. ** temporary table. */
  68556. return;
  68557. }
  68558. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  68559. if( pExpr->op==TK_TRIGGER ){
  68560. pTab = pParse->pTriggerTab;
  68561. }else{
  68562. assert( pTabList );
  68563. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  68564. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  68565. pTab = pTabList->a[iSrc].pTab;
  68566. break;
  68567. }
  68568. }
  68569. }
  68570. iCol = pExpr->iColumn;
  68571. if( NEVER(pTab==0) ) return;
  68572. if( iCol>=0 ){
  68573. assert( iCol<pTab->nCol );
  68574. zCol = pTab->aCol[iCol].zName;
  68575. }else if( pTab->iPKey>=0 ){
  68576. assert( pTab->iPKey<pTab->nCol );
  68577. zCol = pTab->aCol[pTab->iPKey].zName;
  68578. }else{
  68579. zCol = "ROWID";
  68580. }
  68581. assert( iDb>=0 && iDb<db->nDb );
  68582. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  68583. pExpr->op = TK_NULL;
  68584. }
  68585. }
  68586. /*
  68587. ** Do an authorization check using the code and arguments given. Return
  68588. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  68589. ** is returned, then the error count and error message in pParse are
  68590. ** modified appropriately.
  68591. */
  68592. SQLITE_PRIVATE int sqlite3AuthCheck(
  68593. Parse *pParse,
  68594. int code,
  68595. const char *zArg1,
  68596. const char *zArg2,
  68597. const char *zArg3
  68598. ){
  68599. sqlite3 *db = pParse->db;
  68600. int rc;
  68601. /* Don't do any authorization checks if the database is initialising
  68602. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  68603. */
  68604. if( db->init.busy || IN_DECLARE_VTAB ){
  68605. return SQLITE_OK;
  68606. }
  68607. if( db->xAuth==0 ){
  68608. return SQLITE_OK;
  68609. }
  68610. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  68611. if( rc==SQLITE_DENY ){
  68612. sqlite3ErrorMsg(pParse, "not authorized");
  68613. pParse->rc = SQLITE_AUTH;
  68614. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  68615. rc = SQLITE_DENY;
  68616. sqliteAuthBadReturnCode(pParse);
  68617. }
  68618. return rc;
  68619. }
  68620. /*
  68621. ** Push an authorization context. After this routine is called, the
  68622. ** zArg3 argument to authorization callbacks will be zContext until
  68623. ** popped. Or if pParse==0, this routine is a no-op.
  68624. */
  68625. SQLITE_PRIVATE void sqlite3AuthContextPush(
  68626. Parse *pParse,
  68627. AuthContext *pContext,
  68628. const char *zContext
  68629. ){
  68630. assert( pParse );
  68631. pContext->pParse = pParse;
  68632. pContext->zAuthContext = pParse->zAuthContext;
  68633. pParse->zAuthContext = zContext;
  68634. }
  68635. /*
  68636. ** Pop an authorization context that was previously pushed
  68637. ** by sqlite3AuthContextPush
  68638. */
  68639. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  68640. if( pContext->pParse ){
  68641. pContext->pParse->zAuthContext = pContext->zAuthContext;
  68642. pContext->pParse = 0;
  68643. }
  68644. }
  68645. #endif /* SQLITE_OMIT_AUTHORIZATION */
  68646. /************** End of auth.c ************************************************/
  68647. /************** Begin file build.c *******************************************/
  68648. /*
  68649. ** 2001 September 15
  68650. **
  68651. ** The author disclaims copyright to this source code. In place of
  68652. ** a legal notice, here is a blessing:
  68653. **
  68654. ** May you do good and not evil.
  68655. ** May you find forgiveness for yourself and forgive others.
  68656. ** May you share freely, never taking more than you give.
  68657. **
  68658. *************************************************************************
  68659. ** This file contains C code routines that are called by the SQLite parser
  68660. ** when syntax rules are reduced. The routines in this file handle the
  68661. ** following kinds of SQL syntax:
  68662. **
  68663. ** CREATE TABLE
  68664. ** DROP TABLE
  68665. ** CREATE INDEX
  68666. ** DROP INDEX
  68667. ** creating ID lists
  68668. ** BEGIN TRANSACTION
  68669. ** COMMIT
  68670. ** ROLLBACK
  68671. */
  68672. /*
  68673. ** This routine is called when a new SQL statement is beginning to
  68674. ** be parsed. Initialize the pParse structure as needed.
  68675. */
  68676. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  68677. pParse->explain = (u8)explainFlag;
  68678. pParse->nVar = 0;
  68679. }
  68680. #ifndef SQLITE_OMIT_SHARED_CACHE
  68681. /*
  68682. ** The TableLock structure is only used by the sqlite3TableLock() and
  68683. ** codeTableLocks() functions.
  68684. */
  68685. struct TableLock {
  68686. int iDb; /* The database containing the table to be locked */
  68687. int iTab; /* The root page of the table to be locked */
  68688. u8 isWriteLock; /* True for write lock. False for a read lock */
  68689. const char *zName; /* Name of the table */
  68690. };
  68691. /*
  68692. ** Record the fact that we want to lock a table at run-time.
  68693. **
  68694. ** The table to be locked has root page iTab and is found in database iDb.
  68695. ** A read or a write lock can be taken depending on isWritelock.
  68696. **
  68697. ** This routine just records the fact that the lock is desired. The
  68698. ** code to make the lock occur is generated by a later call to
  68699. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  68700. */
  68701. SQLITE_PRIVATE void sqlite3TableLock(
  68702. Parse *pParse, /* Parsing context */
  68703. int iDb, /* Index of the database containing the table to lock */
  68704. int iTab, /* Root page number of the table to be locked */
  68705. u8 isWriteLock, /* True for a write lock */
  68706. const char *zName /* Name of the table to be locked */
  68707. ){
  68708. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  68709. int i;
  68710. int nBytes;
  68711. TableLock *p;
  68712. assert( iDb>=0 );
  68713. for(i=0; i<pToplevel->nTableLock; i++){
  68714. p = &pToplevel->aTableLock[i];
  68715. if( p->iDb==iDb && p->iTab==iTab ){
  68716. p->isWriteLock = (p->isWriteLock || isWriteLock);
  68717. return;
  68718. }
  68719. }
  68720. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  68721. pToplevel->aTableLock =
  68722. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  68723. if( pToplevel->aTableLock ){
  68724. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  68725. p->iDb = iDb;
  68726. p->iTab = iTab;
  68727. p->isWriteLock = isWriteLock;
  68728. p->zName = zName;
  68729. }else{
  68730. pToplevel->nTableLock = 0;
  68731. pToplevel->db->mallocFailed = 1;
  68732. }
  68733. }
  68734. /*
  68735. ** Code an OP_TableLock instruction for each table locked by the
  68736. ** statement (configured by calls to sqlite3TableLock()).
  68737. */
  68738. static void codeTableLocks(Parse *pParse){
  68739. int i;
  68740. Vdbe *pVdbe;
  68741. pVdbe = sqlite3GetVdbe(pParse);
  68742. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  68743. for(i=0; i<pParse->nTableLock; i++){
  68744. TableLock *p = &pParse->aTableLock[i];
  68745. int p1 = p->iDb;
  68746. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  68747. p->zName, P4_STATIC);
  68748. }
  68749. }
  68750. #else
  68751. #define codeTableLocks(x)
  68752. #endif
  68753. /*
  68754. ** This routine is called after a single SQL statement has been
  68755. ** parsed and a VDBE program to execute that statement has been
  68756. ** prepared. This routine puts the finishing touches on the
  68757. ** VDBE program and resets the pParse structure for the next
  68758. ** parse.
  68759. **
  68760. ** Note that if an error occurred, it might be the case that
  68761. ** no VDBE code was generated.
  68762. */
  68763. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  68764. sqlite3 *db;
  68765. Vdbe *v;
  68766. assert( pParse->pToplevel==0 );
  68767. db = pParse->db;
  68768. if( db->mallocFailed ) return;
  68769. if( pParse->nested ) return;
  68770. if( pParse->nErr ) return;
  68771. /* Begin by generating some termination code at the end of the
  68772. ** vdbe program
  68773. */
  68774. v = sqlite3GetVdbe(pParse);
  68775. assert( !pParse->isMultiWrite
  68776. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  68777. if( v ){
  68778. sqlite3VdbeAddOp0(v, OP_Halt);
  68779. /* The cookie mask contains one bit for each database file open.
  68780. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  68781. ** set for each database that is used. Generate code to start a
  68782. ** transaction on each used database and to verify the schema cookie
  68783. ** on each used database.
  68784. */
  68785. if( pParse->cookieGoto>0 ){
  68786. yDbMask mask;
  68787. int iDb;
  68788. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  68789. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  68790. if( (mask & pParse->cookieMask)==0 ) continue;
  68791. sqlite3VdbeUsesBtree(v, iDb);
  68792. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  68793. if( db->init.busy==0 ){
  68794. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  68795. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  68796. iDb, pParse->cookieValue[iDb],
  68797. db->aDb[iDb].pSchema->iGeneration);
  68798. }
  68799. }
  68800. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68801. {
  68802. int i;
  68803. for(i=0; i<pParse->nVtabLock; i++){
  68804. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  68805. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  68806. }
  68807. pParse->nVtabLock = 0;
  68808. }
  68809. #endif
  68810. /* Once all the cookies have been verified and transactions opened,
  68811. ** obtain the required table-locks. This is a no-op unless the
  68812. ** shared-cache feature is enabled.
  68813. */
  68814. codeTableLocks(pParse);
  68815. /* Initialize any AUTOINCREMENT data structures required.
  68816. */
  68817. sqlite3AutoincrementBegin(pParse);
  68818. /* Finally, jump back to the beginning of the executable code. */
  68819. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  68820. }
  68821. }
  68822. /* Get the VDBE program ready for execution
  68823. */
  68824. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  68825. #ifdef SQLITE_DEBUG
  68826. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  68827. sqlite3VdbeTrace(v, trace);
  68828. #endif
  68829. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  68830. /* A minimum of one cursor is required if autoincrement is used
  68831. * See ticket [a696379c1f08866] */
  68832. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  68833. sqlite3VdbeMakeReady(v, pParse);
  68834. pParse->rc = SQLITE_DONE;
  68835. pParse->colNamesSet = 0;
  68836. }else{
  68837. pParse->rc = SQLITE_ERROR;
  68838. }
  68839. pParse->nTab = 0;
  68840. pParse->nMem = 0;
  68841. pParse->nSet = 0;
  68842. pParse->nVar = 0;
  68843. pParse->cookieMask = 0;
  68844. pParse->cookieGoto = 0;
  68845. }
  68846. /*
  68847. ** Run the parser and code generator recursively in order to generate
  68848. ** code for the SQL statement given onto the end of the pParse context
  68849. ** currently under construction. When the parser is run recursively
  68850. ** this way, the final OP_Halt is not appended and other initialization
  68851. ** and finalization steps are omitted because those are handling by the
  68852. ** outermost parser.
  68853. **
  68854. ** Not everything is nestable. This facility is designed to permit
  68855. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  68856. ** care if you decide to try to use this routine for some other purposes.
  68857. */
  68858. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  68859. va_list ap;
  68860. char *zSql;
  68861. char *zErrMsg = 0;
  68862. sqlite3 *db = pParse->db;
  68863. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  68864. char saveBuf[SAVE_SZ];
  68865. if( pParse->nErr ) return;
  68866. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  68867. va_start(ap, zFormat);
  68868. zSql = sqlite3VMPrintf(db, zFormat, ap);
  68869. va_end(ap);
  68870. if( zSql==0 ){
  68871. return; /* A malloc must have failed */
  68872. }
  68873. pParse->nested++;
  68874. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  68875. memset(&pParse->nVar, 0, SAVE_SZ);
  68876. sqlite3RunParser(pParse, zSql, &zErrMsg);
  68877. sqlite3DbFree(db, zErrMsg);
  68878. sqlite3DbFree(db, zSql);
  68879. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  68880. pParse->nested--;
  68881. }
  68882. /*
  68883. ** Locate the in-memory structure that describes a particular database
  68884. ** table given the name of that table and (optionally) the name of the
  68885. ** database containing the table. Return NULL if not found.
  68886. **
  68887. ** If zDatabase is 0, all databases are searched for the table and the
  68888. ** first matching table is returned. (No checking for duplicate table
  68889. ** names is done.) The search order is TEMP first, then MAIN, then any
  68890. ** auxiliary databases added using the ATTACH command.
  68891. **
  68892. ** See also sqlite3LocateTable().
  68893. */
  68894. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  68895. Table *p = 0;
  68896. int i;
  68897. int nName;
  68898. assert( zName!=0 );
  68899. nName = sqlite3Strlen30(zName);
  68900. /* All mutexes are required for schema access. Make sure we hold them. */
  68901. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  68902. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  68903. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  68904. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  68905. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  68906. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  68907. if( p ) break;
  68908. }
  68909. return p;
  68910. }
  68911. /*
  68912. ** Locate the in-memory structure that describes a particular database
  68913. ** table given the name of that table and (optionally) the name of the
  68914. ** database containing the table. Return NULL if not found. Also leave an
  68915. ** error message in pParse->zErrMsg.
  68916. **
  68917. ** The difference between this routine and sqlite3FindTable() is that this
  68918. ** routine leaves an error message in pParse->zErrMsg where
  68919. ** sqlite3FindTable() does not.
  68920. */
  68921. SQLITE_PRIVATE Table *sqlite3LocateTable(
  68922. Parse *pParse, /* context in which to report errors */
  68923. int isView, /* True if looking for a VIEW rather than a TABLE */
  68924. const char *zName, /* Name of the table we are looking for */
  68925. const char *zDbase /* Name of the database. Might be NULL */
  68926. ){
  68927. Table *p;
  68928. /* Read the database schema. If an error occurs, leave an error message
  68929. ** and code in pParse and return NULL. */
  68930. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  68931. return 0;
  68932. }
  68933. p = sqlite3FindTable(pParse->db, zName, zDbase);
  68934. if( p==0 ){
  68935. const char *zMsg = isView ? "no such view" : "no such table";
  68936. if( zDbase ){
  68937. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  68938. }else{
  68939. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  68940. }
  68941. pParse->checkSchema = 1;
  68942. }
  68943. return p;
  68944. }
  68945. /*
  68946. ** Locate the table identified by *p.
  68947. **
  68948. ** This is a wrapper around sqlite3LocateTable(). The difference between
  68949. ** sqlite3LocateTable() and this function is that this function restricts
  68950. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  68951. ** non-NULL if it is part of a view or trigger program definition. See
  68952. ** sqlite3FixSrcList() for details.
  68953. */
  68954. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  68955. Parse *pParse,
  68956. int isView,
  68957. struct SrcList_item *p
  68958. ){
  68959. const char *zDb;
  68960. assert( p->pSchema==0 || p->zDatabase==0 );
  68961. if( p->pSchema ){
  68962. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  68963. zDb = pParse->db->aDb[iDb].zName;
  68964. }else{
  68965. zDb = p->zDatabase;
  68966. }
  68967. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  68968. }
  68969. /*
  68970. ** Locate the in-memory structure that describes
  68971. ** a particular index given the name of that index
  68972. ** and the name of the database that contains the index.
  68973. ** Return NULL if not found.
  68974. **
  68975. ** If zDatabase is 0, all databases are searched for the
  68976. ** table and the first matching index is returned. (No checking
  68977. ** for duplicate index names is done.) The search order is
  68978. ** TEMP first, then MAIN, then any auxiliary databases added
  68979. ** using the ATTACH command.
  68980. */
  68981. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  68982. Index *p = 0;
  68983. int i;
  68984. int nName = sqlite3Strlen30(zName);
  68985. /* All mutexes are required for schema access. Make sure we hold them. */
  68986. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  68987. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  68988. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  68989. Schema *pSchema = db->aDb[j].pSchema;
  68990. assert( pSchema );
  68991. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  68992. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  68993. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  68994. if( p ) break;
  68995. }
  68996. return p;
  68997. }
  68998. /*
  68999. ** Reclaim the memory used by an index
  69000. */
  69001. static void freeIndex(sqlite3 *db, Index *p){
  69002. #ifndef SQLITE_OMIT_ANALYZE
  69003. sqlite3DeleteIndexSamples(db, p);
  69004. #endif
  69005. sqlite3ExprDelete(db, p->pPartIdxWhere);
  69006. sqlite3DbFree(db, p->zColAff);
  69007. sqlite3DbFree(db, p);
  69008. }
  69009. /*
  69010. ** For the index called zIdxName which is found in the database iDb,
  69011. ** unlike that index from its Table then remove the index from
  69012. ** the index hash table and free all memory structures associated
  69013. ** with the index.
  69014. */
  69015. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  69016. Index *pIndex;
  69017. int len;
  69018. Hash *pHash;
  69019. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69020. pHash = &db->aDb[iDb].pSchema->idxHash;
  69021. len = sqlite3Strlen30(zIdxName);
  69022. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  69023. if( ALWAYS(pIndex) ){
  69024. if( pIndex->pTable->pIndex==pIndex ){
  69025. pIndex->pTable->pIndex = pIndex->pNext;
  69026. }else{
  69027. Index *p;
  69028. /* Justification of ALWAYS(); The index must be on the list of
  69029. ** indices. */
  69030. p = pIndex->pTable->pIndex;
  69031. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  69032. if( ALWAYS(p && p->pNext==pIndex) ){
  69033. p->pNext = pIndex->pNext;
  69034. }
  69035. }
  69036. freeIndex(db, pIndex);
  69037. }
  69038. db->flags |= SQLITE_InternChanges;
  69039. }
  69040. /*
  69041. ** Look through the list of open database files in db->aDb[] and if
  69042. ** any have been closed, remove them from the list. Reallocate the
  69043. ** db->aDb[] structure to a smaller size, if possible.
  69044. **
  69045. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  69046. ** are never candidates for being collapsed.
  69047. */
  69048. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  69049. int i, j;
  69050. for(i=j=2; i<db->nDb; i++){
  69051. struct Db *pDb = &db->aDb[i];
  69052. if( pDb->pBt==0 ){
  69053. sqlite3DbFree(db, pDb->zName);
  69054. pDb->zName = 0;
  69055. continue;
  69056. }
  69057. if( j<i ){
  69058. db->aDb[j] = db->aDb[i];
  69059. }
  69060. j++;
  69061. }
  69062. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  69063. db->nDb = j;
  69064. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  69065. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  69066. sqlite3DbFree(db, db->aDb);
  69067. db->aDb = db->aDbStatic;
  69068. }
  69069. }
  69070. /*
  69071. ** Reset the schema for the database at index iDb. Also reset the
  69072. ** TEMP schema.
  69073. */
  69074. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  69075. Db *pDb;
  69076. assert( iDb<db->nDb );
  69077. /* Case 1: Reset the single schema identified by iDb */
  69078. pDb = &db->aDb[iDb];
  69079. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69080. assert( pDb->pSchema!=0 );
  69081. sqlite3SchemaClear(pDb->pSchema);
  69082. /* If any database other than TEMP is reset, then also reset TEMP
  69083. ** since TEMP might be holding triggers that reference tables in the
  69084. ** other database.
  69085. */
  69086. if( iDb!=1 ){
  69087. pDb = &db->aDb[1];
  69088. assert( pDb->pSchema!=0 );
  69089. sqlite3SchemaClear(pDb->pSchema);
  69090. }
  69091. return;
  69092. }
  69093. /*
  69094. ** Erase all schema information from all attached databases (including
  69095. ** "main" and "temp") for a single database connection.
  69096. */
  69097. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  69098. int i;
  69099. sqlite3BtreeEnterAll(db);
  69100. for(i=0; i<db->nDb; i++){
  69101. Db *pDb = &db->aDb[i];
  69102. if( pDb->pSchema ){
  69103. sqlite3SchemaClear(pDb->pSchema);
  69104. }
  69105. }
  69106. db->flags &= ~SQLITE_InternChanges;
  69107. sqlite3VtabUnlockList(db);
  69108. sqlite3BtreeLeaveAll(db);
  69109. sqlite3CollapseDatabaseArray(db);
  69110. }
  69111. /*
  69112. ** This routine is called when a commit occurs.
  69113. */
  69114. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  69115. db->flags &= ~SQLITE_InternChanges;
  69116. }
  69117. /*
  69118. ** Delete memory allocated for the column names of a table or view (the
  69119. ** Table.aCol[] array).
  69120. */
  69121. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  69122. int i;
  69123. Column *pCol;
  69124. assert( pTable!=0 );
  69125. if( (pCol = pTable->aCol)!=0 ){
  69126. for(i=0; i<pTable->nCol; i++, pCol++){
  69127. sqlite3DbFree(db, pCol->zName);
  69128. sqlite3ExprDelete(db, pCol->pDflt);
  69129. sqlite3DbFree(db, pCol->zDflt);
  69130. sqlite3DbFree(db, pCol->zType);
  69131. sqlite3DbFree(db, pCol->zColl);
  69132. }
  69133. sqlite3DbFree(db, pTable->aCol);
  69134. }
  69135. }
  69136. /*
  69137. ** Remove the memory data structures associated with the given
  69138. ** Table. No changes are made to disk by this routine.
  69139. **
  69140. ** This routine just deletes the data structure. It does not unlink
  69141. ** the table data structure from the hash table. But it does destroy
  69142. ** memory structures of the indices and foreign keys associated with
  69143. ** the table.
  69144. **
  69145. ** The db parameter is optional. It is needed if the Table object
  69146. ** contains lookaside memory. (Table objects in the schema do not use
  69147. ** lookaside memory, but some ephemeral Table objects do.) Or the
  69148. ** db parameter can be used with db->pnBytesFreed to measure the memory
  69149. ** used by the Table object.
  69150. */
  69151. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  69152. Index *pIndex, *pNext;
  69153. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  69154. assert( !pTable || pTable->nRef>0 );
  69155. /* Do not delete the table until the reference count reaches zero. */
  69156. if( !pTable ) return;
  69157. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  69158. /* Record the number of outstanding lookaside allocations in schema Tables
  69159. ** prior to doing any free() operations. Since schema Tables do not use
  69160. ** lookaside, this number should not change. */
  69161. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  69162. db->lookaside.nOut : 0 );
  69163. /* Delete all indices associated with this table. */
  69164. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  69165. pNext = pIndex->pNext;
  69166. assert( pIndex->pSchema==pTable->pSchema );
  69167. if( !db || db->pnBytesFreed==0 ){
  69168. char *zName = pIndex->zName;
  69169. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  69170. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  69171. );
  69172. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  69173. assert( pOld==pIndex || pOld==0 );
  69174. }
  69175. freeIndex(db, pIndex);
  69176. }
  69177. /* Delete any foreign keys attached to this table. */
  69178. sqlite3FkDelete(db, pTable);
  69179. /* Delete the Table structure itself.
  69180. */
  69181. sqliteDeleteColumnNames(db, pTable);
  69182. sqlite3DbFree(db, pTable->zName);
  69183. sqlite3DbFree(db, pTable->zColAff);
  69184. sqlite3SelectDelete(db, pTable->pSelect);
  69185. #ifndef SQLITE_OMIT_CHECK
  69186. sqlite3ExprListDelete(db, pTable->pCheck);
  69187. #endif
  69188. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69189. sqlite3VtabClear(db, pTable);
  69190. #endif
  69191. sqlite3DbFree(db, pTable);
  69192. /* Verify that no lookaside memory was used by schema tables */
  69193. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  69194. }
  69195. /*
  69196. ** Unlink the given table from the hash tables and the delete the
  69197. ** table structure with all its indices and foreign keys.
  69198. */
  69199. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  69200. Table *p;
  69201. Db *pDb;
  69202. assert( db!=0 );
  69203. assert( iDb>=0 && iDb<db->nDb );
  69204. assert( zTabName );
  69205. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69206. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  69207. pDb = &db->aDb[iDb];
  69208. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  69209. sqlite3Strlen30(zTabName),0);
  69210. sqlite3DeleteTable(db, p);
  69211. db->flags |= SQLITE_InternChanges;
  69212. }
  69213. /*
  69214. ** Given a token, return a string that consists of the text of that
  69215. ** token. Space to hold the returned string
  69216. ** is obtained from sqliteMalloc() and must be freed by the calling
  69217. ** function.
  69218. **
  69219. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  69220. ** surround the body of the token are removed.
  69221. **
  69222. ** Tokens are often just pointers into the original SQL text and so
  69223. ** are not \000 terminated and are not persistent. The returned string
  69224. ** is \000 terminated and is persistent.
  69225. */
  69226. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  69227. char *zName;
  69228. if( pName ){
  69229. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  69230. sqlite3Dequote(zName);
  69231. }else{
  69232. zName = 0;
  69233. }
  69234. return zName;
  69235. }
  69236. /*
  69237. ** Open the sqlite_master table stored in database number iDb for
  69238. ** writing. The table is opened using cursor 0.
  69239. */
  69240. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  69241. Vdbe *v = sqlite3GetVdbe(p);
  69242. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  69243. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  69244. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  69245. if( p->nTab==0 ){
  69246. p->nTab = 1;
  69247. }
  69248. }
  69249. /*
  69250. ** Parameter zName points to a nul-terminated buffer containing the name
  69251. ** of a database ("main", "temp" or the name of an attached db). This
  69252. ** function returns the index of the named database in db->aDb[], or
  69253. ** -1 if the named db cannot be found.
  69254. */
  69255. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  69256. int i = -1; /* Database number */
  69257. if( zName ){
  69258. Db *pDb;
  69259. int n = sqlite3Strlen30(zName);
  69260. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  69261. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  69262. 0==sqlite3StrICmp(pDb->zName, zName) ){
  69263. break;
  69264. }
  69265. }
  69266. }
  69267. return i;
  69268. }
  69269. /*
  69270. ** The token *pName contains the name of a database (either "main" or
  69271. ** "temp" or the name of an attached db). This routine returns the
  69272. ** index of the named database in db->aDb[], or -1 if the named db
  69273. ** does not exist.
  69274. */
  69275. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  69276. int i; /* Database number */
  69277. char *zName; /* Name we are searching for */
  69278. zName = sqlite3NameFromToken(db, pName);
  69279. i = sqlite3FindDbName(db, zName);
  69280. sqlite3DbFree(db, zName);
  69281. return i;
  69282. }
  69283. /* The table or view or trigger name is passed to this routine via tokens
  69284. ** pName1 and pName2. If the table name was fully qualified, for example:
  69285. **
  69286. ** CREATE TABLE xxx.yyy (...);
  69287. **
  69288. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  69289. ** the table name is not fully qualified, i.e.:
  69290. **
  69291. ** CREATE TABLE yyy(...);
  69292. **
  69293. ** Then pName1 is set to "yyy" and pName2 is "".
  69294. **
  69295. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  69296. ** pName2) that stores the unqualified table name. The index of the
  69297. ** database "xxx" is returned.
  69298. */
  69299. SQLITE_PRIVATE int sqlite3TwoPartName(
  69300. Parse *pParse, /* Parsing and code generating context */
  69301. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  69302. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  69303. Token **pUnqual /* Write the unqualified object name here */
  69304. ){
  69305. int iDb; /* Database holding the object */
  69306. sqlite3 *db = pParse->db;
  69307. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  69308. if( db->init.busy ) {
  69309. sqlite3ErrorMsg(pParse, "corrupt database");
  69310. pParse->nErr++;
  69311. return -1;
  69312. }
  69313. *pUnqual = pName2;
  69314. iDb = sqlite3FindDb(db, pName1);
  69315. if( iDb<0 ){
  69316. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  69317. pParse->nErr++;
  69318. return -1;
  69319. }
  69320. }else{
  69321. assert( db->init.iDb==0 || db->init.busy );
  69322. iDb = db->init.iDb;
  69323. *pUnqual = pName1;
  69324. }
  69325. return iDb;
  69326. }
  69327. /*
  69328. ** This routine is used to check if the UTF-8 string zName is a legal
  69329. ** unqualified name for a new schema object (table, index, view or
  69330. ** trigger). All names are legal except those that begin with the string
  69331. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  69332. ** is reserved for internal use.
  69333. */
  69334. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  69335. if( !pParse->db->init.busy && pParse->nested==0
  69336. && (pParse->db->flags & SQLITE_WriteSchema)==0
  69337. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  69338. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  69339. return SQLITE_ERROR;
  69340. }
  69341. return SQLITE_OK;
  69342. }
  69343. /*
  69344. ** Begin constructing a new table representation in memory. This is
  69345. ** the first of several action routines that get called in response
  69346. ** to a CREATE TABLE statement. In particular, this routine is called
  69347. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  69348. ** flag is true if the table should be stored in the auxiliary database
  69349. ** file instead of in the main database file. This is normally the case
  69350. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  69351. ** CREATE and TABLE.
  69352. **
  69353. ** The new table record is initialized and put in pParse->pNewTable.
  69354. ** As more of the CREATE TABLE statement is parsed, additional action
  69355. ** routines will be called to add more information to this record.
  69356. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  69357. ** is called to complete the construction of the new table record.
  69358. */
  69359. SQLITE_PRIVATE void sqlite3StartTable(
  69360. Parse *pParse, /* Parser context */
  69361. Token *pName1, /* First part of the name of the table or view */
  69362. Token *pName2, /* Second part of the name of the table or view */
  69363. int isTemp, /* True if this is a TEMP table */
  69364. int isView, /* True if this is a VIEW */
  69365. int isVirtual, /* True if this is a VIRTUAL table */
  69366. int noErr /* Do nothing if table already exists */
  69367. ){
  69368. Table *pTable;
  69369. char *zName = 0; /* The name of the new table */
  69370. sqlite3 *db = pParse->db;
  69371. Vdbe *v;
  69372. int iDb; /* Database number to create the table in */
  69373. Token *pName; /* Unqualified name of the table to create */
  69374. /* The table or view name to create is passed to this routine via tokens
  69375. ** pName1 and pName2. If the table name was fully qualified, for example:
  69376. **
  69377. ** CREATE TABLE xxx.yyy (...);
  69378. **
  69379. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  69380. ** the table name is not fully qualified, i.e.:
  69381. **
  69382. ** CREATE TABLE yyy(...);
  69383. **
  69384. ** Then pName1 is set to "yyy" and pName2 is "".
  69385. **
  69386. ** The call below sets the pName pointer to point at the token (pName1 or
  69387. ** pName2) that stores the unqualified table name. The variable iDb is
  69388. ** set to the index of the database that the table or view is to be
  69389. ** created in.
  69390. */
  69391. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  69392. if( iDb<0 ) return;
  69393. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  69394. /* If creating a temp table, the name may not be qualified. Unless
  69395. ** the database name is "temp" anyway. */
  69396. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  69397. return;
  69398. }
  69399. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  69400. pParse->sNameToken = *pName;
  69401. zName = sqlite3NameFromToken(db, pName);
  69402. if( zName==0 ) return;
  69403. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  69404. goto begin_table_error;
  69405. }
  69406. if( db->init.iDb==1 ) isTemp = 1;
  69407. #ifndef SQLITE_OMIT_AUTHORIZATION
  69408. assert( (isTemp & 1)==isTemp );
  69409. {
  69410. int code;
  69411. char *zDb = db->aDb[iDb].zName;
  69412. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  69413. goto begin_table_error;
  69414. }
  69415. if( isView ){
  69416. if( !OMIT_TEMPDB && isTemp ){
  69417. code = SQLITE_CREATE_TEMP_VIEW;
  69418. }else{
  69419. code = SQLITE_CREATE_VIEW;
  69420. }
  69421. }else{
  69422. if( !OMIT_TEMPDB && isTemp ){
  69423. code = SQLITE_CREATE_TEMP_TABLE;
  69424. }else{
  69425. code = SQLITE_CREATE_TABLE;
  69426. }
  69427. }
  69428. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  69429. goto begin_table_error;
  69430. }
  69431. }
  69432. #endif
  69433. /* Make sure the new table name does not collide with an existing
  69434. ** index or table name in the same database. Issue an error message if
  69435. ** it does. The exception is if the statement being parsed was passed
  69436. ** to an sqlite3_declare_vtab() call. In that case only the column names
  69437. ** and types will be used, so there is no need to test for namespace
  69438. ** collisions.
  69439. */
  69440. if( !IN_DECLARE_VTAB ){
  69441. char *zDb = db->aDb[iDb].zName;
  69442. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  69443. goto begin_table_error;
  69444. }
  69445. pTable = sqlite3FindTable(db, zName, zDb);
  69446. if( pTable ){
  69447. if( !noErr ){
  69448. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  69449. }else{
  69450. assert( !db->init.busy );
  69451. sqlite3CodeVerifySchema(pParse, iDb);
  69452. }
  69453. goto begin_table_error;
  69454. }
  69455. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  69456. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  69457. goto begin_table_error;
  69458. }
  69459. }
  69460. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  69461. if( pTable==0 ){
  69462. db->mallocFailed = 1;
  69463. pParse->rc = SQLITE_NOMEM;
  69464. pParse->nErr++;
  69465. goto begin_table_error;
  69466. }
  69467. pTable->zName = zName;
  69468. pTable->iPKey = -1;
  69469. pTable->pSchema = db->aDb[iDb].pSchema;
  69470. pTable->nRef = 1;
  69471. pTable->nRowEst = 1048576;
  69472. assert( pParse->pNewTable==0 );
  69473. pParse->pNewTable = pTable;
  69474. /* If this is the magic sqlite_sequence table used by autoincrement,
  69475. ** then record a pointer to this table in the main database structure
  69476. ** so that INSERT can find the table easily.
  69477. */
  69478. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69479. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  69480. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69481. pTable->pSchema->pSeqTab = pTable;
  69482. }
  69483. #endif
  69484. /* Begin generating the code that will insert the table record into
  69485. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  69486. ** and allocate the record number for the table entry now. Before any
  69487. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  69488. ** indices to be created and the table record must come before the
  69489. ** indices. Hence, the record number for the table must be allocated
  69490. ** now.
  69491. */
  69492. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  69493. int j1;
  69494. int fileFormat;
  69495. int reg1, reg2, reg3;
  69496. sqlite3BeginWriteOperation(pParse, 0, iDb);
  69497. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69498. if( isVirtual ){
  69499. sqlite3VdbeAddOp0(v, OP_VBegin);
  69500. }
  69501. #endif
  69502. /* If the file format and encoding in the database have not been set,
  69503. ** set them now.
  69504. */
  69505. reg1 = pParse->regRowid = ++pParse->nMem;
  69506. reg2 = pParse->regRoot = ++pParse->nMem;
  69507. reg3 = ++pParse->nMem;
  69508. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  69509. sqlite3VdbeUsesBtree(v, iDb);
  69510. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  69511. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  69512. 1 : SQLITE_MAX_FILE_FORMAT;
  69513. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  69514. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  69515. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  69516. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  69517. sqlite3VdbeJumpHere(v, j1);
  69518. /* This just creates a place-holder record in the sqlite_master table.
  69519. ** The record created does not contain anything yet. It will be replaced
  69520. ** by the real entry in code generated at sqlite3EndTable().
  69521. **
  69522. ** The rowid for the new entry is left in register pParse->regRowid.
  69523. ** The root page number of the new table is left in reg pParse->regRoot.
  69524. ** The rowid and root page number values are needed by the code that
  69525. ** sqlite3EndTable will generate.
  69526. */
  69527. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  69528. if( isView || isVirtual ){
  69529. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  69530. }else
  69531. #endif
  69532. {
  69533. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  69534. }
  69535. sqlite3OpenMasterTable(pParse, iDb);
  69536. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  69537. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  69538. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  69539. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  69540. sqlite3VdbeAddOp0(v, OP_Close);
  69541. }
  69542. /* Normal (non-error) return. */
  69543. return;
  69544. /* If an error occurs, we jump here */
  69545. begin_table_error:
  69546. sqlite3DbFree(db, zName);
  69547. return;
  69548. }
  69549. /*
  69550. ** This macro is used to compare two strings in a case-insensitive manner.
  69551. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  69552. ** produces larger code.
  69553. **
  69554. ** WARNING: This macro is not compatible with the strcmp() family. It
  69555. ** returns true if the two strings are equal, otherwise false.
  69556. */
  69557. #define STRICMP(x, y) (\
  69558. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  69559. sqlite3UpperToLower[*(unsigned char *)(y)] \
  69560. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  69561. /*
  69562. ** Add a new column to the table currently being constructed.
  69563. **
  69564. ** The parser calls this routine once for each column declaration
  69565. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  69566. ** first to get things going. Then this routine is called for each
  69567. ** column.
  69568. */
  69569. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  69570. Table *p;
  69571. int i;
  69572. char *z;
  69573. Column *pCol;
  69574. sqlite3 *db = pParse->db;
  69575. if( (p = pParse->pNewTable)==0 ) return;
  69576. #if SQLITE_MAX_COLUMN
  69577. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  69578. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  69579. return;
  69580. }
  69581. #endif
  69582. z = sqlite3NameFromToken(db, pName);
  69583. if( z==0 ) return;
  69584. for(i=0; i<p->nCol; i++){
  69585. if( STRICMP(z, p->aCol[i].zName) ){
  69586. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  69587. sqlite3DbFree(db, z);
  69588. return;
  69589. }
  69590. }
  69591. if( (p->nCol & 0x7)==0 ){
  69592. Column *aNew;
  69593. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  69594. if( aNew==0 ){
  69595. sqlite3DbFree(db, z);
  69596. return;
  69597. }
  69598. p->aCol = aNew;
  69599. }
  69600. pCol = &p->aCol[p->nCol];
  69601. memset(pCol, 0, sizeof(p->aCol[0]));
  69602. pCol->zName = z;
  69603. /* If there is no type specified, columns have the default affinity
  69604. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  69605. ** be called next to set pCol->affinity correctly.
  69606. */
  69607. pCol->affinity = SQLITE_AFF_NONE;
  69608. pCol->szEst = 1;
  69609. p->nCol++;
  69610. }
  69611. /*
  69612. ** This routine is called by the parser while in the middle of
  69613. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  69614. ** been seen on a column. This routine sets the notNull flag on
  69615. ** the column currently under construction.
  69616. */
  69617. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  69618. Table *p;
  69619. p = pParse->pNewTable;
  69620. if( p==0 || NEVER(p->nCol<1) ) return;
  69621. p->aCol[p->nCol-1].notNull = (u8)onError;
  69622. }
  69623. /*
  69624. ** Scan the column type name zType (length nType) and return the
  69625. ** associated affinity type.
  69626. **
  69627. ** This routine does a case-independent search of zType for the
  69628. ** substrings in the following table. If one of the substrings is
  69629. ** found, the corresponding affinity is returned. If zType contains
  69630. ** more than one of the substrings, entries toward the top of
  69631. ** the table take priority. For example, if zType is 'BLOBINT',
  69632. ** SQLITE_AFF_INTEGER is returned.
  69633. **
  69634. ** Substring | Affinity
  69635. ** --------------------------------
  69636. ** 'INT' | SQLITE_AFF_INTEGER
  69637. ** 'CHAR' | SQLITE_AFF_TEXT
  69638. ** 'CLOB' | SQLITE_AFF_TEXT
  69639. ** 'TEXT' | SQLITE_AFF_TEXT
  69640. ** 'BLOB' | SQLITE_AFF_NONE
  69641. ** 'REAL' | SQLITE_AFF_REAL
  69642. ** 'FLOA' | SQLITE_AFF_REAL
  69643. ** 'DOUB' | SQLITE_AFF_REAL
  69644. **
  69645. ** If none of the substrings in the above table are found,
  69646. ** SQLITE_AFF_NUMERIC is returned.
  69647. */
  69648. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  69649. u32 h = 0;
  69650. char aff = SQLITE_AFF_NUMERIC;
  69651. const char *zChar = 0;
  69652. if( zIn==0 ) return aff;
  69653. while( zIn[0] ){
  69654. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  69655. zIn++;
  69656. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  69657. aff = SQLITE_AFF_TEXT;
  69658. zChar = zIn;
  69659. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  69660. aff = SQLITE_AFF_TEXT;
  69661. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  69662. aff = SQLITE_AFF_TEXT;
  69663. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  69664. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  69665. aff = SQLITE_AFF_NONE;
  69666. if( zIn[0]=='(' ) zChar = zIn;
  69667. #ifndef SQLITE_OMIT_FLOATING_POINT
  69668. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  69669. && aff==SQLITE_AFF_NUMERIC ){
  69670. aff = SQLITE_AFF_REAL;
  69671. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  69672. && aff==SQLITE_AFF_NUMERIC ){
  69673. aff = SQLITE_AFF_REAL;
  69674. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  69675. && aff==SQLITE_AFF_NUMERIC ){
  69676. aff = SQLITE_AFF_REAL;
  69677. #endif
  69678. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  69679. aff = SQLITE_AFF_INTEGER;
  69680. break;
  69681. }
  69682. }
  69683. /* If pszEst is not NULL, store an estimate of the field size. The
  69684. ** estimate is scaled so that the size of an integer is 1. */
  69685. if( pszEst ){
  69686. *pszEst = 1; /* default size is approx 4 bytes */
  69687. if( aff<=SQLITE_AFF_NONE ){
  69688. if( zChar ){
  69689. while( zChar[0] ){
  69690. if( sqlite3Isdigit(zChar[0]) ){
  69691. int v = 0;
  69692. sqlite3GetInt32(zChar, &v);
  69693. v = v/4 + 1;
  69694. if( v>255 ) v = 255;
  69695. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  69696. break;
  69697. }
  69698. zChar++;
  69699. }
  69700. }else{
  69701. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  69702. }
  69703. }
  69704. }
  69705. return aff;
  69706. }
  69707. /*
  69708. ** This routine is called by the parser while in the middle of
  69709. ** parsing a CREATE TABLE statement. The pFirst token is the first
  69710. ** token in the sequence of tokens that describe the type of the
  69711. ** column currently under construction. pLast is the last token
  69712. ** in the sequence. Use this information to construct a string
  69713. ** that contains the typename of the column and store that string
  69714. ** in zType.
  69715. */
  69716. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  69717. Table *p;
  69718. Column *pCol;
  69719. p = pParse->pNewTable;
  69720. if( p==0 || NEVER(p->nCol<1) ) return;
  69721. pCol = &p->aCol[p->nCol-1];
  69722. assert( pCol->zType==0 );
  69723. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  69724. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  69725. }
  69726. /*
  69727. ** The expression is the default value for the most recently added column
  69728. ** of the table currently under construction.
  69729. **
  69730. ** Default value expressions must be constant. Raise an exception if this
  69731. ** is not the case.
  69732. **
  69733. ** This routine is called by the parser while in the middle of
  69734. ** parsing a CREATE TABLE statement.
  69735. */
  69736. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  69737. Table *p;
  69738. Column *pCol;
  69739. sqlite3 *db = pParse->db;
  69740. p = pParse->pNewTable;
  69741. if( p!=0 ){
  69742. pCol = &(p->aCol[p->nCol-1]);
  69743. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  69744. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  69745. pCol->zName);
  69746. }else{
  69747. /* A copy of pExpr is used instead of the original, as pExpr contains
  69748. ** tokens that point to volatile memory. The 'span' of the expression
  69749. ** is required by pragma table_info.
  69750. */
  69751. sqlite3ExprDelete(db, pCol->pDflt);
  69752. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  69753. sqlite3DbFree(db, pCol->zDflt);
  69754. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  69755. (int)(pSpan->zEnd - pSpan->zStart));
  69756. }
  69757. }
  69758. sqlite3ExprDelete(db, pSpan->pExpr);
  69759. }
  69760. /*
  69761. ** Designate the PRIMARY KEY for the table. pList is a list of names
  69762. ** of columns that form the primary key. If pList is NULL, then the
  69763. ** most recently added column of the table is the primary key.
  69764. **
  69765. ** A table can have at most one primary key. If the table already has
  69766. ** a primary key (and this is the second primary key) then create an
  69767. ** error.
  69768. **
  69769. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  69770. ** then we will try to use that column as the rowid. Set the Table.iPKey
  69771. ** field of the table under construction to be the index of the
  69772. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  69773. ** no INTEGER PRIMARY KEY.
  69774. **
  69775. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  69776. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  69777. */
  69778. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  69779. Parse *pParse, /* Parsing context */
  69780. ExprList *pList, /* List of field names to be indexed */
  69781. int onError, /* What to do with a uniqueness conflict */
  69782. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  69783. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  69784. ){
  69785. Table *pTab = pParse->pNewTable;
  69786. char *zType = 0;
  69787. int iCol = -1, i;
  69788. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  69789. if( pTab->tabFlags & TF_HasPrimaryKey ){
  69790. sqlite3ErrorMsg(pParse,
  69791. "table \"%s\" has more than one primary key", pTab->zName);
  69792. goto primary_key_exit;
  69793. }
  69794. pTab->tabFlags |= TF_HasPrimaryKey;
  69795. if( pList==0 ){
  69796. iCol = pTab->nCol - 1;
  69797. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  69798. }else{
  69799. for(i=0; i<pList->nExpr; i++){
  69800. for(iCol=0; iCol<pTab->nCol; iCol++){
  69801. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  69802. break;
  69803. }
  69804. }
  69805. if( iCol<pTab->nCol ){
  69806. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  69807. }
  69808. }
  69809. if( pList->nExpr>1 ) iCol = -1;
  69810. }
  69811. if( iCol>=0 && iCol<pTab->nCol ){
  69812. zType = pTab->aCol[iCol].zType;
  69813. }
  69814. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  69815. && sortOrder==SQLITE_SO_ASC ){
  69816. pTab->iPKey = iCol;
  69817. pTab->keyConf = (u8)onError;
  69818. assert( autoInc==0 || autoInc==1 );
  69819. pTab->tabFlags |= autoInc*TF_Autoincrement;
  69820. }else if( autoInc ){
  69821. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69822. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  69823. "INTEGER PRIMARY KEY");
  69824. #endif
  69825. }else{
  69826. Index *p;
  69827. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  69828. 0, sortOrder, 0);
  69829. if( p ){
  69830. p->autoIndex = 2;
  69831. }
  69832. pList = 0;
  69833. }
  69834. primary_key_exit:
  69835. sqlite3ExprListDelete(pParse->db, pList);
  69836. return;
  69837. }
  69838. /*
  69839. ** Add a new CHECK constraint to the table currently under construction.
  69840. */
  69841. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  69842. Parse *pParse, /* Parsing context */
  69843. Expr *pCheckExpr /* The check expression */
  69844. ){
  69845. #ifndef SQLITE_OMIT_CHECK
  69846. Table *pTab = pParse->pNewTable;
  69847. if( pTab && !IN_DECLARE_VTAB ){
  69848. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  69849. if( pParse->constraintName.n ){
  69850. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  69851. }
  69852. }else
  69853. #endif
  69854. {
  69855. sqlite3ExprDelete(pParse->db, pCheckExpr);
  69856. }
  69857. }
  69858. /*
  69859. ** Set the collation function of the most recently parsed table column
  69860. ** to the CollSeq given.
  69861. */
  69862. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  69863. Table *p;
  69864. int i;
  69865. char *zColl; /* Dequoted name of collation sequence */
  69866. sqlite3 *db;
  69867. if( (p = pParse->pNewTable)==0 ) return;
  69868. i = p->nCol-1;
  69869. db = pParse->db;
  69870. zColl = sqlite3NameFromToken(db, pToken);
  69871. if( !zColl ) return;
  69872. if( sqlite3LocateCollSeq(pParse, zColl) ){
  69873. Index *pIdx;
  69874. sqlite3DbFree(db, p->aCol[i].zColl);
  69875. p->aCol[i].zColl = zColl;
  69876. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  69877. ** then an index may have been created on this column before the
  69878. ** collation type was added. Correct this if it is the case.
  69879. */
  69880. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  69881. assert( pIdx->nColumn==1 );
  69882. if( pIdx->aiColumn[0]==i ){
  69883. pIdx->azColl[0] = p->aCol[i].zColl;
  69884. }
  69885. }
  69886. }else{
  69887. sqlite3DbFree(db, zColl);
  69888. }
  69889. }
  69890. /*
  69891. ** This function returns the collation sequence for database native text
  69892. ** encoding identified by the string zName, length nName.
  69893. **
  69894. ** If the requested collation sequence is not available, or not available
  69895. ** in the database native encoding, the collation factory is invoked to
  69896. ** request it. If the collation factory does not supply such a sequence,
  69897. ** and the sequence is available in another text encoding, then that is
  69898. ** returned instead.
  69899. **
  69900. ** If no versions of the requested collations sequence are available, or
  69901. ** another error occurs, NULL is returned and an error message written into
  69902. ** pParse.
  69903. **
  69904. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  69905. ** invokes the collation factory if the named collation cannot be found
  69906. ** and generates an error message.
  69907. **
  69908. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  69909. */
  69910. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  69911. sqlite3 *db = pParse->db;
  69912. u8 enc = ENC(db);
  69913. u8 initbusy = db->init.busy;
  69914. CollSeq *pColl;
  69915. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  69916. if( !initbusy && (!pColl || !pColl->xCmp) ){
  69917. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  69918. }
  69919. return pColl;
  69920. }
  69921. /*
  69922. ** Generate code that will increment the schema cookie.
  69923. **
  69924. ** The schema cookie is used to determine when the schema for the
  69925. ** database changes. After each schema change, the cookie value
  69926. ** changes. When a process first reads the schema it records the
  69927. ** cookie. Thereafter, whenever it goes to access the database,
  69928. ** it checks the cookie to make sure the schema has not changed
  69929. ** since it was last read.
  69930. **
  69931. ** This plan is not completely bullet-proof. It is possible for
  69932. ** the schema to change multiple times and for the cookie to be
  69933. ** set back to prior value. But schema changes are infrequent
  69934. ** and the probability of hitting the same cookie value is only
  69935. ** 1 chance in 2^32. So we're safe enough.
  69936. */
  69937. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  69938. int r1 = sqlite3GetTempReg(pParse);
  69939. sqlite3 *db = pParse->db;
  69940. Vdbe *v = pParse->pVdbe;
  69941. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69942. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  69943. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  69944. sqlite3ReleaseTempReg(pParse, r1);
  69945. }
  69946. /*
  69947. ** Measure the number of characters needed to output the given
  69948. ** identifier. The number returned includes any quotes used
  69949. ** but does not include the null terminator.
  69950. **
  69951. ** The estimate is conservative. It might be larger that what is
  69952. ** really needed.
  69953. */
  69954. static int identLength(const char *z){
  69955. int n;
  69956. for(n=0; *z; n++, z++){
  69957. if( *z=='"' ){ n++; }
  69958. }
  69959. return n + 2;
  69960. }
  69961. /*
  69962. ** The first parameter is a pointer to an output buffer. The second
  69963. ** parameter is a pointer to an integer that contains the offset at
  69964. ** which to write into the output buffer. This function copies the
  69965. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  69966. ** to the specified offset in the buffer and updates *pIdx to refer
  69967. ** to the first byte after the last byte written before returning.
  69968. **
  69969. ** If the string zSignedIdent consists entirely of alpha-numeric
  69970. ** characters, does not begin with a digit and is not an SQL keyword,
  69971. ** then it is copied to the output buffer exactly as it is. Otherwise,
  69972. ** it is quoted using double-quotes.
  69973. */
  69974. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  69975. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  69976. int i, j, needQuote;
  69977. i = *pIdx;
  69978. for(j=0; zIdent[j]; j++){
  69979. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  69980. }
  69981. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  69982. if( !needQuote ){
  69983. needQuote = zIdent[j];
  69984. }
  69985. if( needQuote ) z[i++] = '"';
  69986. for(j=0; zIdent[j]; j++){
  69987. z[i++] = zIdent[j];
  69988. if( zIdent[j]=='"' ) z[i++] = '"';
  69989. }
  69990. if( needQuote ) z[i++] = '"';
  69991. z[i] = 0;
  69992. *pIdx = i;
  69993. }
  69994. /*
  69995. ** Generate a CREATE TABLE statement appropriate for the given
  69996. ** table. Memory to hold the text of the statement is obtained
  69997. ** from sqliteMalloc() and must be freed by the calling function.
  69998. */
  69999. static char *createTableStmt(sqlite3 *db, Table *p){
  70000. int i, k, n;
  70001. char *zStmt;
  70002. char *zSep, *zSep2, *zEnd;
  70003. Column *pCol;
  70004. n = 0;
  70005. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  70006. n += identLength(pCol->zName) + 5;
  70007. }
  70008. n += identLength(p->zName);
  70009. if( n<50 ){
  70010. zSep = "";
  70011. zSep2 = ",";
  70012. zEnd = ")";
  70013. }else{
  70014. zSep = "\n ";
  70015. zSep2 = ",\n ";
  70016. zEnd = "\n)";
  70017. }
  70018. n += 35 + 6*p->nCol;
  70019. zStmt = sqlite3DbMallocRaw(0, n);
  70020. if( zStmt==0 ){
  70021. db->mallocFailed = 1;
  70022. return 0;
  70023. }
  70024. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  70025. k = sqlite3Strlen30(zStmt);
  70026. identPut(zStmt, &k, p->zName);
  70027. zStmt[k++] = '(';
  70028. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  70029. static const char * const azType[] = {
  70030. /* SQLITE_AFF_TEXT */ " TEXT",
  70031. /* SQLITE_AFF_NONE */ "",
  70032. /* SQLITE_AFF_NUMERIC */ " NUM",
  70033. /* SQLITE_AFF_INTEGER */ " INT",
  70034. /* SQLITE_AFF_REAL */ " REAL"
  70035. };
  70036. int len;
  70037. const char *zType;
  70038. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  70039. k += sqlite3Strlen30(&zStmt[k]);
  70040. zSep = zSep2;
  70041. identPut(zStmt, &k, pCol->zName);
  70042. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  70043. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  70044. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  70045. testcase( pCol->affinity==SQLITE_AFF_NONE );
  70046. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  70047. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  70048. testcase( pCol->affinity==SQLITE_AFF_REAL );
  70049. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  70050. len = sqlite3Strlen30(zType);
  70051. assert( pCol->affinity==SQLITE_AFF_NONE
  70052. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  70053. memcpy(&zStmt[k], zType, len);
  70054. k += len;
  70055. assert( k<=n );
  70056. }
  70057. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  70058. return zStmt;
  70059. }
  70060. /*
  70061. ** Estimate the total row width for a table.
  70062. */
  70063. static void estimateTableWidth(Table *pTab){
  70064. unsigned wTable = 0;
  70065. const Column *pTabCol;
  70066. int i;
  70067. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  70068. wTable += pTabCol->szEst;
  70069. }
  70070. if( pTab->iPKey<0 ) wTable++;
  70071. pTab->szTabRow = sqlite3LogEst(wTable*4);
  70072. }
  70073. /*
  70074. ** Estimate the average size of a row for an index.
  70075. */
  70076. static void estimateIndexWidth(Index *pIdx){
  70077. unsigned wIndex = 1;
  70078. int i;
  70079. const Column *aCol = pIdx->pTable->aCol;
  70080. for(i=0; i<pIdx->nColumn; i++){
  70081. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  70082. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  70083. }
  70084. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  70085. }
  70086. /*
  70087. ** This routine is called to report the final ")" that terminates
  70088. ** a CREATE TABLE statement.
  70089. **
  70090. ** The table structure that other action routines have been building
  70091. ** is added to the internal hash tables, assuming no errors have
  70092. ** occurred.
  70093. **
  70094. ** An entry for the table is made in the master table on disk, unless
  70095. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  70096. ** it means we are reading the sqlite_master table because we just
  70097. ** connected to the database or because the sqlite_master table has
  70098. ** recently changed, so the entry for this table already exists in
  70099. ** the sqlite_master table. We do not want to create it again.
  70100. **
  70101. ** If the pSelect argument is not NULL, it means that this routine
  70102. ** was called to create a table generated from a
  70103. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  70104. ** the new table will match the result set of the SELECT.
  70105. */
  70106. SQLITE_PRIVATE void sqlite3EndTable(
  70107. Parse *pParse, /* Parse context */
  70108. Token *pCons, /* The ',' token after the last column defn. */
  70109. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  70110. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  70111. ){
  70112. Table *p; /* The new table */
  70113. sqlite3 *db = pParse->db; /* The database connection */
  70114. int iDb; /* Database in which the table lives */
  70115. Index *pIdx; /* An implied index of the table */
  70116. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  70117. return;
  70118. }
  70119. p = pParse->pNewTable;
  70120. if( p==0 ) return;
  70121. assert( !db->init.busy || !pSelect );
  70122. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  70123. #ifndef SQLITE_OMIT_CHECK
  70124. /* Resolve names in all CHECK constraint expressions.
  70125. */
  70126. if( p->pCheck ){
  70127. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  70128. }
  70129. #endif /* !defined(SQLITE_OMIT_CHECK) */
  70130. /* Estimate the average row size for the table and for all implied indices */
  70131. estimateTableWidth(p);
  70132. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  70133. estimateIndexWidth(pIdx);
  70134. }
  70135. /* If the db->init.busy is 1 it means we are reading the SQL off the
  70136. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  70137. ** So do not write to the disk again. Extract the root page number
  70138. ** for the table from the db->init.newTnum field. (The page number
  70139. ** should have been put there by the sqliteOpenCb routine.)
  70140. */
  70141. if( db->init.busy ){
  70142. p->tnum = db->init.newTnum;
  70143. }
  70144. /* If not initializing, then create a record for the new table
  70145. ** in the SQLITE_MASTER table of the database.
  70146. **
  70147. ** If this is a TEMPORARY table, write the entry into the auxiliary
  70148. ** file instead of into the main database file.
  70149. */
  70150. if( !db->init.busy ){
  70151. int n;
  70152. Vdbe *v;
  70153. char *zType; /* "view" or "table" */
  70154. char *zType2; /* "VIEW" or "TABLE" */
  70155. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  70156. v = sqlite3GetVdbe(pParse);
  70157. if( NEVER(v==0) ) return;
  70158. sqlite3VdbeAddOp1(v, OP_Close, 0);
  70159. /*
  70160. ** Initialize zType for the new view or table.
  70161. */
  70162. if( p->pSelect==0 ){
  70163. /* A regular table */
  70164. zType = "table";
  70165. zType2 = "TABLE";
  70166. #ifndef SQLITE_OMIT_VIEW
  70167. }else{
  70168. /* A view */
  70169. zType = "view";
  70170. zType2 = "VIEW";
  70171. #endif
  70172. }
  70173. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  70174. ** statement to populate the new table. The root-page number for the
  70175. ** new table is in register pParse->regRoot.
  70176. **
  70177. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  70178. ** suitable state to query for the column names and types to be used
  70179. ** by the new table.
  70180. **
  70181. ** A shared-cache write-lock is not required to write to the new table,
  70182. ** as a schema-lock must have already been obtained to create it. Since
  70183. ** a schema-lock excludes all other database users, the write-lock would
  70184. ** be redundant.
  70185. */
  70186. if( pSelect ){
  70187. SelectDest dest;
  70188. Table *pSelTab;
  70189. assert(pParse->nTab==1);
  70190. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  70191. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  70192. pParse->nTab = 2;
  70193. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  70194. sqlite3Select(pParse, pSelect, &dest);
  70195. sqlite3VdbeAddOp1(v, OP_Close, 1);
  70196. if( pParse->nErr==0 ){
  70197. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  70198. if( pSelTab==0 ) return;
  70199. assert( p->aCol==0 );
  70200. p->nCol = pSelTab->nCol;
  70201. p->aCol = pSelTab->aCol;
  70202. pSelTab->nCol = 0;
  70203. pSelTab->aCol = 0;
  70204. sqlite3DeleteTable(db, pSelTab);
  70205. }
  70206. }
  70207. /* Compute the complete text of the CREATE statement */
  70208. if( pSelect ){
  70209. zStmt = createTableStmt(db, p);
  70210. }else{
  70211. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  70212. zStmt = sqlite3MPrintf(db,
  70213. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  70214. );
  70215. }
  70216. /* A slot for the record has already been allocated in the
  70217. ** SQLITE_MASTER table. We just need to update that slot with all
  70218. ** the information we've collected.
  70219. */
  70220. sqlite3NestedParse(pParse,
  70221. "UPDATE %Q.%s "
  70222. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  70223. "WHERE rowid=#%d",
  70224. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  70225. zType,
  70226. p->zName,
  70227. p->zName,
  70228. pParse->regRoot,
  70229. zStmt,
  70230. pParse->regRowid
  70231. );
  70232. sqlite3DbFree(db, zStmt);
  70233. sqlite3ChangeCookie(pParse, iDb);
  70234. #ifndef SQLITE_OMIT_AUTOINCREMENT
  70235. /* Check to see if we need to create an sqlite_sequence table for
  70236. ** keeping track of autoincrement keys.
  70237. */
  70238. if( p->tabFlags & TF_Autoincrement ){
  70239. Db *pDb = &db->aDb[iDb];
  70240. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70241. if( pDb->pSchema->pSeqTab==0 ){
  70242. sqlite3NestedParse(pParse,
  70243. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  70244. pDb->zName
  70245. );
  70246. }
  70247. }
  70248. #endif
  70249. /* Reparse everything to update our internal data structures */
  70250. sqlite3VdbeAddParseSchemaOp(v, iDb,
  70251. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  70252. }
  70253. /* Add the table to the in-memory representation of the database.
  70254. */
  70255. if( db->init.busy ){
  70256. Table *pOld;
  70257. Schema *pSchema = p->pSchema;
  70258. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70259. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  70260. sqlite3Strlen30(p->zName),p);
  70261. if( pOld ){
  70262. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  70263. db->mallocFailed = 1;
  70264. return;
  70265. }
  70266. pParse->pNewTable = 0;
  70267. db->flags |= SQLITE_InternChanges;
  70268. #ifndef SQLITE_OMIT_ALTERTABLE
  70269. if( !p->pSelect ){
  70270. const char *zName = (const char *)pParse->sNameToken.z;
  70271. int nName;
  70272. assert( !pSelect && pCons && pEnd );
  70273. if( pCons->z==0 ){
  70274. pCons = pEnd;
  70275. }
  70276. nName = (int)((const char *)pCons->z - zName);
  70277. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  70278. }
  70279. #endif
  70280. }
  70281. }
  70282. #ifndef SQLITE_OMIT_VIEW
  70283. /*
  70284. ** The parser calls this routine in order to create a new VIEW
  70285. */
  70286. SQLITE_PRIVATE void sqlite3CreateView(
  70287. Parse *pParse, /* The parsing context */
  70288. Token *pBegin, /* The CREATE token that begins the statement */
  70289. Token *pName1, /* The token that holds the name of the view */
  70290. Token *pName2, /* The token that holds the name of the view */
  70291. Select *pSelect, /* A SELECT statement that will become the new view */
  70292. int isTemp, /* TRUE for a TEMPORARY view */
  70293. int noErr /* Suppress error messages if VIEW already exists */
  70294. ){
  70295. Table *p;
  70296. int n;
  70297. const char *z;
  70298. Token sEnd;
  70299. DbFixer sFix;
  70300. Token *pName = 0;
  70301. int iDb;
  70302. sqlite3 *db = pParse->db;
  70303. if( pParse->nVar>0 ){
  70304. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  70305. sqlite3SelectDelete(db, pSelect);
  70306. return;
  70307. }
  70308. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  70309. p = pParse->pNewTable;
  70310. if( p==0 || pParse->nErr ){
  70311. sqlite3SelectDelete(db, pSelect);
  70312. return;
  70313. }
  70314. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  70315. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  70316. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  70317. if( sqlite3FixSelect(&sFix, pSelect) ){
  70318. sqlite3SelectDelete(db, pSelect);
  70319. return;
  70320. }
  70321. /* Make a copy of the entire SELECT statement that defines the view.
  70322. ** This will force all the Expr.token.z values to be dynamically
  70323. ** allocated rather than point to the input string - which means that
  70324. ** they will persist after the current sqlite3_exec() call returns.
  70325. */
  70326. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  70327. sqlite3SelectDelete(db, pSelect);
  70328. if( db->mallocFailed ){
  70329. return;
  70330. }
  70331. if( !db->init.busy ){
  70332. sqlite3ViewGetColumnNames(pParse, p);
  70333. }
  70334. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  70335. ** the end.
  70336. */
  70337. sEnd = pParse->sLastToken;
  70338. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  70339. sEnd.z += sEnd.n;
  70340. }
  70341. sEnd.n = 0;
  70342. n = (int)(sEnd.z - pBegin->z);
  70343. z = pBegin->z;
  70344. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  70345. sEnd.z = &z[n-1];
  70346. sEnd.n = 1;
  70347. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  70348. sqlite3EndTable(pParse, 0, &sEnd, 0);
  70349. return;
  70350. }
  70351. #endif /* SQLITE_OMIT_VIEW */
  70352. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  70353. /*
  70354. ** The Table structure pTable is really a VIEW. Fill in the names of
  70355. ** the columns of the view in the pTable structure. Return the number
  70356. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  70357. */
  70358. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  70359. Table *pSelTab; /* A fake table from which we get the result set */
  70360. Select *pSel; /* Copy of the SELECT that implements the view */
  70361. int nErr = 0; /* Number of errors encountered */
  70362. int n; /* Temporarily holds the number of cursors assigned */
  70363. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  70364. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  70365. assert( pTable );
  70366. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70367. if( sqlite3VtabCallConnect(pParse, pTable) ){
  70368. return SQLITE_ERROR;
  70369. }
  70370. if( IsVirtual(pTable) ) return 0;
  70371. #endif
  70372. #ifndef SQLITE_OMIT_VIEW
  70373. /* A positive nCol means the columns names for this view are
  70374. ** already known.
  70375. */
  70376. if( pTable->nCol>0 ) return 0;
  70377. /* A negative nCol is a special marker meaning that we are currently
  70378. ** trying to compute the column names. If we enter this routine with
  70379. ** a negative nCol, it means two or more views form a loop, like this:
  70380. **
  70381. ** CREATE VIEW one AS SELECT * FROM two;
  70382. ** CREATE VIEW two AS SELECT * FROM one;
  70383. **
  70384. ** Actually, the error above is now caught prior to reaching this point.
  70385. ** But the following test is still important as it does come up
  70386. ** in the following:
  70387. **
  70388. ** CREATE TABLE main.ex1(a);
  70389. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  70390. ** SELECT * FROM temp.ex1;
  70391. */
  70392. if( pTable->nCol<0 ){
  70393. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  70394. return 1;
  70395. }
  70396. assert( pTable->nCol>=0 );
  70397. /* If we get this far, it means we need to compute the table names.
  70398. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  70399. ** "*" elements in the results set of the view and will assign cursors
  70400. ** to the elements of the FROM clause. But we do not want these changes
  70401. ** to be permanent. So the computation is done on a copy of the SELECT
  70402. ** statement that defines the view.
  70403. */
  70404. assert( pTable->pSelect );
  70405. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  70406. if( pSel ){
  70407. u8 enableLookaside = db->lookaside.bEnabled;
  70408. n = pParse->nTab;
  70409. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  70410. pTable->nCol = -1;
  70411. db->lookaside.bEnabled = 0;
  70412. #ifndef SQLITE_OMIT_AUTHORIZATION
  70413. xAuth = db->xAuth;
  70414. db->xAuth = 0;
  70415. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  70416. db->xAuth = xAuth;
  70417. #else
  70418. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  70419. #endif
  70420. db->lookaside.bEnabled = enableLookaside;
  70421. pParse->nTab = n;
  70422. if( pSelTab ){
  70423. assert( pTable->aCol==0 );
  70424. pTable->nCol = pSelTab->nCol;
  70425. pTable->aCol = pSelTab->aCol;
  70426. pSelTab->nCol = 0;
  70427. pSelTab->aCol = 0;
  70428. sqlite3DeleteTable(db, pSelTab);
  70429. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  70430. pTable->pSchema->flags |= DB_UnresetViews;
  70431. }else{
  70432. pTable->nCol = 0;
  70433. nErr++;
  70434. }
  70435. sqlite3SelectDelete(db, pSel);
  70436. } else {
  70437. nErr++;
  70438. }
  70439. #endif /* SQLITE_OMIT_VIEW */
  70440. return nErr;
  70441. }
  70442. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  70443. #ifndef SQLITE_OMIT_VIEW
  70444. /*
  70445. ** Clear the column names from every VIEW in database idx.
  70446. */
  70447. static void sqliteViewResetAll(sqlite3 *db, int idx){
  70448. HashElem *i;
  70449. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  70450. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  70451. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  70452. Table *pTab = sqliteHashData(i);
  70453. if( pTab->pSelect ){
  70454. sqliteDeleteColumnNames(db, pTab);
  70455. pTab->aCol = 0;
  70456. pTab->nCol = 0;
  70457. }
  70458. }
  70459. DbClearProperty(db, idx, DB_UnresetViews);
  70460. }
  70461. #else
  70462. # define sqliteViewResetAll(A,B)
  70463. #endif /* SQLITE_OMIT_VIEW */
  70464. /*
  70465. ** This function is called by the VDBE to adjust the internal schema
  70466. ** used by SQLite when the btree layer moves a table root page. The
  70467. ** root-page of a table or index in database iDb has changed from iFrom
  70468. ** to iTo.
  70469. **
  70470. ** Ticket #1728: The symbol table might still contain information
  70471. ** on tables and/or indices that are the process of being deleted.
  70472. ** If you are unlucky, one of those deleted indices or tables might
  70473. ** have the same rootpage number as the real table or index that is
  70474. ** being moved. So we cannot stop searching after the first match
  70475. ** because the first match might be for one of the deleted indices
  70476. ** or tables and not the table/index that is actually being moved.
  70477. ** We must continue looping until all tables and indices with
  70478. ** rootpage==iFrom have been converted to have a rootpage of iTo
  70479. ** in order to be certain that we got the right one.
  70480. */
  70481. #ifndef SQLITE_OMIT_AUTOVACUUM
  70482. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  70483. HashElem *pElem;
  70484. Hash *pHash;
  70485. Db *pDb;
  70486. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70487. pDb = &db->aDb[iDb];
  70488. pHash = &pDb->pSchema->tblHash;
  70489. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  70490. Table *pTab = sqliteHashData(pElem);
  70491. if( pTab->tnum==iFrom ){
  70492. pTab->tnum = iTo;
  70493. }
  70494. }
  70495. pHash = &pDb->pSchema->idxHash;
  70496. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  70497. Index *pIdx = sqliteHashData(pElem);
  70498. if( pIdx->tnum==iFrom ){
  70499. pIdx->tnum = iTo;
  70500. }
  70501. }
  70502. }
  70503. #endif
  70504. /*
  70505. ** Write code to erase the table with root-page iTable from database iDb.
  70506. ** Also write code to modify the sqlite_master table and internal schema
  70507. ** if a root-page of another table is moved by the btree-layer whilst
  70508. ** erasing iTable (this can happen with an auto-vacuum database).
  70509. */
  70510. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  70511. Vdbe *v = sqlite3GetVdbe(pParse);
  70512. int r1 = sqlite3GetTempReg(pParse);
  70513. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  70514. sqlite3MayAbort(pParse);
  70515. #ifndef SQLITE_OMIT_AUTOVACUUM
  70516. /* OP_Destroy stores an in integer r1. If this integer
  70517. ** is non-zero, then it is the root page number of a table moved to
  70518. ** location iTable. The following code modifies the sqlite_master table to
  70519. ** reflect this.
  70520. **
  70521. ** The "#NNN" in the SQL is a special constant that means whatever value
  70522. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  70523. ** token for additional information.
  70524. */
  70525. sqlite3NestedParse(pParse,
  70526. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  70527. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  70528. #endif
  70529. sqlite3ReleaseTempReg(pParse, r1);
  70530. }
  70531. /*
  70532. ** Write VDBE code to erase table pTab and all associated indices on disk.
  70533. ** Code to update the sqlite_master tables and internal schema definitions
  70534. ** in case a root-page belonging to another table is moved by the btree layer
  70535. ** is also added (this can happen with an auto-vacuum database).
  70536. */
  70537. static void destroyTable(Parse *pParse, Table *pTab){
  70538. #ifdef SQLITE_OMIT_AUTOVACUUM
  70539. Index *pIdx;
  70540. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  70541. destroyRootPage(pParse, pTab->tnum, iDb);
  70542. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70543. destroyRootPage(pParse, pIdx->tnum, iDb);
  70544. }
  70545. #else
  70546. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  70547. ** is not defined), then it is important to call OP_Destroy on the
  70548. ** table and index root-pages in order, starting with the numerically
  70549. ** largest root-page number. This guarantees that none of the root-pages
  70550. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  70551. ** following were coded:
  70552. **
  70553. ** OP_Destroy 4 0
  70554. ** ...
  70555. ** OP_Destroy 5 0
  70556. **
  70557. ** and root page 5 happened to be the largest root-page number in the
  70558. ** database, then root page 5 would be moved to page 4 by the
  70559. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  70560. ** a free-list page.
  70561. */
  70562. int iTab = pTab->tnum;
  70563. int iDestroyed = 0;
  70564. while( 1 ){
  70565. Index *pIdx;
  70566. int iLargest = 0;
  70567. if( iDestroyed==0 || iTab<iDestroyed ){
  70568. iLargest = iTab;
  70569. }
  70570. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70571. int iIdx = pIdx->tnum;
  70572. assert( pIdx->pSchema==pTab->pSchema );
  70573. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  70574. iLargest = iIdx;
  70575. }
  70576. }
  70577. if( iLargest==0 ){
  70578. return;
  70579. }else{
  70580. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  70581. assert( iDb>=0 && iDb<pParse->db->nDb );
  70582. destroyRootPage(pParse, iLargest, iDb);
  70583. iDestroyed = iLargest;
  70584. }
  70585. }
  70586. #endif
  70587. }
  70588. /*
  70589. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  70590. ** after a DROP INDEX or DROP TABLE command.
  70591. */
  70592. static void sqlite3ClearStatTables(
  70593. Parse *pParse, /* The parsing context */
  70594. int iDb, /* The database number */
  70595. const char *zType, /* "idx" or "tbl" */
  70596. const char *zName /* Name of index or table */
  70597. ){
  70598. int i;
  70599. const char *zDbName = pParse->db->aDb[iDb].zName;
  70600. for(i=1; i<=4; i++){
  70601. char zTab[24];
  70602. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  70603. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  70604. sqlite3NestedParse(pParse,
  70605. "DELETE FROM %Q.%s WHERE %s=%Q",
  70606. zDbName, zTab, zType, zName
  70607. );
  70608. }
  70609. }
  70610. }
  70611. /*
  70612. ** Generate code to drop a table.
  70613. */
  70614. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  70615. Vdbe *v;
  70616. sqlite3 *db = pParse->db;
  70617. Trigger *pTrigger;
  70618. Db *pDb = &db->aDb[iDb];
  70619. v = sqlite3GetVdbe(pParse);
  70620. assert( v!=0 );
  70621. sqlite3BeginWriteOperation(pParse, 1, iDb);
  70622. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70623. if( IsVirtual(pTab) ){
  70624. sqlite3VdbeAddOp0(v, OP_VBegin);
  70625. }
  70626. #endif
  70627. /* Drop all triggers associated with the table being dropped. Code
  70628. ** is generated to remove entries from sqlite_master and/or
  70629. ** sqlite_temp_master if required.
  70630. */
  70631. pTrigger = sqlite3TriggerList(pParse, pTab);
  70632. while( pTrigger ){
  70633. assert( pTrigger->pSchema==pTab->pSchema ||
  70634. pTrigger->pSchema==db->aDb[1].pSchema );
  70635. sqlite3DropTriggerPtr(pParse, pTrigger);
  70636. pTrigger = pTrigger->pNext;
  70637. }
  70638. #ifndef SQLITE_OMIT_AUTOINCREMENT
  70639. /* Remove any entries of the sqlite_sequence table associated with
  70640. ** the table being dropped. This is done before the table is dropped
  70641. ** at the btree level, in case the sqlite_sequence table needs to
  70642. ** move as a result of the drop (can happen in auto-vacuum mode).
  70643. */
  70644. if( pTab->tabFlags & TF_Autoincrement ){
  70645. sqlite3NestedParse(pParse,
  70646. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  70647. pDb->zName, pTab->zName
  70648. );
  70649. }
  70650. #endif
  70651. /* Drop all SQLITE_MASTER table and index entries that refer to the
  70652. ** table. The program name loops through the master table and deletes
  70653. ** every row that refers to a table of the same name as the one being
  70654. ** dropped. Triggers are handled separately because a trigger can be
  70655. ** created in the temp database that refers to a table in another
  70656. ** database.
  70657. */
  70658. sqlite3NestedParse(pParse,
  70659. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  70660. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  70661. if( !isView && !IsVirtual(pTab) ){
  70662. destroyTable(pParse, pTab);
  70663. }
  70664. /* Remove the table entry from SQLite's internal schema and modify
  70665. ** the schema cookie.
  70666. */
  70667. if( IsVirtual(pTab) ){
  70668. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  70669. }
  70670. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  70671. sqlite3ChangeCookie(pParse, iDb);
  70672. sqliteViewResetAll(db, iDb);
  70673. }
  70674. /*
  70675. ** This routine is called to do the work of a DROP TABLE statement.
  70676. ** pName is the name of the table to be dropped.
  70677. */
  70678. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  70679. Table *pTab;
  70680. Vdbe *v;
  70681. sqlite3 *db = pParse->db;
  70682. int iDb;
  70683. if( db->mallocFailed ){
  70684. goto exit_drop_table;
  70685. }
  70686. assert( pParse->nErr==0 );
  70687. assert( pName->nSrc==1 );
  70688. if( noErr ) db->suppressErr++;
  70689. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  70690. if( noErr ) db->suppressErr--;
  70691. if( pTab==0 ){
  70692. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  70693. goto exit_drop_table;
  70694. }
  70695. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70696. assert( iDb>=0 && iDb<db->nDb );
  70697. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  70698. ** it is initialized.
  70699. */
  70700. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  70701. goto exit_drop_table;
  70702. }
  70703. #ifndef SQLITE_OMIT_AUTHORIZATION
  70704. {
  70705. int code;
  70706. const char *zTab = SCHEMA_TABLE(iDb);
  70707. const char *zDb = db->aDb[iDb].zName;
  70708. const char *zArg2 = 0;
  70709. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  70710. goto exit_drop_table;
  70711. }
  70712. if( isView ){
  70713. if( !OMIT_TEMPDB && iDb==1 ){
  70714. code = SQLITE_DROP_TEMP_VIEW;
  70715. }else{
  70716. code = SQLITE_DROP_VIEW;
  70717. }
  70718. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70719. }else if( IsVirtual(pTab) ){
  70720. code = SQLITE_DROP_VTABLE;
  70721. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  70722. #endif
  70723. }else{
  70724. if( !OMIT_TEMPDB && iDb==1 ){
  70725. code = SQLITE_DROP_TEMP_TABLE;
  70726. }else{
  70727. code = SQLITE_DROP_TABLE;
  70728. }
  70729. }
  70730. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  70731. goto exit_drop_table;
  70732. }
  70733. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  70734. goto exit_drop_table;
  70735. }
  70736. }
  70737. #endif
  70738. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  70739. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  70740. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  70741. goto exit_drop_table;
  70742. }
  70743. #ifndef SQLITE_OMIT_VIEW
  70744. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  70745. ** on a table.
  70746. */
  70747. if( isView && pTab->pSelect==0 ){
  70748. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  70749. goto exit_drop_table;
  70750. }
  70751. if( !isView && pTab->pSelect ){
  70752. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  70753. goto exit_drop_table;
  70754. }
  70755. #endif
  70756. /* Generate code to remove the table from the master table
  70757. ** on disk.
  70758. */
  70759. v = sqlite3GetVdbe(pParse);
  70760. if( v ){
  70761. sqlite3BeginWriteOperation(pParse, 1, iDb);
  70762. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  70763. sqlite3FkDropTable(pParse, pName, pTab);
  70764. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  70765. }
  70766. exit_drop_table:
  70767. sqlite3SrcListDelete(db, pName);
  70768. }
  70769. /*
  70770. ** This routine is called to create a new foreign key on the table
  70771. ** currently under construction. pFromCol determines which columns
  70772. ** in the current table point to the foreign key. If pFromCol==0 then
  70773. ** connect the key to the last column inserted. pTo is the name of
  70774. ** the table referred to. pToCol is a list of tables in the other
  70775. ** pTo table that the foreign key points to. flags contains all
  70776. ** information about the conflict resolution algorithms specified
  70777. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  70778. **
  70779. ** An FKey structure is created and added to the table currently
  70780. ** under construction in the pParse->pNewTable field.
  70781. **
  70782. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  70783. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  70784. */
  70785. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  70786. Parse *pParse, /* Parsing context */
  70787. ExprList *pFromCol, /* Columns in this table that point to other table */
  70788. Token *pTo, /* Name of the other table */
  70789. ExprList *pToCol, /* Columns in the other table */
  70790. int flags /* Conflict resolution algorithms. */
  70791. ){
  70792. sqlite3 *db = pParse->db;
  70793. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70794. FKey *pFKey = 0;
  70795. FKey *pNextTo;
  70796. Table *p = pParse->pNewTable;
  70797. int nByte;
  70798. int i;
  70799. int nCol;
  70800. char *z;
  70801. assert( pTo!=0 );
  70802. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  70803. if( pFromCol==0 ){
  70804. int iCol = p->nCol-1;
  70805. if( NEVER(iCol<0) ) goto fk_end;
  70806. if( pToCol && pToCol->nExpr!=1 ){
  70807. sqlite3ErrorMsg(pParse, "foreign key on %s"
  70808. " should reference only one column of table %T",
  70809. p->aCol[iCol].zName, pTo);
  70810. goto fk_end;
  70811. }
  70812. nCol = 1;
  70813. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  70814. sqlite3ErrorMsg(pParse,
  70815. "number of columns in foreign key does not match the number of "
  70816. "columns in the referenced table");
  70817. goto fk_end;
  70818. }else{
  70819. nCol = pFromCol->nExpr;
  70820. }
  70821. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  70822. if( pToCol ){
  70823. for(i=0; i<pToCol->nExpr; i++){
  70824. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  70825. }
  70826. }
  70827. pFKey = sqlite3DbMallocZero(db, nByte );
  70828. if( pFKey==0 ){
  70829. goto fk_end;
  70830. }
  70831. pFKey->pFrom = p;
  70832. pFKey->pNextFrom = p->pFKey;
  70833. z = (char*)&pFKey->aCol[nCol];
  70834. pFKey->zTo = z;
  70835. memcpy(z, pTo->z, pTo->n);
  70836. z[pTo->n] = 0;
  70837. sqlite3Dequote(z);
  70838. z += pTo->n+1;
  70839. pFKey->nCol = nCol;
  70840. if( pFromCol==0 ){
  70841. pFKey->aCol[0].iFrom = p->nCol-1;
  70842. }else{
  70843. for(i=0; i<nCol; i++){
  70844. int j;
  70845. for(j=0; j<p->nCol; j++){
  70846. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  70847. pFKey->aCol[i].iFrom = j;
  70848. break;
  70849. }
  70850. }
  70851. if( j>=p->nCol ){
  70852. sqlite3ErrorMsg(pParse,
  70853. "unknown column \"%s\" in foreign key definition",
  70854. pFromCol->a[i].zName);
  70855. goto fk_end;
  70856. }
  70857. }
  70858. }
  70859. if( pToCol ){
  70860. for(i=0; i<nCol; i++){
  70861. int n = sqlite3Strlen30(pToCol->a[i].zName);
  70862. pFKey->aCol[i].zCol = z;
  70863. memcpy(z, pToCol->a[i].zName, n);
  70864. z[n] = 0;
  70865. z += n+1;
  70866. }
  70867. }
  70868. pFKey->isDeferred = 0;
  70869. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  70870. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  70871. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  70872. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  70873. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  70874. );
  70875. if( pNextTo==pFKey ){
  70876. db->mallocFailed = 1;
  70877. goto fk_end;
  70878. }
  70879. if( pNextTo ){
  70880. assert( pNextTo->pPrevTo==0 );
  70881. pFKey->pNextTo = pNextTo;
  70882. pNextTo->pPrevTo = pFKey;
  70883. }
  70884. /* Link the foreign key to the table as the last step.
  70885. */
  70886. p->pFKey = pFKey;
  70887. pFKey = 0;
  70888. fk_end:
  70889. sqlite3DbFree(db, pFKey);
  70890. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  70891. sqlite3ExprListDelete(db, pFromCol);
  70892. sqlite3ExprListDelete(db, pToCol);
  70893. }
  70894. /*
  70895. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  70896. ** clause is seen as part of a foreign key definition. The isDeferred
  70897. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  70898. ** The behavior of the most recently created foreign key is adjusted
  70899. ** accordingly.
  70900. */
  70901. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  70902. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70903. Table *pTab;
  70904. FKey *pFKey;
  70905. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  70906. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  70907. pFKey->isDeferred = (u8)isDeferred;
  70908. #endif
  70909. }
  70910. /*
  70911. ** Generate code that will erase and refill index *pIdx. This is
  70912. ** used to initialize a newly created index or to recompute the
  70913. ** content of an index in response to a REINDEX command.
  70914. **
  70915. ** if memRootPage is not negative, it means that the index is newly
  70916. ** created. The register specified by memRootPage contains the
  70917. ** root page number of the index. If memRootPage is negative, then
  70918. ** the index already exists and must be cleared before being refilled and
  70919. ** the root page number of the index is taken from pIndex->tnum.
  70920. */
  70921. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  70922. Table *pTab = pIndex->pTable; /* The table that is indexed */
  70923. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  70924. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  70925. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  70926. int addr1; /* Address of top of loop */
  70927. int addr2; /* Address to jump to for next iteration */
  70928. int tnum; /* Root page of index */
  70929. int iPartIdxLabel; /* Jump to this label to skip a row */
  70930. Vdbe *v; /* Generate code into this virtual machine */
  70931. KeyInfo *pKey; /* KeyInfo for index */
  70932. int regRecord; /* Register holding assemblied index record */
  70933. sqlite3 *db = pParse->db; /* The database connection */
  70934. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  70935. #ifndef SQLITE_OMIT_AUTHORIZATION
  70936. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  70937. db->aDb[iDb].zName ) ){
  70938. return;
  70939. }
  70940. #endif
  70941. /* Require a write-lock on the table to perform this operation */
  70942. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  70943. v = sqlite3GetVdbe(pParse);
  70944. if( v==0 ) return;
  70945. if( memRootPage>=0 ){
  70946. tnum = memRootPage;
  70947. }else{
  70948. tnum = pIndex->tnum;
  70949. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  70950. }
  70951. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  70952. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  70953. (char *)pKey, P4_KEYINFO_HANDOFF);
  70954. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  70955. /* Open the sorter cursor if we are to use one. */
  70956. iSorter = pParse->nTab++;
  70957. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  70958. /* Open the table. Loop through all rows of the table, inserting index
  70959. ** records into the sorter. */
  70960. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  70961. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  70962. regRecord = sqlite3GetTempReg(pParse);
  70963. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  70964. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  70965. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  70966. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  70967. sqlite3VdbeJumpHere(v, addr1);
  70968. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  70969. if( pIndex->onError!=OE_None ){
  70970. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  70971. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  70972. addr2 = sqlite3VdbeCurrentAddr(v);
  70973. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  70974. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  70975. OE_Abort, "indexed columns are not unique", P4_STATIC
  70976. );
  70977. }else{
  70978. addr2 = sqlite3VdbeCurrentAddr(v);
  70979. }
  70980. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  70981. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  70982. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  70983. sqlite3ReleaseTempReg(pParse, regRecord);
  70984. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  70985. sqlite3VdbeJumpHere(v, addr1);
  70986. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  70987. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  70988. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  70989. }
  70990. /*
  70991. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  70992. ** and pTblList is the name of the table that is to be indexed. Both will
  70993. ** be NULL for a primary key or an index that is created to satisfy a
  70994. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  70995. ** as the table to be indexed. pParse->pNewTable is a table that is
  70996. ** currently being constructed by a CREATE TABLE statement.
  70997. **
  70998. ** pList is a list of columns to be indexed. pList will be NULL if this
  70999. ** is a primary key or unique-constraint on the most recent column added
  71000. ** to the table currently under construction.
  71001. **
  71002. ** If the index is created successfully, return a pointer to the new Index
  71003. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  71004. ** as the tables primary key (Index.autoIndex==2).
  71005. */
  71006. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  71007. Parse *pParse, /* All information about this parse */
  71008. Token *pName1, /* First part of index name. May be NULL */
  71009. Token *pName2, /* Second part of index name. May be NULL */
  71010. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  71011. ExprList *pList, /* A list of columns to be indexed */
  71012. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  71013. Token *pStart, /* The CREATE token that begins this statement */
  71014. Expr *pPIWhere, /* WHERE clause for partial indices */
  71015. int sortOrder, /* Sort order of primary key when pList==NULL */
  71016. int ifNotExist /* Omit error if index already exists */
  71017. ){
  71018. Index *pRet = 0; /* Pointer to return */
  71019. Table *pTab = 0; /* Table to be indexed */
  71020. Index *pIndex = 0; /* The index to be created */
  71021. char *zName = 0; /* Name of the index */
  71022. int nName; /* Number of characters in zName */
  71023. int i, j;
  71024. Token nullId; /* Fake token for an empty ID list */
  71025. DbFixer sFix; /* For assigning database names to pTable */
  71026. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  71027. sqlite3 *db = pParse->db;
  71028. Db *pDb; /* The specific table containing the indexed database */
  71029. int iDb; /* Index of the database that is being written */
  71030. Token *pName = 0; /* Unqualified name of the index to create */
  71031. struct ExprList_item *pListItem; /* For looping over pList */
  71032. const Column *pTabCol; /* A column in the table */
  71033. int nCol; /* Number of columns */
  71034. int nExtra = 0; /* Space allocated for zExtra[] */
  71035. char *zExtra; /* Extra space after the Index object */
  71036. assert( pParse->nErr==0 ); /* Never called with prior errors */
  71037. if( db->mallocFailed || IN_DECLARE_VTAB ){
  71038. goto exit_create_index;
  71039. }
  71040. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  71041. goto exit_create_index;
  71042. }
  71043. /*
  71044. ** Find the table that is to be indexed. Return early if not found.
  71045. */
  71046. if( pTblName!=0 ){
  71047. /* Use the two-part index name to determine the database
  71048. ** to search for the table. 'Fix' the table name to this db
  71049. ** before looking up the table.
  71050. */
  71051. assert( pName1 && pName2 );
  71052. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  71053. if( iDb<0 ) goto exit_create_index;
  71054. assert( pName && pName->z );
  71055. #ifndef SQLITE_OMIT_TEMPDB
  71056. /* If the index name was unqualified, check if the table
  71057. ** is a temp table. If so, set the database to 1. Do not do this
  71058. ** if initialising a database schema.
  71059. */
  71060. if( !db->init.busy ){
  71061. pTab = sqlite3SrcListLookup(pParse, pTblName);
  71062. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  71063. iDb = 1;
  71064. }
  71065. }
  71066. #endif
  71067. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  71068. if( sqlite3FixSrcList(&sFix, pTblName) ){
  71069. /* Because the parser constructs pTblName from a single identifier,
  71070. ** sqlite3FixSrcList can never fail. */
  71071. assert(0);
  71072. }
  71073. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  71074. assert( db->mallocFailed==0 || pTab==0 );
  71075. if( pTab==0 ) goto exit_create_index;
  71076. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  71077. sqlite3ErrorMsg(pParse,
  71078. "cannot create a TEMP index on non-TEMP table \"%s\"",
  71079. pTab->zName);
  71080. goto exit_create_index;
  71081. }
  71082. }else{
  71083. assert( pName==0 );
  71084. assert( pStart==0 );
  71085. pTab = pParse->pNewTable;
  71086. if( !pTab ) goto exit_create_index;
  71087. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  71088. }
  71089. pDb = &db->aDb[iDb];
  71090. assert( pTab!=0 );
  71091. assert( pParse->nErr==0 );
  71092. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  71093. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  71094. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  71095. goto exit_create_index;
  71096. }
  71097. #ifndef SQLITE_OMIT_VIEW
  71098. if( pTab->pSelect ){
  71099. sqlite3ErrorMsg(pParse, "views may not be indexed");
  71100. goto exit_create_index;
  71101. }
  71102. #endif
  71103. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71104. if( IsVirtual(pTab) ){
  71105. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  71106. goto exit_create_index;
  71107. }
  71108. #endif
  71109. /*
  71110. ** Find the name of the index. Make sure there is not already another
  71111. ** index or table with the same name.
  71112. **
  71113. ** Exception: If we are reading the names of permanent indices from the
  71114. ** sqlite_master table (because some other process changed the schema) and
  71115. ** one of the index names collides with the name of a temporary table or
  71116. ** index, then we will continue to process this index.
  71117. **
  71118. ** If pName==0 it means that we are
  71119. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  71120. ** own name.
  71121. */
  71122. if( pName ){
  71123. zName = sqlite3NameFromToken(db, pName);
  71124. if( zName==0 ) goto exit_create_index;
  71125. assert( pName->z!=0 );
  71126. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  71127. goto exit_create_index;
  71128. }
  71129. if( !db->init.busy ){
  71130. if( sqlite3FindTable(db, zName, 0)!=0 ){
  71131. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  71132. goto exit_create_index;
  71133. }
  71134. }
  71135. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  71136. if( !ifNotExist ){
  71137. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  71138. }else{
  71139. assert( !db->init.busy );
  71140. sqlite3CodeVerifySchema(pParse, iDb);
  71141. }
  71142. goto exit_create_index;
  71143. }
  71144. }else{
  71145. int n;
  71146. Index *pLoop;
  71147. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  71148. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  71149. if( zName==0 ){
  71150. goto exit_create_index;
  71151. }
  71152. }
  71153. /* Check for authorization to create an index.
  71154. */
  71155. #ifndef SQLITE_OMIT_AUTHORIZATION
  71156. {
  71157. const char *zDb = pDb->zName;
  71158. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  71159. goto exit_create_index;
  71160. }
  71161. i = SQLITE_CREATE_INDEX;
  71162. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  71163. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  71164. goto exit_create_index;
  71165. }
  71166. }
  71167. #endif
  71168. /* If pList==0, it means this routine was called to make a primary
  71169. ** key out of the last column added to the table under construction.
  71170. ** So create a fake list to simulate this.
  71171. */
  71172. if( pList==0 ){
  71173. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  71174. nullId.n = sqlite3Strlen30((char*)nullId.z);
  71175. pList = sqlite3ExprListAppend(pParse, 0, 0);
  71176. if( pList==0 ) goto exit_create_index;
  71177. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  71178. pList->a[0].sortOrder = (u8)sortOrder;
  71179. }
  71180. /* Figure out how many bytes of space are required to store explicitly
  71181. ** specified collation sequence names.
  71182. */
  71183. for(i=0; i<pList->nExpr; i++){
  71184. Expr *pExpr = pList->a[i].pExpr;
  71185. if( pExpr ){
  71186. assert( pExpr->op==TK_COLLATE );
  71187. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  71188. }
  71189. }
  71190. /*
  71191. ** Allocate the index structure.
  71192. */
  71193. nName = sqlite3Strlen30(zName);
  71194. nCol = pList->nExpr;
  71195. pIndex = sqlite3DbMallocZero(db,
  71196. ROUND8(sizeof(Index)) + /* Index structure */
  71197. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  71198. sizeof(char *)*nCol + /* Index.azColl */
  71199. sizeof(int)*nCol + /* Index.aiColumn */
  71200. sizeof(u8)*nCol + /* Index.aSortOrder */
  71201. nName + 1 + /* Index.zName */
  71202. nExtra /* Collation sequence names */
  71203. );
  71204. if( db->mallocFailed ){
  71205. goto exit_create_index;
  71206. }
  71207. zExtra = (char*)pIndex;
  71208. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  71209. pIndex->azColl = (char**)
  71210. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  71211. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  71212. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  71213. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  71214. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  71215. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  71216. zExtra = (char *)(&pIndex->zName[nName+1]);
  71217. memcpy(pIndex->zName, zName, nName+1);
  71218. pIndex->pTable = pTab;
  71219. pIndex->nColumn = pList->nExpr;
  71220. pIndex->onError = (u8)onError;
  71221. pIndex->uniqNotNull = onError==OE_Abort;
  71222. pIndex->autoIndex = (u8)(pName==0);
  71223. pIndex->pSchema = db->aDb[iDb].pSchema;
  71224. if( pPIWhere ){
  71225. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  71226. pIndex->pPartIdxWhere = pPIWhere;
  71227. pPIWhere = 0;
  71228. }
  71229. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  71230. /* Check to see if we should honor DESC requests on index columns
  71231. */
  71232. if( pDb->pSchema->file_format>=4 ){
  71233. sortOrderMask = -1; /* Honor DESC */
  71234. }else{
  71235. sortOrderMask = 0; /* Ignore DESC */
  71236. }
  71237. /* Scan the names of the columns of the table to be indexed and
  71238. ** load the column indices into the Index structure. Report an error
  71239. ** if any column is not found.
  71240. **
  71241. ** TODO: Add a test to make sure that the same column is not named
  71242. ** more than once within the same index. Only the first instance of
  71243. ** the column will ever be used by the optimizer. Note that using the
  71244. ** same column more than once cannot be an error because that would
  71245. ** break backwards compatibility - it needs to be a warning.
  71246. */
  71247. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  71248. const char *zColName = pListItem->zName;
  71249. int requestedSortOrder;
  71250. char *zColl; /* Collation sequence name */
  71251. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  71252. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  71253. }
  71254. if( j>=pTab->nCol ){
  71255. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  71256. pTab->zName, zColName);
  71257. pParse->checkSchema = 1;
  71258. goto exit_create_index;
  71259. }
  71260. pIndex->aiColumn[i] = j;
  71261. if( pListItem->pExpr ){
  71262. int nColl;
  71263. assert( pListItem->pExpr->op==TK_COLLATE );
  71264. zColl = pListItem->pExpr->u.zToken;
  71265. nColl = sqlite3Strlen30(zColl) + 1;
  71266. assert( nExtra>=nColl );
  71267. memcpy(zExtra, zColl, nColl);
  71268. zColl = zExtra;
  71269. zExtra += nColl;
  71270. nExtra -= nColl;
  71271. }else{
  71272. zColl = pTab->aCol[j].zColl;
  71273. if( !zColl ) zColl = "BINARY";
  71274. }
  71275. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  71276. goto exit_create_index;
  71277. }
  71278. pIndex->azColl[i] = zColl;
  71279. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  71280. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  71281. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  71282. }
  71283. sqlite3DefaultRowEst(pIndex);
  71284. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  71285. if( pTab==pParse->pNewTable ){
  71286. /* This routine has been called to create an automatic index as a
  71287. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  71288. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  71289. ** i.e. one of:
  71290. **
  71291. ** CREATE TABLE t(x PRIMARY KEY, y);
  71292. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  71293. **
  71294. ** Either way, check to see if the table already has such an index. If
  71295. ** so, don't bother creating this one. This only applies to
  71296. ** automatically created indices. Users can do as they wish with
  71297. ** explicit indices.
  71298. **
  71299. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  71300. ** (and thus suppressing the second one) even if they have different
  71301. ** sort orders.
  71302. **
  71303. ** If there are different collating sequences or if the columns of
  71304. ** the constraint occur in different orders, then the constraints are
  71305. ** considered distinct and both result in separate indices.
  71306. */
  71307. Index *pIdx;
  71308. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  71309. int k;
  71310. assert( pIdx->onError!=OE_None );
  71311. assert( pIdx->autoIndex );
  71312. assert( pIndex->onError!=OE_None );
  71313. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  71314. for(k=0; k<pIdx->nColumn; k++){
  71315. const char *z1;
  71316. const char *z2;
  71317. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  71318. z1 = pIdx->azColl[k];
  71319. z2 = pIndex->azColl[k];
  71320. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  71321. }
  71322. if( k==pIdx->nColumn ){
  71323. if( pIdx->onError!=pIndex->onError ){
  71324. /* This constraint creates the same index as a previous
  71325. ** constraint specified somewhere in the CREATE TABLE statement.
  71326. ** However the ON CONFLICT clauses are different. If both this
  71327. ** constraint and the previous equivalent constraint have explicit
  71328. ** ON CONFLICT clauses this is an error. Otherwise, use the
  71329. ** explicitly specified behavior for the index.
  71330. */
  71331. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  71332. sqlite3ErrorMsg(pParse,
  71333. "conflicting ON CONFLICT clauses specified", 0);
  71334. }
  71335. if( pIdx->onError==OE_Default ){
  71336. pIdx->onError = pIndex->onError;
  71337. }
  71338. }
  71339. goto exit_create_index;
  71340. }
  71341. }
  71342. }
  71343. /* Link the new Index structure to its table and to the other
  71344. ** in-memory database structures.
  71345. */
  71346. if( db->init.busy ){
  71347. Index *p;
  71348. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  71349. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  71350. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  71351. pIndex);
  71352. if( p ){
  71353. assert( p==pIndex ); /* Malloc must have failed */
  71354. db->mallocFailed = 1;
  71355. goto exit_create_index;
  71356. }
  71357. db->flags |= SQLITE_InternChanges;
  71358. if( pTblName!=0 ){
  71359. pIndex->tnum = db->init.newTnum;
  71360. }
  71361. }
  71362. /* If the db->init.busy is 0 then create the index on disk. This
  71363. ** involves writing the index into the master table and filling in the
  71364. ** index with the current table contents.
  71365. **
  71366. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  71367. ** command. db->init.busy is 1 when a database is opened and
  71368. ** CREATE INDEX statements are read out of the master table. In
  71369. ** the latter case the index already exists on disk, which is why
  71370. ** we don't want to recreate it.
  71371. **
  71372. ** If pTblName==0 it means this index is generated as a primary key
  71373. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  71374. ** has just been created, it contains no data and the index initialization
  71375. ** step can be skipped.
  71376. */
  71377. else if( pParse->nErr==0 ){
  71378. Vdbe *v;
  71379. char *zStmt;
  71380. int iMem = ++pParse->nMem;
  71381. v = sqlite3GetVdbe(pParse);
  71382. if( v==0 ) goto exit_create_index;
  71383. /* Create the rootpage for the index
  71384. */
  71385. sqlite3BeginWriteOperation(pParse, 1, iDb);
  71386. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  71387. /* Gather the complete text of the CREATE INDEX statement into
  71388. ** the zStmt variable
  71389. */
  71390. if( pStart ){
  71391. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  71392. if( pName->z[n-1]==';' ) n--;
  71393. /* A named index with an explicit CREATE INDEX statement */
  71394. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  71395. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  71396. }else{
  71397. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  71398. /* zStmt = sqlite3MPrintf(""); */
  71399. zStmt = 0;
  71400. }
  71401. /* Add an entry in sqlite_master for this index
  71402. */
  71403. sqlite3NestedParse(pParse,
  71404. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  71405. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  71406. pIndex->zName,
  71407. pTab->zName,
  71408. iMem,
  71409. zStmt
  71410. );
  71411. sqlite3DbFree(db, zStmt);
  71412. /* Fill the index with data and reparse the schema. Code an OP_Expire
  71413. ** to invalidate all pre-compiled statements.
  71414. */
  71415. if( pTblName ){
  71416. sqlite3RefillIndex(pParse, pIndex, iMem);
  71417. sqlite3ChangeCookie(pParse, iDb);
  71418. sqlite3VdbeAddParseSchemaOp(v, iDb,
  71419. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  71420. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  71421. }
  71422. }
  71423. /* When adding an index to the list of indices for a table, make
  71424. ** sure all indices labeled OE_Replace come after all those labeled
  71425. ** OE_Ignore. This is necessary for the correct constraint check
  71426. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  71427. ** UPDATE and INSERT statements.
  71428. */
  71429. if( db->init.busy || pTblName==0 ){
  71430. if( onError!=OE_Replace || pTab->pIndex==0
  71431. || pTab->pIndex->onError==OE_Replace){
  71432. pIndex->pNext = pTab->pIndex;
  71433. pTab->pIndex = pIndex;
  71434. }else{
  71435. Index *pOther = pTab->pIndex;
  71436. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  71437. pOther = pOther->pNext;
  71438. }
  71439. pIndex->pNext = pOther->pNext;
  71440. pOther->pNext = pIndex;
  71441. }
  71442. pRet = pIndex;
  71443. pIndex = 0;
  71444. }
  71445. /* Clean up before exiting */
  71446. exit_create_index:
  71447. if( pIndex ) freeIndex(db, pIndex);
  71448. sqlite3ExprDelete(db, pPIWhere);
  71449. sqlite3ExprListDelete(db, pList);
  71450. sqlite3SrcListDelete(db, pTblName);
  71451. sqlite3DbFree(db, zName);
  71452. return pRet;
  71453. }
  71454. /*
  71455. ** Fill the Index.aiRowEst[] array with default information - information
  71456. ** to be used when we have not run the ANALYZE command.
  71457. **
  71458. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  71459. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  71460. ** number of rows in the table that match any particular value of the
  71461. ** first column of the index. aiRowEst[2] is an estimate of the number
  71462. ** of rows that match any particular combiniation of the first 2 columns
  71463. ** of the index. And so forth. It must always be the case that
  71464. *
  71465. ** aiRowEst[N]<=aiRowEst[N-1]
  71466. ** aiRowEst[N]>=1
  71467. **
  71468. ** Apart from that, we have little to go on besides intuition as to
  71469. ** how aiRowEst[] should be initialized. The numbers generated here
  71470. ** are based on typical values found in actual indices.
  71471. */
  71472. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  71473. tRowcnt *a = pIdx->aiRowEst;
  71474. int i;
  71475. tRowcnt n;
  71476. assert( a!=0 );
  71477. a[0] = pIdx->pTable->nRowEst;
  71478. if( a[0]<10 ) a[0] = 10;
  71479. n = 10;
  71480. for(i=1; i<=pIdx->nColumn; i++){
  71481. a[i] = n;
  71482. if( n>5 ) n--;
  71483. }
  71484. if( pIdx->onError!=OE_None ){
  71485. a[pIdx->nColumn] = 1;
  71486. }
  71487. }
  71488. /*
  71489. ** This routine will drop an existing named index. This routine
  71490. ** implements the DROP INDEX statement.
  71491. */
  71492. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  71493. Index *pIndex;
  71494. Vdbe *v;
  71495. sqlite3 *db = pParse->db;
  71496. int iDb;
  71497. assert( pParse->nErr==0 ); /* Never called with prior errors */
  71498. if( db->mallocFailed ){
  71499. goto exit_drop_index;
  71500. }
  71501. assert( pName->nSrc==1 );
  71502. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  71503. goto exit_drop_index;
  71504. }
  71505. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  71506. if( pIndex==0 ){
  71507. if( !ifExists ){
  71508. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  71509. }else{
  71510. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  71511. }
  71512. pParse->checkSchema = 1;
  71513. goto exit_drop_index;
  71514. }
  71515. if( pIndex->autoIndex ){
  71516. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  71517. "or PRIMARY KEY constraint cannot be dropped", 0);
  71518. goto exit_drop_index;
  71519. }
  71520. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  71521. #ifndef SQLITE_OMIT_AUTHORIZATION
  71522. {
  71523. int code = SQLITE_DROP_INDEX;
  71524. Table *pTab = pIndex->pTable;
  71525. const char *zDb = db->aDb[iDb].zName;
  71526. const char *zTab = SCHEMA_TABLE(iDb);
  71527. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  71528. goto exit_drop_index;
  71529. }
  71530. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  71531. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  71532. goto exit_drop_index;
  71533. }
  71534. }
  71535. #endif
  71536. /* Generate code to remove the index and from the master table */
  71537. v = sqlite3GetVdbe(pParse);
  71538. if( v ){
  71539. sqlite3BeginWriteOperation(pParse, 1, iDb);
  71540. sqlite3NestedParse(pParse,
  71541. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  71542. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  71543. );
  71544. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  71545. sqlite3ChangeCookie(pParse, iDb);
  71546. destroyRootPage(pParse, pIndex->tnum, iDb);
  71547. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  71548. }
  71549. exit_drop_index:
  71550. sqlite3SrcListDelete(db, pName);
  71551. }
  71552. /*
  71553. ** pArray is a pointer to an array of objects. Each object in the
  71554. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  71555. ** to extend the array so that there is space for a new object at the end.
  71556. **
  71557. ** When this function is called, *pnEntry contains the current size of
  71558. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  71559. ** in total).
  71560. **
  71561. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  71562. ** space allocated for the new object is zeroed, *pnEntry updated to
  71563. ** reflect the new size of the array and a pointer to the new allocation
  71564. ** returned. *pIdx is set to the index of the new array entry in this case.
  71565. **
  71566. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  71567. ** unchanged and a copy of pArray returned.
  71568. */
  71569. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  71570. sqlite3 *db, /* Connection to notify of malloc failures */
  71571. void *pArray, /* Array of objects. Might be reallocated */
  71572. int szEntry, /* Size of each object in the array */
  71573. int *pnEntry, /* Number of objects currently in use */
  71574. int *pIdx /* Write the index of a new slot here */
  71575. ){
  71576. char *z;
  71577. int n = *pnEntry;
  71578. if( (n & (n-1))==0 ){
  71579. int sz = (n==0) ? 1 : 2*n;
  71580. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  71581. if( pNew==0 ){
  71582. *pIdx = -1;
  71583. return pArray;
  71584. }
  71585. pArray = pNew;
  71586. }
  71587. z = (char*)pArray;
  71588. memset(&z[n * szEntry], 0, szEntry);
  71589. *pIdx = n;
  71590. ++*pnEntry;
  71591. return pArray;
  71592. }
  71593. /*
  71594. ** Append a new element to the given IdList. Create a new IdList if
  71595. ** need be.
  71596. **
  71597. ** A new IdList is returned, or NULL if malloc() fails.
  71598. */
  71599. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  71600. int i;
  71601. if( pList==0 ){
  71602. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  71603. if( pList==0 ) return 0;
  71604. }
  71605. pList->a = sqlite3ArrayAllocate(
  71606. db,
  71607. pList->a,
  71608. sizeof(pList->a[0]),
  71609. &pList->nId,
  71610. &i
  71611. );
  71612. if( i<0 ){
  71613. sqlite3IdListDelete(db, pList);
  71614. return 0;
  71615. }
  71616. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  71617. return pList;
  71618. }
  71619. /*
  71620. ** Delete an IdList.
  71621. */
  71622. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  71623. int i;
  71624. if( pList==0 ) return;
  71625. for(i=0; i<pList->nId; i++){
  71626. sqlite3DbFree(db, pList->a[i].zName);
  71627. }
  71628. sqlite3DbFree(db, pList->a);
  71629. sqlite3DbFree(db, pList);
  71630. }
  71631. /*
  71632. ** Return the index in pList of the identifier named zId. Return -1
  71633. ** if not found.
  71634. */
  71635. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  71636. int i;
  71637. if( pList==0 ) return -1;
  71638. for(i=0; i<pList->nId; i++){
  71639. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  71640. }
  71641. return -1;
  71642. }
  71643. /*
  71644. ** Expand the space allocated for the given SrcList object by
  71645. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  71646. ** New slots are zeroed.
  71647. **
  71648. ** For example, suppose a SrcList initially contains two entries: A,B.
  71649. ** To append 3 new entries onto the end, do this:
  71650. **
  71651. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  71652. **
  71653. ** After the call above it would contain: A, B, nil, nil, nil.
  71654. ** If the iStart argument had been 1 instead of 2, then the result
  71655. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  71656. ** the iStart value would be 0. The result then would
  71657. ** be: nil, nil, nil, A, B.
  71658. **
  71659. ** If a memory allocation fails the SrcList is unchanged. The
  71660. ** db->mallocFailed flag will be set to true.
  71661. */
  71662. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  71663. sqlite3 *db, /* Database connection to notify of OOM errors */
  71664. SrcList *pSrc, /* The SrcList to be enlarged */
  71665. int nExtra, /* Number of new slots to add to pSrc->a[] */
  71666. int iStart /* Index in pSrc->a[] of first new slot */
  71667. ){
  71668. int i;
  71669. /* Sanity checking on calling parameters */
  71670. assert( iStart>=0 );
  71671. assert( nExtra>=1 );
  71672. assert( pSrc!=0 );
  71673. assert( iStart<=pSrc->nSrc );
  71674. /* Allocate additional space if needed */
  71675. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  71676. SrcList *pNew;
  71677. int nAlloc = pSrc->nSrc+nExtra;
  71678. int nGot;
  71679. pNew = sqlite3DbRealloc(db, pSrc,
  71680. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  71681. if( pNew==0 ){
  71682. assert( db->mallocFailed );
  71683. return pSrc;
  71684. }
  71685. pSrc = pNew;
  71686. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  71687. pSrc->nAlloc = (u8)nGot;
  71688. }
  71689. /* Move existing slots that come after the newly inserted slots
  71690. ** out of the way */
  71691. for(i=pSrc->nSrc-1; i>=iStart; i--){
  71692. pSrc->a[i+nExtra] = pSrc->a[i];
  71693. }
  71694. pSrc->nSrc += (i8)nExtra;
  71695. /* Zero the newly allocated slots */
  71696. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  71697. for(i=iStart; i<iStart+nExtra; i++){
  71698. pSrc->a[i].iCursor = -1;
  71699. }
  71700. /* Return a pointer to the enlarged SrcList */
  71701. return pSrc;
  71702. }
  71703. /*
  71704. ** Append a new table name to the given SrcList. Create a new SrcList if
  71705. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  71706. **
  71707. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  71708. ** SrcList might be the same as the SrcList that was input or it might be
  71709. ** a new one. If an OOM error does occurs, then the prior value of pList
  71710. ** that is input to this routine is automatically freed.
  71711. **
  71712. ** If pDatabase is not null, it means that the table has an optional
  71713. ** database name prefix. Like this: "database.table". The pDatabase
  71714. ** points to the table name and the pTable points to the database name.
  71715. ** The SrcList.a[].zName field is filled with the table name which might
  71716. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  71717. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  71718. ** or with NULL if no database is specified.
  71719. **
  71720. ** In other words, if call like this:
  71721. **
  71722. ** sqlite3SrcListAppend(D,A,B,0);
  71723. **
  71724. ** Then B is a table name and the database name is unspecified. If called
  71725. ** like this:
  71726. **
  71727. ** sqlite3SrcListAppend(D,A,B,C);
  71728. **
  71729. ** Then C is the table name and B is the database name. If C is defined
  71730. ** then so is B. In other words, we never have a case where:
  71731. **
  71732. ** sqlite3SrcListAppend(D,A,0,C);
  71733. **
  71734. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  71735. ** before being added to the SrcList.
  71736. */
  71737. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  71738. sqlite3 *db, /* Connection to notify of malloc failures */
  71739. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  71740. Token *pTable, /* Table to append */
  71741. Token *pDatabase /* Database of the table */
  71742. ){
  71743. struct SrcList_item *pItem;
  71744. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  71745. if( pList==0 ){
  71746. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  71747. if( pList==0 ) return 0;
  71748. pList->nAlloc = 1;
  71749. }
  71750. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  71751. if( db->mallocFailed ){
  71752. sqlite3SrcListDelete(db, pList);
  71753. return 0;
  71754. }
  71755. pItem = &pList->a[pList->nSrc-1];
  71756. if( pDatabase && pDatabase->z==0 ){
  71757. pDatabase = 0;
  71758. }
  71759. if( pDatabase ){
  71760. Token *pTemp = pDatabase;
  71761. pDatabase = pTable;
  71762. pTable = pTemp;
  71763. }
  71764. pItem->zName = sqlite3NameFromToken(db, pTable);
  71765. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  71766. return pList;
  71767. }
  71768. /*
  71769. ** Assign VdbeCursor index numbers to all tables in a SrcList
  71770. */
  71771. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  71772. int i;
  71773. struct SrcList_item *pItem;
  71774. assert(pList || pParse->db->mallocFailed );
  71775. if( pList ){
  71776. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  71777. if( pItem->iCursor>=0 ) break;
  71778. pItem->iCursor = pParse->nTab++;
  71779. if( pItem->pSelect ){
  71780. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  71781. }
  71782. }
  71783. }
  71784. }
  71785. /*
  71786. ** Delete an entire SrcList including all its substructure.
  71787. */
  71788. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  71789. int i;
  71790. struct SrcList_item *pItem;
  71791. if( pList==0 ) return;
  71792. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  71793. sqlite3DbFree(db, pItem->zDatabase);
  71794. sqlite3DbFree(db, pItem->zName);
  71795. sqlite3DbFree(db, pItem->zAlias);
  71796. sqlite3DbFree(db, pItem->zIndex);
  71797. sqlite3DeleteTable(db, pItem->pTab);
  71798. sqlite3SelectDelete(db, pItem->pSelect);
  71799. sqlite3ExprDelete(db, pItem->pOn);
  71800. sqlite3IdListDelete(db, pItem->pUsing);
  71801. }
  71802. sqlite3DbFree(db, pList);
  71803. }
  71804. /*
  71805. ** This routine is called by the parser to add a new term to the
  71806. ** end of a growing FROM clause. The "p" parameter is the part of
  71807. ** the FROM clause that has already been constructed. "p" is NULL
  71808. ** if this is the first term of the FROM clause. pTable and pDatabase
  71809. ** are the name of the table and database named in the FROM clause term.
  71810. ** pDatabase is NULL if the database name qualifier is missing - the
  71811. ** usual case. If the term has a alias, then pAlias points to the
  71812. ** alias token. If the term is a subquery, then pSubquery is the
  71813. ** SELECT statement that the subquery encodes. The pTable and
  71814. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  71815. ** parameters are the content of the ON and USING clauses.
  71816. **
  71817. ** Return a new SrcList which encodes is the FROM with the new
  71818. ** term added.
  71819. */
  71820. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  71821. Parse *pParse, /* Parsing context */
  71822. SrcList *p, /* The left part of the FROM clause already seen */
  71823. Token *pTable, /* Name of the table to add to the FROM clause */
  71824. Token *pDatabase, /* Name of the database containing pTable */
  71825. Token *pAlias, /* The right-hand side of the AS subexpression */
  71826. Select *pSubquery, /* A subquery used in place of a table name */
  71827. Expr *pOn, /* The ON clause of a join */
  71828. IdList *pUsing /* The USING clause of a join */
  71829. ){
  71830. struct SrcList_item *pItem;
  71831. sqlite3 *db = pParse->db;
  71832. if( !p && (pOn || pUsing) ){
  71833. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  71834. (pOn ? "ON" : "USING")
  71835. );
  71836. goto append_from_error;
  71837. }
  71838. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  71839. if( p==0 || NEVER(p->nSrc==0) ){
  71840. goto append_from_error;
  71841. }
  71842. pItem = &p->a[p->nSrc-1];
  71843. assert( pAlias!=0 );
  71844. if( pAlias->n ){
  71845. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  71846. }
  71847. pItem->pSelect = pSubquery;
  71848. pItem->pOn = pOn;
  71849. pItem->pUsing = pUsing;
  71850. return p;
  71851. append_from_error:
  71852. assert( p==0 );
  71853. sqlite3ExprDelete(db, pOn);
  71854. sqlite3IdListDelete(db, pUsing);
  71855. sqlite3SelectDelete(db, pSubquery);
  71856. return 0;
  71857. }
  71858. /*
  71859. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  71860. ** element of the source-list passed as the second argument.
  71861. */
  71862. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  71863. assert( pIndexedBy!=0 );
  71864. if( p && ALWAYS(p->nSrc>0) ){
  71865. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  71866. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  71867. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  71868. /* A "NOT INDEXED" clause was supplied. See parse.y
  71869. ** construct "indexed_opt" for details. */
  71870. pItem->notIndexed = 1;
  71871. }else{
  71872. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  71873. }
  71874. }
  71875. }
  71876. /*
  71877. ** When building up a FROM clause in the parser, the join operator
  71878. ** is initially attached to the left operand. But the code generator
  71879. ** expects the join operator to be on the right operand. This routine
  71880. ** Shifts all join operators from left to right for an entire FROM
  71881. ** clause.
  71882. **
  71883. ** Example: Suppose the join is like this:
  71884. **
  71885. ** A natural cross join B
  71886. **
  71887. ** The operator is "natural cross join". The A and B operands are stored
  71888. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  71889. ** operator with A. This routine shifts that operator over to B.
  71890. */
  71891. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  71892. if( p ){
  71893. int i;
  71894. assert( p->a || p->nSrc==0 );
  71895. for(i=p->nSrc-1; i>0; i--){
  71896. p->a[i].jointype = p->a[i-1].jointype;
  71897. }
  71898. p->a[0].jointype = 0;
  71899. }
  71900. }
  71901. /*
  71902. ** Begin a transaction
  71903. */
  71904. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  71905. sqlite3 *db;
  71906. Vdbe *v;
  71907. int i;
  71908. assert( pParse!=0 );
  71909. db = pParse->db;
  71910. assert( db!=0 );
  71911. /* if( db->aDb[0].pBt==0 ) return; */
  71912. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  71913. return;
  71914. }
  71915. v = sqlite3GetVdbe(pParse);
  71916. if( !v ) return;
  71917. if( type!=TK_DEFERRED ){
  71918. for(i=0; i<db->nDb; i++){
  71919. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  71920. sqlite3VdbeUsesBtree(v, i);
  71921. }
  71922. }
  71923. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  71924. }
  71925. /*
  71926. ** Commit a transaction
  71927. */
  71928. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  71929. Vdbe *v;
  71930. assert( pParse!=0 );
  71931. assert( pParse->db!=0 );
  71932. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  71933. return;
  71934. }
  71935. v = sqlite3GetVdbe(pParse);
  71936. if( v ){
  71937. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  71938. }
  71939. }
  71940. /*
  71941. ** Rollback a transaction
  71942. */
  71943. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  71944. Vdbe *v;
  71945. assert( pParse!=0 );
  71946. assert( pParse->db!=0 );
  71947. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  71948. return;
  71949. }
  71950. v = sqlite3GetVdbe(pParse);
  71951. if( v ){
  71952. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  71953. }
  71954. }
  71955. /*
  71956. ** This function is called by the parser when it parses a command to create,
  71957. ** release or rollback an SQL savepoint.
  71958. */
  71959. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  71960. char *zName = sqlite3NameFromToken(pParse->db, pName);
  71961. if( zName ){
  71962. Vdbe *v = sqlite3GetVdbe(pParse);
  71963. #ifndef SQLITE_OMIT_AUTHORIZATION
  71964. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  71965. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  71966. #endif
  71967. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  71968. sqlite3DbFree(pParse->db, zName);
  71969. return;
  71970. }
  71971. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  71972. }
  71973. }
  71974. /*
  71975. ** Make sure the TEMP database is open and available for use. Return
  71976. ** the number of errors. Leave any error messages in the pParse structure.
  71977. */
  71978. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  71979. sqlite3 *db = pParse->db;
  71980. if( db->aDb[1].pBt==0 && !pParse->explain ){
  71981. int rc;
  71982. Btree *pBt;
  71983. static const int flags =
  71984. SQLITE_OPEN_READWRITE |
  71985. SQLITE_OPEN_CREATE |
  71986. SQLITE_OPEN_EXCLUSIVE |
  71987. SQLITE_OPEN_DELETEONCLOSE |
  71988. SQLITE_OPEN_TEMP_DB;
  71989. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  71990. if( rc!=SQLITE_OK ){
  71991. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  71992. "file for storing temporary tables");
  71993. pParse->rc = rc;
  71994. return 1;
  71995. }
  71996. db->aDb[1].pBt = pBt;
  71997. assert( db->aDb[1].pSchema );
  71998. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  71999. db->mallocFailed = 1;
  72000. return 1;
  72001. }
  72002. }
  72003. return 0;
  72004. }
  72005. /*
  72006. ** Generate VDBE code that will verify the schema cookie and start
  72007. ** a read-transaction for all named database files.
  72008. **
  72009. ** It is important that all schema cookies be verified and all
  72010. ** read transactions be started before anything else happens in
  72011. ** the VDBE program. But this routine can be called after much other
  72012. ** code has been generated. So here is what we do:
  72013. **
  72014. ** The first time this routine is called, we code an OP_Goto that
  72015. ** will jump to a subroutine at the end of the program. Then we
  72016. ** record every database that needs its schema verified in the
  72017. ** pParse->cookieMask field. Later, after all other code has been
  72018. ** generated, the subroutine that does the cookie verifications and
  72019. ** starts the transactions will be coded and the OP_Goto P2 value
  72020. ** will be made to point to that subroutine. The generation of the
  72021. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  72022. **
  72023. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  72024. ** schema on any databases. This can be used to position the OP_Goto
  72025. ** early in the code, before we know if any database tables will be used.
  72026. */
  72027. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  72028. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72029. #ifndef SQLITE_OMIT_TRIGGER
  72030. if( pToplevel!=pParse ){
  72031. /* This branch is taken if a trigger is currently being coded. In this
  72032. ** case, set cookieGoto to a non-zero value to show that this function
  72033. ** has been called. This is used by the sqlite3ExprCodeConstants()
  72034. ** function. */
  72035. pParse->cookieGoto = -1;
  72036. }
  72037. #endif
  72038. if( pToplevel->cookieGoto==0 ){
  72039. Vdbe *v = sqlite3GetVdbe(pToplevel);
  72040. if( v==0 ) return; /* This only happens if there was a prior error */
  72041. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  72042. }
  72043. if( iDb>=0 ){
  72044. sqlite3 *db = pToplevel->db;
  72045. yDbMask mask;
  72046. assert( iDb<db->nDb );
  72047. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  72048. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  72049. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72050. mask = ((yDbMask)1)<<iDb;
  72051. if( (pToplevel->cookieMask & mask)==0 ){
  72052. pToplevel->cookieMask |= mask;
  72053. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  72054. if( !OMIT_TEMPDB && iDb==1 ){
  72055. sqlite3OpenTempDatabase(pToplevel);
  72056. }
  72057. }
  72058. }
  72059. }
  72060. /*
  72061. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  72062. ** attached database. Otherwise, invoke it for the database named zDb only.
  72063. */
  72064. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  72065. sqlite3 *db = pParse->db;
  72066. int i;
  72067. for(i=0; i<db->nDb; i++){
  72068. Db *pDb = &db->aDb[i];
  72069. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  72070. sqlite3CodeVerifySchema(pParse, i);
  72071. }
  72072. }
  72073. }
  72074. /*
  72075. ** Generate VDBE code that prepares for doing an operation that
  72076. ** might change the database.
  72077. **
  72078. ** This routine starts a new transaction if we are not already within
  72079. ** a transaction. If we are already within a transaction, then a checkpoint
  72080. ** is set if the setStatement parameter is true. A checkpoint should
  72081. ** be set for operations that might fail (due to a constraint) part of
  72082. ** the way through and which will need to undo some writes without having to
  72083. ** rollback the whole transaction. For operations where all constraints
  72084. ** can be checked before any changes are made to the database, it is never
  72085. ** necessary to undo a write and the checkpoint should not be set.
  72086. */
  72087. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  72088. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72089. sqlite3CodeVerifySchema(pParse, iDb);
  72090. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  72091. pToplevel->isMultiWrite |= setStatement;
  72092. }
  72093. /*
  72094. ** Indicate that the statement currently under construction might write
  72095. ** more than one entry (example: deleting one row then inserting another,
  72096. ** inserting multiple rows in a table, or inserting a row and index entries.)
  72097. ** If an abort occurs after some of these writes have completed, then it will
  72098. ** be necessary to undo the completed writes.
  72099. */
  72100. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  72101. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72102. pToplevel->isMultiWrite = 1;
  72103. }
  72104. /*
  72105. ** The code generator calls this routine if is discovers that it is
  72106. ** possible to abort a statement prior to completion. In order to
  72107. ** perform this abort without corrupting the database, we need to make
  72108. ** sure that the statement is protected by a statement transaction.
  72109. **
  72110. ** Technically, we only need to set the mayAbort flag if the
  72111. ** isMultiWrite flag was previously set. There is a time dependency
  72112. ** such that the abort must occur after the multiwrite. This makes
  72113. ** some statements involving the REPLACE conflict resolution algorithm
  72114. ** go a little faster. But taking advantage of this time dependency
  72115. ** makes it more difficult to prove that the code is correct (in
  72116. ** particular, it prevents us from writing an effective
  72117. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  72118. ** to take the safe route and skip the optimization.
  72119. */
  72120. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  72121. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72122. pToplevel->mayAbort = 1;
  72123. }
  72124. /*
  72125. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  72126. ** error. The onError parameter determines which (if any) of the statement
  72127. ** and/or current transaction is rolled back.
  72128. */
  72129. SQLITE_PRIVATE void sqlite3HaltConstraint(
  72130. Parse *pParse, /* Parsing context */
  72131. int errCode, /* extended error code */
  72132. int onError, /* Constraint type */
  72133. char *p4, /* Error message */
  72134. int p4type /* P4_STATIC or P4_TRANSIENT */
  72135. ){
  72136. Vdbe *v = sqlite3GetVdbe(pParse);
  72137. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  72138. if( onError==OE_Abort ){
  72139. sqlite3MayAbort(pParse);
  72140. }
  72141. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  72142. }
  72143. /*
  72144. ** Check to see if pIndex uses the collating sequence pColl. Return
  72145. ** true if it does and false if it does not.
  72146. */
  72147. #ifndef SQLITE_OMIT_REINDEX
  72148. static int collationMatch(const char *zColl, Index *pIndex){
  72149. int i;
  72150. assert( zColl!=0 );
  72151. for(i=0; i<pIndex->nColumn; i++){
  72152. const char *z = pIndex->azColl[i];
  72153. assert( z!=0 );
  72154. if( 0==sqlite3StrICmp(z, zColl) ){
  72155. return 1;
  72156. }
  72157. }
  72158. return 0;
  72159. }
  72160. #endif
  72161. /*
  72162. ** Recompute all indices of pTab that use the collating sequence pColl.
  72163. ** If pColl==0 then recompute all indices of pTab.
  72164. */
  72165. #ifndef SQLITE_OMIT_REINDEX
  72166. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  72167. Index *pIndex; /* An index associated with pTab */
  72168. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  72169. if( zColl==0 || collationMatch(zColl, pIndex) ){
  72170. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  72171. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72172. sqlite3RefillIndex(pParse, pIndex, -1);
  72173. }
  72174. }
  72175. }
  72176. #endif
  72177. /*
  72178. ** Recompute all indices of all tables in all databases where the
  72179. ** indices use the collating sequence pColl. If pColl==0 then recompute
  72180. ** all indices everywhere.
  72181. */
  72182. #ifndef SQLITE_OMIT_REINDEX
  72183. static void reindexDatabases(Parse *pParse, char const *zColl){
  72184. Db *pDb; /* A single database */
  72185. int iDb; /* The database index number */
  72186. sqlite3 *db = pParse->db; /* The database connection */
  72187. HashElem *k; /* For looping over tables in pDb */
  72188. Table *pTab; /* A table in the database */
  72189. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  72190. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  72191. assert( pDb!=0 );
  72192. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  72193. pTab = (Table*)sqliteHashData(k);
  72194. reindexTable(pParse, pTab, zColl);
  72195. }
  72196. }
  72197. }
  72198. #endif
  72199. /*
  72200. ** Generate code for the REINDEX command.
  72201. **
  72202. ** REINDEX -- 1
  72203. ** REINDEX <collation> -- 2
  72204. ** REINDEX ?<database>.?<tablename> -- 3
  72205. ** REINDEX ?<database>.?<indexname> -- 4
  72206. **
  72207. ** Form 1 causes all indices in all attached databases to be rebuilt.
  72208. ** Form 2 rebuilds all indices in all databases that use the named
  72209. ** collating function. Forms 3 and 4 rebuild the named index or all
  72210. ** indices associated with the named table.
  72211. */
  72212. #ifndef SQLITE_OMIT_REINDEX
  72213. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  72214. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  72215. char *z; /* Name of a table or index */
  72216. const char *zDb; /* Name of the database */
  72217. Table *pTab; /* A table in the database */
  72218. Index *pIndex; /* An index associated with pTab */
  72219. int iDb; /* The database index number */
  72220. sqlite3 *db = pParse->db; /* The database connection */
  72221. Token *pObjName; /* Name of the table or index to be reindexed */
  72222. /* Read the database schema. If an error occurs, leave an error message
  72223. ** and code in pParse and return NULL. */
  72224. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  72225. return;
  72226. }
  72227. if( pName1==0 ){
  72228. reindexDatabases(pParse, 0);
  72229. return;
  72230. }else if( NEVER(pName2==0) || pName2->z==0 ){
  72231. char *zColl;
  72232. assert( pName1->z );
  72233. zColl = sqlite3NameFromToken(pParse->db, pName1);
  72234. if( !zColl ) return;
  72235. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  72236. if( pColl ){
  72237. reindexDatabases(pParse, zColl);
  72238. sqlite3DbFree(db, zColl);
  72239. return;
  72240. }
  72241. sqlite3DbFree(db, zColl);
  72242. }
  72243. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  72244. if( iDb<0 ) return;
  72245. z = sqlite3NameFromToken(db, pObjName);
  72246. if( z==0 ) return;
  72247. zDb = db->aDb[iDb].zName;
  72248. pTab = sqlite3FindTable(db, z, zDb);
  72249. if( pTab ){
  72250. reindexTable(pParse, pTab, 0);
  72251. sqlite3DbFree(db, z);
  72252. return;
  72253. }
  72254. pIndex = sqlite3FindIndex(db, z, zDb);
  72255. sqlite3DbFree(db, z);
  72256. if( pIndex ){
  72257. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72258. sqlite3RefillIndex(pParse, pIndex, -1);
  72259. return;
  72260. }
  72261. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  72262. }
  72263. #endif
  72264. /*
  72265. ** Return a dynamicly allocated KeyInfo structure that can be used
  72266. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  72267. **
  72268. ** If successful, a pointer to the new structure is returned. In this case
  72269. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  72270. ** pointer. If an error occurs (out of memory or missing collation
  72271. ** sequence), NULL is returned and the state of pParse updated to reflect
  72272. ** the error.
  72273. */
  72274. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  72275. int i;
  72276. int nCol = pIdx->nColumn;
  72277. KeyInfo *pKey;
  72278. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  72279. if( pKey ){
  72280. for(i=0; i<nCol; i++){
  72281. char *zColl = pIdx->azColl[i];
  72282. assert( zColl );
  72283. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  72284. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  72285. }
  72286. }
  72287. if( pParse->nErr ){
  72288. sqlite3DbFree(pParse->db, pKey);
  72289. pKey = 0;
  72290. }
  72291. return pKey;
  72292. }
  72293. /************** End of build.c ***********************************************/
  72294. /************** Begin file callback.c ****************************************/
  72295. /*
  72296. ** 2005 May 23
  72297. **
  72298. ** The author disclaims copyright to this source code. In place of
  72299. ** a legal notice, here is a blessing:
  72300. **
  72301. ** May you do good and not evil.
  72302. ** May you find forgiveness for yourself and forgive others.
  72303. ** May you share freely, never taking more than you give.
  72304. **
  72305. *************************************************************************
  72306. **
  72307. ** This file contains functions used to access the internal hash tables
  72308. ** of user defined functions and collation sequences.
  72309. */
  72310. /*
  72311. ** Invoke the 'collation needed' callback to request a collation sequence
  72312. ** in the encoding enc of name zName, length nName.
  72313. */
  72314. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  72315. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  72316. if( db->xCollNeeded ){
  72317. char *zExternal = sqlite3DbStrDup(db, zName);
  72318. if( !zExternal ) return;
  72319. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  72320. sqlite3DbFree(db, zExternal);
  72321. }
  72322. #ifndef SQLITE_OMIT_UTF16
  72323. if( db->xCollNeeded16 ){
  72324. char const *zExternal;
  72325. sqlite3_value *pTmp = sqlite3ValueNew(db);
  72326. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  72327. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  72328. if( zExternal ){
  72329. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  72330. }
  72331. sqlite3ValueFree(pTmp);
  72332. }
  72333. #endif
  72334. }
  72335. /*
  72336. ** This routine is called if the collation factory fails to deliver a
  72337. ** collation function in the best encoding but there may be other versions
  72338. ** of this collation function (for other text encodings) available. Use one
  72339. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  72340. ** possible.
  72341. */
  72342. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  72343. CollSeq *pColl2;
  72344. char *z = pColl->zName;
  72345. int i;
  72346. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  72347. for(i=0; i<3; i++){
  72348. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  72349. if( pColl2->xCmp!=0 ){
  72350. memcpy(pColl, pColl2, sizeof(CollSeq));
  72351. pColl->xDel = 0; /* Do not copy the destructor */
  72352. return SQLITE_OK;
  72353. }
  72354. }
  72355. return SQLITE_ERROR;
  72356. }
  72357. /*
  72358. ** This function is responsible for invoking the collation factory callback
  72359. ** or substituting a collation sequence of a different encoding when the
  72360. ** requested collation sequence is not available in the desired encoding.
  72361. **
  72362. ** If it is not NULL, then pColl must point to the database native encoding
  72363. ** collation sequence with name zName, length nName.
  72364. **
  72365. ** The return value is either the collation sequence to be used in database
  72366. ** db for collation type name zName, length nName, or NULL, if no collation
  72367. ** sequence can be found. If no collation is found, leave an error message.
  72368. **
  72369. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  72370. */
  72371. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  72372. Parse *pParse, /* Parsing context */
  72373. u8 enc, /* The desired encoding for the collating sequence */
  72374. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  72375. const char *zName /* Collating sequence name */
  72376. ){
  72377. CollSeq *p;
  72378. sqlite3 *db = pParse->db;
  72379. p = pColl;
  72380. if( !p ){
  72381. p = sqlite3FindCollSeq(db, enc, zName, 0);
  72382. }
  72383. if( !p || !p->xCmp ){
  72384. /* No collation sequence of this type for this encoding is registered.
  72385. ** Call the collation factory to see if it can supply us with one.
  72386. */
  72387. callCollNeeded(db, enc, zName);
  72388. p = sqlite3FindCollSeq(db, enc, zName, 0);
  72389. }
  72390. if( p && !p->xCmp && synthCollSeq(db, p) ){
  72391. p = 0;
  72392. }
  72393. assert( !p || p->xCmp );
  72394. if( p==0 ){
  72395. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  72396. }
  72397. return p;
  72398. }
  72399. /*
  72400. ** This routine is called on a collation sequence before it is used to
  72401. ** check that it is defined. An undefined collation sequence exists when
  72402. ** a database is loaded that contains references to collation sequences
  72403. ** that have not been defined by sqlite3_create_collation() etc.
  72404. **
  72405. ** If required, this routine calls the 'collation needed' callback to
  72406. ** request a definition of the collating sequence. If this doesn't work,
  72407. ** an equivalent collating sequence that uses a text encoding different
  72408. ** from the main database is substituted, if one is available.
  72409. */
  72410. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  72411. if( pColl ){
  72412. const char *zName = pColl->zName;
  72413. sqlite3 *db = pParse->db;
  72414. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  72415. if( !p ){
  72416. return SQLITE_ERROR;
  72417. }
  72418. assert( p==pColl );
  72419. }
  72420. return SQLITE_OK;
  72421. }
  72422. /*
  72423. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  72424. ** specified by zName and nName is not found and parameter 'create' is
  72425. ** true, then create a new entry. Otherwise return NULL.
  72426. **
  72427. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  72428. ** array of three CollSeq structures. The first is the collation sequence
  72429. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  72430. **
  72431. ** Stored immediately after the three collation sequences is a copy of
  72432. ** the collation sequence name. A pointer to this string is stored in
  72433. ** each collation sequence structure.
  72434. */
  72435. static CollSeq *findCollSeqEntry(
  72436. sqlite3 *db, /* Database connection */
  72437. const char *zName, /* Name of the collating sequence */
  72438. int create /* Create a new entry if true */
  72439. ){
  72440. CollSeq *pColl;
  72441. int nName = sqlite3Strlen30(zName);
  72442. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  72443. if( 0==pColl && create ){
  72444. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  72445. if( pColl ){
  72446. CollSeq *pDel = 0;
  72447. pColl[0].zName = (char*)&pColl[3];
  72448. pColl[0].enc = SQLITE_UTF8;
  72449. pColl[1].zName = (char*)&pColl[3];
  72450. pColl[1].enc = SQLITE_UTF16LE;
  72451. pColl[2].zName = (char*)&pColl[3];
  72452. pColl[2].enc = SQLITE_UTF16BE;
  72453. memcpy(pColl[0].zName, zName, nName);
  72454. pColl[0].zName[nName] = 0;
  72455. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  72456. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  72457. ** return the pColl pointer to be deleted (because it wasn't added
  72458. ** to the hash table).
  72459. */
  72460. assert( pDel==0 || pDel==pColl );
  72461. if( pDel!=0 ){
  72462. db->mallocFailed = 1;
  72463. sqlite3DbFree(db, pDel);
  72464. pColl = 0;
  72465. }
  72466. }
  72467. }
  72468. return pColl;
  72469. }
  72470. /*
  72471. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  72472. ** Return the CollSeq* pointer for the collation sequence named zName
  72473. ** for the encoding 'enc' from the database 'db'.
  72474. **
  72475. ** If the entry specified is not found and 'create' is true, then create a
  72476. ** new entry. Otherwise return NULL.
  72477. **
  72478. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  72479. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  72480. ** if necessary and generates an error message if the collating sequence
  72481. ** cannot be found.
  72482. **
  72483. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  72484. */
  72485. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  72486. sqlite3 *db,
  72487. u8 enc,
  72488. const char *zName,
  72489. int create
  72490. ){
  72491. CollSeq *pColl;
  72492. if( zName ){
  72493. pColl = findCollSeqEntry(db, zName, create);
  72494. }else{
  72495. pColl = db->pDfltColl;
  72496. }
  72497. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  72498. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  72499. if( pColl ) pColl += enc-1;
  72500. return pColl;
  72501. }
  72502. /* During the search for the best function definition, this procedure
  72503. ** is called to test how well the function passed as the first argument
  72504. ** matches the request for a function with nArg arguments in a system
  72505. ** that uses encoding enc. The value returned indicates how well the
  72506. ** request is matched. A higher value indicates a better match.
  72507. **
  72508. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  72509. ** is also -1. In other words, we are searching for a function that
  72510. ** takes a variable number of arguments.
  72511. **
  72512. ** If nArg is -2 that means that we are searching for any function
  72513. ** regardless of the number of arguments it uses, so return a positive
  72514. ** match score for any
  72515. **
  72516. ** The returned value is always between 0 and 6, as follows:
  72517. **
  72518. ** 0: Not a match.
  72519. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  72520. ** 2: UTF16 byte order change required and function takes any number of args.
  72521. ** 3: encoding matches and function takes any number of arguments
  72522. ** 4: UTF8/16 conversion required - argument count matches exactly
  72523. ** 5: UTF16 byte order conversion required - argument count matches exactly
  72524. ** 6: Perfect match: encoding and argument count match exactly.
  72525. **
  72526. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  72527. ** a perfect match and any function with both xStep and xFunc NULL is
  72528. ** a non-match.
  72529. */
  72530. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  72531. static int matchQuality(
  72532. FuncDef *p, /* The function we are evaluating for match quality */
  72533. int nArg, /* Desired number of arguments. (-1)==any */
  72534. u8 enc /* Desired text encoding */
  72535. ){
  72536. int match;
  72537. /* nArg of -2 is a special case */
  72538. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  72539. /* Wrong number of arguments means "no match" */
  72540. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  72541. /* Give a better score to a function with a specific number of arguments
  72542. ** than to function that accepts any number of arguments. */
  72543. if( p->nArg==nArg ){
  72544. match = 4;
  72545. }else{
  72546. match = 1;
  72547. }
  72548. /* Bonus points if the text encoding matches */
  72549. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  72550. match += 2; /* Exact encoding match */
  72551. }else if( (enc & p->funcFlags & 2)!=0 ){
  72552. match += 1; /* Both are UTF16, but with different byte orders */
  72553. }
  72554. return match;
  72555. }
  72556. /*
  72557. ** Search a FuncDefHash for a function with the given name. Return
  72558. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  72559. */
  72560. static FuncDef *functionSearch(
  72561. FuncDefHash *pHash, /* Hash table to search */
  72562. int h, /* Hash of the name */
  72563. const char *zFunc, /* Name of function */
  72564. int nFunc /* Number of bytes in zFunc */
  72565. ){
  72566. FuncDef *p;
  72567. for(p=pHash->a[h]; p; p=p->pHash){
  72568. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  72569. return p;
  72570. }
  72571. }
  72572. return 0;
  72573. }
  72574. /*
  72575. ** Insert a new FuncDef into a FuncDefHash hash table.
  72576. */
  72577. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  72578. FuncDefHash *pHash, /* The hash table into which to insert */
  72579. FuncDef *pDef /* The function definition to insert */
  72580. ){
  72581. FuncDef *pOther;
  72582. int nName = sqlite3Strlen30(pDef->zName);
  72583. u8 c1 = (u8)pDef->zName[0];
  72584. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  72585. pOther = functionSearch(pHash, h, pDef->zName, nName);
  72586. if( pOther ){
  72587. assert( pOther!=pDef && pOther->pNext!=pDef );
  72588. pDef->pNext = pOther->pNext;
  72589. pOther->pNext = pDef;
  72590. }else{
  72591. pDef->pNext = 0;
  72592. pDef->pHash = pHash->a[h];
  72593. pHash->a[h] = pDef;
  72594. }
  72595. }
  72596. /*
  72597. ** Locate a user function given a name, a number of arguments and a flag
  72598. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  72599. ** pointer to the FuncDef structure that defines that function, or return
  72600. ** NULL if the function does not exist.
  72601. **
  72602. ** If the createFlag argument is true, then a new (blank) FuncDef
  72603. ** structure is created and liked into the "db" structure if a
  72604. ** no matching function previously existed.
  72605. **
  72606. ** If nArg is -2, then the first valid function found is returned. A
  72607. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  72608. ** case is used to see if zName is a valid function name for some number
  72609. ** of arguments. If nArg is -2, then createFlag must be 0.
  72610. **
  72611. ** If createFlag is false, then a function with the required name and
  72612. ** number of arguments may be returned even if the eTextRep flag does not
  72613. ** match that requested.
  72614. */
  72615. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  72616. sqlite3 *db, /* An open database */
  72617. const char *zName, /* Name of the function. Not null-terminated */
  72618. int nName, /* Number of characters in the name */
  72619. int nArg, /* Number of arguments. -1 means any number */
  72620. u8 enc, /* Preferred text encoding */
  72621. u8 createFlag /* Create new entry if true and does not otherwise exist */
  72622. ){
  72623. FuncDef *p; /* Iterator variable */
  72624. FuncDef *pBest = 0; /* Best match found so far */
  72625. int bestScore = 0; /* Score of best match */
  72626. int h; /* Hash value */
  72627. assert( nArg>=(-2) );
  72628. assert( nArg>=(-1) || createFlag==0 );
  72629. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  72630. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  72631. /* First search for a match amongst the application-defined functions.
  72632. */
  72633. p = functionSearch(&db->aFunc, h, zName, nName);
  72634. while( p ){
  72635. int score = matchQuality(p, nArg, enc);
  72636. if( score>bestScore ){
  72637. pBest = p;
  72638. bestScore = score;
  72639. }
  72640. p = p->pNext;
  72641. }
  72642. /* If no match is found, search the built-in functions.
  72643. **
  72644. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  72645. ** functions even if a prior app-defined function was found. And give
  72646. ** priority to built-in functions.
  72647. **
  72648. ** Except, if createFlag is true, that means that we are trying to
  72649. ** install a new function. Whatever FuncDef structure is returned it will
  72650. ** have fields overwritten with new information appropriate for the
  72651. ** new function. But the FuncDefs for built-in functions are read-only.
  72652. ** So we must not search for built-ins when creating a new function.
  72653. */
  72654. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  72655. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  72656. bestScore = 0;
  72657. p = functionSearch(pHash, h, zName, nName);
  72658. while( p ){
  72659. int score = matchQuality(p, nArg, enc);
  72660. if( score>bestScore ){
  72661. pBest = p;
  72662. bestScore = score;
  72663. }
  72664. p = p->pNext;
  72665. }
  72666. }
  72667. /* If the createFlag parameter is true and the search did not reveal an
  72668. ** exact match for the name, number of arguments and encoding, then add a
  72669. ** new entry to the hash table and return it.
  72670. */
  72671. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  72672. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  72673. pBest->zName = (char *)&pBest[1];
  72674. pBest->nArg = (u16)nArg;
  72675. pBest->funcFlags = enc;
  72676. memcpy(pBest->zName, zName, nName);
  72677. pBest->zName[nName] = 0;
  72678. sqlite3FuncDefInsert(&db->aFunc, pBest);
  72679. }
  72680. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  72681. return pBest;
  72682. }
  72683. return 0;
  72684. }
  72685. /*
  72686. ** Free all resources held by the schema structure. The void* argument points
  72687. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  72688. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  72689. ** of the schema hash tables).
  72690. **
  72691. ** The Schema.cache_size variable is not cleared.
  72692. */
  72693. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  72694. Hash temp1;
  72695. Hash temp2;
  72696. HashElem *pElem;
  72697. Schema *pSchema = (Schema *)p;
  72698. temp1 = pSchema->tblHash;
  72699. temp2 = pSchema->trigHash;
  72700. sqlite3HashInit(&pSchema->trigHash);
  72701. sqlite3HashClear(&pSchema->idxHash);
  72702. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  72703. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  72704. }
  72705. sqlite3HashClear(&temp2);
  72706. sqlite3HashInit(&pSchema->tblHash);
  72707. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  72708. Table *pTab = sqliteHashData(pElem);
  72709. sqlite3DeleteTable(0, pTab);
  72710. }
  72711. sqlite3HashClear(&temp1);
  72712. sqlite3HashClear(&pSchema->fkeyHash);
  72713. pSchema->pSeqTab = 0;
  72714. if( pSchema->flags & DB_SchemaLoaded ){
  72715. pSchema->iGeneration++;
  72716. pSchema->flags &= ~DB_SchemaLoaded;
  72717. }
  72718. }
  72719. /*
  72720. ** Find and return the schema associated with a BTree. Create
  72721. ** a new one if necessary.
  72722. */
  72723. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  72724. Schema * p;
  72725. if( pBt ){
  72726. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  72727. }else{
  72728. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  72729. }
  72730. if( !p ){
  72731. db->mallocFailed = 1;
  72732. }else if ( 0==p->file_format ){
  72733. sqlite3HashInit(&p->tblHash);
  72734. sqlite3HashInit(&p->idxHash);
  72735. sqlite3HashInit(&p->trigHash);
  72736. sqlite3HashInit(&p->fkeyHash);
  72737. p->enc = SQLITE_UTF8;
  72738. }
  72739. return p;
  72740. }
  72741. /************** End of callback.c ********************************************/
  72742. /************** Begin file delete.c ******************************************/
  72743. /*
  72744. ** 2001 September 15
  72745. **
  72746. ** The author disclaims copyright to this source code. In place of
  72747. ** a legal notice, here is a blessing:
  72748. **
  72749. ** May you do good and not evil.
  72750. ** May you find forgiveness for yourself and forgive others.
  72751. ** May you share freely, never taking more than you give.
  72752. **
  72753. *************************************************************************
  72754. ** This file contains C code routines that are called by the parser
  72755. ** in order to generate code for DELETE FROM statements.
  72756. */
  72757. /*
  72758. ** While a SrcList can in general represent multiple tables and subqueries
  72759. ** (as in the FROM clause of a SELECT statement) in this case it contains
  72760. ** the name of a single table, as one might find in an INSERT, DELETE,
  72761. ** or UPDATE statement. Look up that table in the symbol table and
  72762. ** return a pointer. Set an error message and return NULL if the table
  72763. ** name is not found or if any other error occurs.
  72764. **
  72765. ** The following fields are initialized appropriate in pSrc:
  72766. **
  72767. ** pSrc->a[0].pTab Pointer to the Table object
  72768. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  72769. **
  72770. */
  72771. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  72772. struct SrcList_item *pItem = pSrc->a;
  72773. Table *pTab;
  72774. assert( pItem && pSrc->nSrc==1 );
  72775. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  72776. sqlite3DeleteTable(pParse->db, pItem->pTab);
  72777. pItem->pTab = pTab;
  72778. if( pTab ){
  72779. pTab->nRef++;
  72780. }
  72781. if( sqlite3IndexedByLookup(pParse, pItem) ){
  72782. pTab = 0;
  72783. }
  72784. return pTab;
  72785. }
  72786. /*
  72787. ** Check to make sure the given table is writable. If it is not
  72788. ** writable, generate an error message and return 1. If it is
  72789. ** writable return 0;
  72790. */
  72791. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  72792. /* A table is not writable under the following circumstances:
  72793. **
  72794. ** 1) It is a virtual table and no implementation of the xUpdate method
  72795. ** has been provided, or
  72796. ** 2) It is a system table (i.e. sqlite_master), this call is not
  72797. ** part of a nested parse and writable_schema pragma has not
  72798. ** been specified.
  72799. **
  72800. ** In either case leave an error message in pParse and return non-zero.
  72801. */
  72802. if( ( IsVirtual(pTab)
  72803. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  72804. || ( (pTab->tabFlags & TF_Readonly)!=0
  72805. && (pParse->db->flags & SQLITE_WriteSchema)==0
  72806. && pParse->nested==0 )
  72807. ){
  72808. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  72809. return 1;
  72810. }
  72811. #ifndef SQLITE_OMIT_VIEW
  72812. if( !viewOk && pTab->pSelect ){
  72813. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  72814. return 1;
  72815. }
  72816. #endif
  72817. return 0;
  72818. }
  72819. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  72820. /*
  72821. ** Evaluate a view and store its result in an ephemeral table. The
  72822. ** pWhere argument is an optional WHERE clause that restricts the
  72823. ** set of rows in the view that are to be added to the ephemeral table.
  72824. */
  72825. SQLITE_PRIVATE void sqlite3MaterializeView(
  72826. Parse *pParse, /* Parsing context */
  72827. Table *pView, /* View definition */
  72828. Expr *pWhere, /* Optional WHERE clause to be added */
  72829. int iCur /* Cursor number for ephemerial table */
  72830. ){
  72831. SelectDest dest;
  72832. Select *pSel;
  72833. SrcList *pFrom;
  72834. sqlite3 *db = pParse->db;
  72835. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  72836. pWhere = sqlite3ExprDup(db, pWhere, 0);
  72837. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  72838. if( pFrom ){
  72839. assert( pFrom->nSrc==1 );
  72840. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  72841. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  72842. assert( pFrom->a[0].pOn==0 );
  72843. assert( pFrom->a[0].pUsing==0 );
  72844. }
  72845. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  72846. if( pSel ) pSel->selFlags |= SF_Materialize;
  72847. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  72848. sqlite3Select(pParse, pSel, &dest);
  72849. sqlite3SelectDelete(db, pSel);
  72850. }
  72851. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  72852. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  72853. /*
  72854. ** Generate an expression tree to implement the WHERE, ORDER BY,
  72855. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  72856. **
  72857. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  72858. ** \__________________________/
  72859. ** pLimitWhere (pInClause)
  72860. */
  72861. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  72862. Parse *pParse, /* The parser context */
  72863. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  72864. Expr *pWhere, /* The WHERE clause. May be null */
  72865. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  72866. Expr *pLimit, /* The LIMIT clause. May be null */
  72867. Expr *pOffset, /* The OFFSET clause. May be null */
  72868. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  72869. ){
  72870. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  72871. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  72872. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  72873. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  72874. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  72875. Select *pSelect = NULL; /* Complete SELECT tree */
  72876. /* Check that there isn't an ORDER BY without a LIMIT clause.
  72877. */
  72878. if( pOrderBy && (pLimit == 0) ) {
  72879. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  72880. goto limit_where_cleanup_2;
  72881. }
  72882. /* We only need to generate a select expression if there
  72883. ** is a limit/offset term to enforce.
  72884. */
  72885. if( pLimit == 0 ) {
  72886. /* if pLimit is null, pOffset will always be null as well. */
  72887. assert( pOffset == 0 );
  72888. return pWhere;
  72889. }
  72890. /* Generate a select expression tree to enforce the limit/offset
  72891. ** term for the DELETE or UPDATE statement. For example:
  72892. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  72893. ** becomes:
  72894. ** DELETE FROM table_a WHERE rowid IN (
  72895. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  72896. ** );
  72897. */
  72898. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  72899. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  72900. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  72901. if( pEList == 0 ) goto limit_where_cleanup_2;
  72902. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  72903. ** and the SELECT subtree. */
  72904. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  72905. if( pSelectSrc == 0 ) {
  72906. sqlite3ExprListDelete(pParse->db, pEList);
  72907. goto limit_where_cleanup_2;
  72908. }
  72909. /* generate the SELECT expression tree. */
  72910. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  72911. pOrderBy,0,pLimit,pOffset);
  72912. if( pSelect == 0 ) return 0;
  72913. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  72914. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  72915. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  72916. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  72917. if( pInClause == 0 ) goto limit_where_cleanup_1;
  72918. pInClause->x.pSelect = pSelect;
  72919. pInClause->flags |= EP_xIsSelect;
  72920. sqlite3ExprSetHeight(pParse, pInClause);
  72921. return pInClause;
  72922. /* something went wrong. clean up anything allocated. */
  72923. limit_where_cleanup_1:
  72924. sqlite3SelectDelete(pParse->db, pSelect);
  72925. return 0;
  72926. limit_where_cleanup_2:
  72927. sqlite3ExprDelete(pParse->db, pWhere);
  72928. sqlite3ExprListDelete(pParse->db, pOrderBy);
  72929. sqlite3ExprDelete(pParse->db, pLimit);
  72930. sqlite3ExprDelete(pParse->db, pOffset);
  72931. return 0;
  72932. }
  72933. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  72934. /*
  72935. ** Generate code for a DELETE FROM statement.
  72936. **
  72937. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  72938. ** \________/ \________________/
  72939. ** pTabList pWhere
  72940. */
  72941. SQLITE_PRIVATE void sqlite3DeleteFrom(
  72942. Parse *pParse, /* The parser context */
  72943. SrcList *pTabList, /* The table from which we should delete things */
  72944. Expr *pWhere /* The WHERE clause. May be null */
  72945. ){
  72946. Vdbe *v; /* The virtual database engine */
  72947. Table *pTab; /* The table from which records will be deleted */
  72948. const char *zDb; /* Name of database holding pTab */
  72949. int end, addr = 0; /* A couple addresses of generated code */
  72950. int i; /* Loop counter */
  72951. WhereInfo *pWInfo; /* Information about the WHERE clause */
  72952. Index *pIdx; /* For looping over indices of the table */
  72953. int iCur; /* VDBE Cursor number for pTab */
  72954. sqlite3 *db; /* Main database structure */
  72955. AuthContext sContext; /* Authorization context */
  72956. NameContext sNC; /* Name context to resolve expressions in */
  72957. int iDb; /* Database number */
  72958. int memCnt = -1; /* Memory cell used for change counting */
  72959. int rcauth; /* Value returned by authorization callback */
  72960. #ifndef SQLITE_OMIT_TRIGGER
  72961. int isView; /* True if attempting to delete from a view */
  72962. Trigger *pTrigger; /* List of table triggers, if required */
  72963. #endif
  72964. memset(&sContext, 0, sizeof(sContext));
  72965. db = pParse->db;
  72966. if( pParse->nErr || db->mallocFailed ){
  72967. goto delete_from_cleanup;
  72968. }
  72969. assert( pTabList->nSrc==1 );
  72970. /* Locate the table which we want to delete. This table has to be
  72971. ** put in an SrcList structure because some of the subroutines we
  72972. ** will be calling are designed to work with multiple tables and expect
  72973. ** an SrcList* parameter instead of just a Table* parameter.
  72974. */
  72975. pTab = sqlite3SrcListLookup(pParse, pTabList);
  72976. if( pTab==0 ) goto delete_from_cleanup;
  72977. /* Figure out if we have any triggers and if the table being
  72978. ** deleted from is a view
  72979. */
  72980. #ifndef SQLITE_OMIT_TRIGGER
  72981. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  72982. isView = pTab->pSelect!=0;
  72983. #else
  72984. # define pTrigger 0
  72985. # define isView 0
  72986. #endif
  72987. #ifdef SQLITE_OMIT_VIEW
  72988. # undef isView
  72989. # define isView 0
  72990. #endif
  72991. /* If pTab is really a view, make sure it has been initialized.
  72992. */
  72993. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  72994. goto delete_from_cleanup;
  72995. }
  72996. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  72997. goto delete_from_cleanup;
  72998. }
  72999. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73000. assert( iDb<db->nDb );
  73001. zDb = db->aDb[iDb].zName;
  73002. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  73003. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  73004. if( rcauth==SQLITE_DENY ){
  73005. goto delete_from_cleanup;
  73006. }
  73007. assert(!isView || pTrigger);
  73008. /* Assign cursor number to the table and all its indices.
  73009. */
  73010. assert( pTabList->nSrc==1 );
  73011. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  73012. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73013. pParse->nTab++;
  73014. }
  73015. /* Start the view context
  73016. */
  73017. if( isView ){
  73018. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  73019. }
  73020. /* Begin generating code.
  73021. */
  73022. v = sqlite3GetVdbe(pParse);
  73023. if( v==0 ){
  73024. goto delete_from_cleanup;
  73025. }
  73026. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  73027. sqlite3BeginWriteOperation(pParse, 1, iDb);
  73028. /* If we are trying to delete from a view, realize that view into
  73029. ** a ephemeral table.
  73030. */
  73031. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  73032. if( isView ){
  73033. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  73034. }
  73035. #endif
  73036. /* Resolve the column names in the WHERE clause.
  73037. */
  73038. memset(&sNC, 0, sizeof(sNC));
  73039. sNC.pParse = pParse;
  73040. sNC.pSrcList = pTabList;
  73041. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  73042. goto delete_from_cleanup;
  73043. }
  73044. /* Initialize the counter of the number of rows deleted, if
  73045. ** we are counting rows.
  73046. */
  73047. if( db->flags & SQLITE_CountRows ){
  73048. memCnt = ++pParse->nMem;
  73049. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  73050. }
  73051. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  73052. /* Special case: A DELETE without a WHERE clause deletes everything.
  73053. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  73054. ** this optimization caused the row change count (the value returned by
  73055. ** API function sqlite3_count_changes) to be set incorrectly. */
  73056. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  73057. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  73058. ){
  73059. assert( !isView );
  73060. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  73061. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  73062. pTab->zName, P4_STATIC);
  73063. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73064. assert( pIdx->pSchema==pTab->pSchema );
  73065. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  73066. }
  73067. }else
  73068. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  73069. /* The usual case: There is a WHERE clause so we have to scan through
  73070. ** the table and pick which records to delete.
  73071. */
  73072. {
  73073. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  73074. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  73075. int regRowid; /* Actual register containing rowids */
  73076. /* Collect rowids of every row to be deleted.
  73077. */
  73078. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  73079. pWInfo = sqlite3WhereBegin(
  73080. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  73081. );
  73082. if( pWInfo==0 ) goto delete_from_cleanup;
  73083. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  73084. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  73085. if( db->flags & SQLITE_CountRows ){
  73086. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  73087. }
  73088. sqlite3WhereEnd(pWInfo);
  73089. /* Delete every item whose key was written to the list during the
  73090. ** database scan. We have to delete items after the scan is complete
  73091. ** because deleting an item can change the scan order. */
  73092. end = sqlite3VdbeMakeLabel(v);
  73093. /* Unless this is a view, open cursors for the table we are
  73094. ** deleting from and all its indices. If this is a view, then the
  73095. ** only effect this statement has is to fire the INSTEAD OF
  73096. ** triggers. */
  73097. if( !isView ){
  73098. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  73099. }
  73100. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  73101. /* Delete the row */
  73102. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73103. if( IsVirtual(pTab) ){
  73104. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  73105. sqlite3VtabMakeWritable(pParse, pTab);
  73106. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  73107. sqlite3VdbeChangeP5(v, OE_Abort);
  73108. sqlite3MayAbort(pParse);
  73109. }else
  73110. #endif
  73111. {
  73112. int count = (pParse->nested==0); /* True to count changes */
  73113. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  73114. }
  73115. /* End of the delete loop */
  73116. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  73117. sqlite3VdbeResolveLabel(v, end);
  73118. /* Close the cursors open on the table and its indexes. */
  73119. if( !isView && !IsVirtual(pTab) ){
  73120. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  73121. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  73122. }
  73123. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  73124. }
  73125. }
  73126. /* Update the sqlite_sequence table by storing the content of the
  73127. ** maximum rowid counter values recorded while inserting into
  73128. ** autoincrement tables.
  73129. */
  73130. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  73131. sqlite3AutoincrementEnd(pParse);
  73132. }
  73133. /* Return the number of rows that were deleted. If this routine is
  73134. ** generating code because of a call to sqlite3NestedParse(), do not
  73135. ** invoke the callback function.
  73136. */
  73137. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  73138. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  73139. sqlite3VdbeSetNumCols(v, 1);
  73140. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  73141. }
  73142. delete_from_cleanup:
  73143. sqlite3AuthContextPop(&sContext);
  73144. sqlite3SrcListDelete(db, pTabList);
  73145. sqlite3ExprDelete(db, pWhere);
  73146. return;
  73147. }
  73148. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  73149. ** thely may interfere with compilation of other functions in this file
  73150. ** (or in another file, if this file becomes part of the amalgamation). */
  73151. #ifdef isView
  73152. #undef isView
  73153. #endif
  73154. #ifdef pTrigger
  73155. #undef pTrigger
  73156. #endif
  73157. /*
  73158. ** This routine generates VDBE code that causes a single row of a
  73159. ** single table to be deleted.
  73160. **
  73161. ** The VDBE must be in a particular state when this routine is called.
  73162. ** These are the requirements:
  73163. **
  73164. ** 1. A read/write cursor pointing to pTab, the table containing the row
  73165. ** to be deleted, must be opened as cursor number $iCur.
  73166. **
  73167. ** 2. Read/write cursors for all indices of pTab must be open as
  73168. ** cursor number base+i for the i-th index.
  73169. **
  73170. ** 3. The record number of the row to be deleted must be stored in
  73171. ** memory cell iRowid.
  73172. **
  73173. ** This routine generates code to remove both the table record and all
  73174. ** index entries that point to that record.
  73175. */
  73176. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  73177. Parse *pParse, /* Parsing context */
  73178. Table *pTab, /* Table containing the row to be deleted */
  73179. int iCur, /* Cursor number for the table */
  73180. int iRowid, /* Memory cell that contains the rowid to delete */
  73181. int count, /* If non-zero, increment the row change counter */
  73182. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  73183. int onconf /* Default ON CONFLICT policy for triggers */
  73184. ){
  73185. Vdbe *v = pParse->pVdbe; /* Vdbe */
  73186. int iOld = 0; /* First register in OLD.* array */
  73187. int iLabel; /* Label resolved to end of generated code */
  73188. /* Vdbe is guaranteed to have been allocated by this stage. */
  73189. assert( v );
  73190. /* Seek cursor iCur to the row to delete. If this row no longer exists
  73191. ** (this can happen if a trigger program has already deleted it), do
  73192. ** not attempt to delete it or fire any DELETE triggers. */
  73193. iLabel = sqlite3VdbeMakeLabel(v);
  73194. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  73195. /* If there are any triggers to fire, allocate a range of registers to
  73196. ** use for the old.* references in the triggers. */
  73197. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  73198. u32 mask; /* Mask of OLD.* columns in use */
  73199. int iCol; /* Iterator used while populating OLD.* */
  73200. /* TODO: Could use temporary registers here. Also could attempt to
  73201. ** avoid copying the contents of the rowid register. */
  73202. mask = sqlite3TriggerColmask(
  73203. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  73204. );
  73205. mask |= sqlite3FkOldmask(pParse, pTab);
  73206. iOld = pParse->nMem+1;
  73207. pParse->nMem += (1 + pTab->nCol);
  73208. /* Populate the OLD.* pseudo-table register array. These values will be
  73209. ** used by any BEFORE and AFTER triggers that exist. */
  73210. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  73211. for(iCol=0; iCol<pTab->nCol; iCol++){
  73212. if( mask==0xffffffff || mask&(1<<iCol) ){
  73213. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  73214. }
  73215. }
  73216. /* Invoke BEFORE DELETE trigger programs. */
  73217. sqlite3CodeRowTrigger(pParse, pTrigger,
  73218. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  73219. );
  73220. /* Seek the cursor to the row to be deleted again. It may be that
  73221. ** the BEFORE triggers coded above have already removed the row
  73222. ** being deleted. Do not attempt to delete the row a second time, and
  73223. ** do not fire AFTER triggers. */
  73224. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  73225. /* Do FK processing. This call checks that any FK constraints that
  73226. ** refer to this table (i.e. constraints attached to other tables)
  73227. ** are not violated by deleting this row. */
  73228. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  73229. }
  73230. /* Delete the index and table entries. Skip this step if pTab is really
  73231. ** a view (in which case the only effect of the DELETE statement is to
  73232. ** fire the INSTEAD OF triggers). */
  73233. if( pTab->pSelect==0 ){
  73234. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  73235. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  73236. if( count ){
  73237. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  73238. }
  73239. }
  73240. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  73241. ** handle rows (possibly in other tables) that refer via a foreign key
  73242. ** to the row just deleted. */
  73243. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  73244. /* Invoke AFTER DELETE trigger programs. */
  73245. sqlite3CodeRowTrigger(pParse, pTrigger,
  73246. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  73247. );
  73248. /* Jump here if the row had already been deleted before any BEFORE
  73249. ** trigger programs were invoked. Or if a trigger program throws a
  73250. ** RAISE(IGNORE) exception. */
  73251. sqlite3VdbeResolveLabel(v, iLabel);
  73252. }
  73253. /*
  73254. ** This routine generates VDBE code that causes the deletion of all
  73255. ** index entries associated with a single row of a single table.
  73256. **
  73257. ** The VDBE must be in a particular state when this routine is called.
  73258. ** These are the requirements:
  73259. **
  73260. ** 1. A read/write cursor pointing to pTab, the table containing the row
  73261. ** to be deleted, must be opened as cursor number "iCur".
  73262. **
  73263. ** 2. Read/write cursors for all indices of pTab must be open as
  73264. ** cursor number iCur+i for the i-th index.
  73265. **
  73266. ** 3. The "iCur" cursor must be pointing to the row that is to be
  73267. ** deleted.
  73268. */
  73269. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  73270. Parse *pParse, /* Parsing and code generating context */
  73271. Table *pTab, /* Table containing the row to be deleted */
  73272. int iCur, /* Cursor number for the table */
  73273. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  73274. ){
  73275. int i;
  73276. Index *pIdx;
  73277. int r1;
  73278. int iPartIdxLabel;
  73279. Vdbe *v = pParse->pVdbe;
  73280. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  73281. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  73282. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  73283. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  73284. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  73285. }
  73286. }
  73287. /*
  73288. ** Generate code that will assemble an index key and put it in register
  73289. ** regOut. The key with be for index pIdx which is an index on pTab.
  73290. ** iCur is the index of a cursor open on the pTab table and pointing to
  73291. ** the entry that needs indexing.
  73292. **
  73293. ** Return a register number which is the first in a block of
  73294. ** registers that holds the elements of the index key. The
  73295. ** block of registers has already been deallocated by the time
  73296. ** this routine returns.
  73297. **
  73298. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  73299. ** to that label if pIdx is a partial index that should be skipped.
  73300. ** A partial index should be skipped if its WHERE clause evaluates
  73301. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  73302. ** will be set to zero which is an empty label that is ignored by
  73303. ** sqlite3VdbeResolveLabel().
  73304. */
  73305. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  73306. Parse *pParse, /* Parsing context */
  73307. Index *pIdx, /* The index for which to generate a key */
  73308. int iCur, /* Cursor number for the pIdx->pTable table */
  73309. int regOut, /* Write the new index key to this register */
  73310. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  73311. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  73312. ){
  73313. Vdbe *v = pParse->pVdbe;
  73314. int j;
  73315. Table *pTab = pIdx->pTable;
  73316. int regBase;
  73317. int nCol;
  73318. if( piPartIdxLabel ){
  73319. if( pIdx->pPartIdxWhere ){
  73320. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  73321. pParse->iPartIdxTab = iCur;
  73322. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  73323. SQLITE_JUMPIFNULL);
  73324. }else{
  73325. *piPartIdxLabel = 0;
  73326. }
  73327. }
  73328. nCol = pIdx->nColumn;
  73329. regBase = sqlite3GetTempRange(pParse, nCol+1);
  73330. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  73331. for(j=0; j<nCol; j++){
  73332. int idx = pIdx->aiColumn[j];
  73333. if( idx==pTab->iPKey ){
  73334. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  73335. }else{
  73336. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  73337. sqlite3ColumnDefault(v, pTab, idx, -1);
  73338. }
  73339. }
  73340. if( doMakeRec ){
  73341. const char *zAff;
  73342. if( pTab->pSelect
  73343. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  73344. ){
  73345. zAff = 0;
  73346. }else{
  73347. zAff = sqlite3IndexAffinityStr(v, pIdx);
  73348. }
  73349. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  73350. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  73351. }
  73352. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  73353. return regBase;
  73354. }
  73355. /************** End of delete.c **********************************************/
  73356. /************** Begin file func.c ********************************************/
  73357. /*
  73358. ** 2002 February 23
  73359. **
  73360. ** The author disclaims copyright to this source code. In place of
  73361. ** a legal notice, here is a blessing:
  73362. **
  73363. ** May you do good and not evil.
  73364. ** May you find forgiveness for yourself and forgive others.
  73365. ** May you share freely, never taking more than you give.
  73366. **
  73367. *************************************************************************
  73368. ** This file contains the C functions that implement various SQL
  73369. ** functions of SQLite.
  73370. **
  73371. ** There is only one exported symbol in this file - the function
  73372. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  73373. ** All other code has file scope.
  73374. */
  73375. /* #include <stdlib.h> */
  73376. /* #include <assert.h> */
  73377. /*
  73378. ** Return the collating function associated with a function.
  73379. */
  73380. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  73381. return context->pColl;
  73382. }
  73383. /*
  73384. ** Indicate that the accumulator load should be skipped on this
  73385. ** iteration of the aggregate loop.
  73386. */
  73387. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  73388. context->skipFlag = 1;
  73389. }
  73390. /*
  73391. ** Implementation of the non-aggregate min() and max() functions
  73392. */
  73393. static void minmaxFunc(
  73394. sqlite3_context *context,
  73395. int argc,
  73396. sqlite3_value **argv
  73397. ){
  73398. int i;
  73399. int mask; /* 0 for min() or 0xffffffff for max() */
  73400. int iBest;
  73401. CollSeq *pColl;
  73402. assert( argc>1 );
  73403. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  73404. pColl = sqlite3GetFuncCollSeq(context);
  73405. assert( pColl );
  73406. assert( mask==-1 || mask==0 );
  73407. iBest = 0;
  73408. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  73409. for(i=1; i<argc; i++){
  73410. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  73411. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  73412. testcase( mask==0 );
  73413. iBest = i;
  73414. }
  73415. }
  73416. sqlite3_result_value(context, argv[iBest]);
  73417. }
  73418. /*
  73419. ** Return the type of the argument.
  73420. */
  73421. static void typeofFunc(
  73422. sqlite3_context *context,
  73423. int NotUsed,
  73424. sqlite3_value **argv
  73425. ){
  73426. const char *z = 0;
  73427. UNUSED_PARAMETER(NotUsed);
  73428. switch( sqlite3_value_type(argv[0]) ){
  73429. case SQLITE_INTEGER: z = "integer"; break;
  73430. case SQLITE_TEXT: z = "text"; break;
  73431. case SQLITE_FLOAT: z = "real"; break;
  73432. case SQLITE_BLOB: z = "blob"; break;
  73433. default: z = "null"; break;
  73434. }
  73435. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  73436. }
  73437. /*
  73438. ** Implementation of the length() function
  73439. */
  73440. static void lengthFunc(
  73441. sqlite3_context *context,
  73442. int argc,
  73443. sqlite3_value **argv
  73444. ){
  73445. int len;
  73446. assert( argc==1 );
  73447. UNUSED_PARAMETER(argc);
  73448. switch( sqlite3_value_type(argv[0]) ){
  73449. case SQLITE_BLOB:
  73450. case SQLITE_INTEGER:
  73451. case SQLITE_FLOAT: {
  73452. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  73453. break;
  73454. }
  73455. case SQLITE_TEXT: {
  73456. const unsigned char *z = sqlite3_value_text(argv[0]);
  73457. if( z==0 ) return;
  73458. len = 0;
  73459. while( *z ){
  73460. len++;
  73461. SQLITE_SKIP_UTF8(z);
  73462. }
  73463. sqlite3_result_int(context, len);
  73464. break;
  73465. }
  73466. default: {
  73467. sqlite3_result_null(context);
  73468. break;
  73469. }
  73470. }
  73471. }
  73472. /*
  73473. ** Implementation of the abs() function.
  73474. **
  73475. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  73476. ** the numeric argument X.
  73477. */
  73478. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73479. assert( argc==1 );
  73480. UNUSED_PARAMETER(argc);
  73481. switch( sqlite3_value_type(argv[0]) ){
  73482. case SQLITE_INTEGER: {
  73483. i64 iVal = sqlite3_value_int64(argv[0]);
  73484. if( iVal<0 ){
  73485. if( (iVal<<1)==0 ){
  73486. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  73487. ** abs(X) throws an integer overflow error since there is no
  73488. ** equivalent positive 64-bit two complement value. */
  73489. sqlite3_result_error(context, "integer overflow", -1);
  73490. return;
  73491. }
  73492. iVal = -iVal;
  73493. }
  73494. sqlite3_result_int64(context, iVal);
  73495. break;
  73496. }
  73497. case SQLITE_NULL: {
  73498. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  73499. sqlite3_result_null(context);
  73500. break;
  73501. }
  73502. default: {
  73503. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  73504. ** something that can be converted into a number, we have:
  73505. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  73506. ** cannot be converted to a numeric value.
  73507. */
  73508. double rVal = sqlite3_value_double(argv[0]);
  73509. if( rVal<0 ) rVal = -rVal;
  73510. sqlite3_result_double(context, rVal);
  73511. break;
  73512. }
  73513. }
  73514. }
  73515. /*
  73516. ** Implementation of the instr() function.
  73517. **
  73518. ** instr(haystack,needle) finds the first occurrence of needle
  73519. ** in haystack and returns the number of previous characters plus 1,
  73520. ** or 0 if needle does not occur within haystack.
  73521. **
  73522. ** If both haystack and needle are BLOBs, then the result is one more than
  73523. ** the number of bytes in haystack prior to the first occurrence of needle,
  73524. ** or 0 if needle never occurs in haystack.
  73525. */
  73526. static void instrFunc(
  73527. sqlite3_context *context,
  73528. int argc,
  73529. sqlite3_value **argv
  73530. ){
  73531. const unsigned char *zHaystack;
  73532. const unsigned char *zNeedle;
  73533. int nHaystack;
  73534. int nNeedle;
  73535. int typeHaystack, typeNeedle;
  73536. int N = 1;
  73537. int isText;
  73538. UNUSED_PARAMETER(argc);
  73539. typeHaystack = sqlite3_value_type(argv[0]);
  73540. typeNeedle = sqlite3_value_type(argv[1]);
  73541. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  73542. nHaystack = sqlite3_value_bytes(argv[0]);
  73543. nNeedle = sqlite3_value_bytes(argv[1]);
  73544. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  73545. zHaystack = sqlite3_value_blob(argv[0]);
  73546. zNeedle = sqlite3_value_blob(argv[1]);
  73547. isText = 0;
  73548. }else{
  73549. zHaystack = sqlite3_value_text(argv[0]);
  73550. zNeedle = sqlite3_value_text(argv[1]);
  73551. isText = 1;
  73552. }
  73553. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  73554. N++;
  73555. do{
  73556. nHaystack--;
  73557. zHaystack++;
  73558. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  73559. }
  73560. if( nNeedle>nHaystack ) N = 0;
  73561. sqlite3_result_int(context, N);
  73562. }
  73563. /*
  73564. ** Implementation of the substr() function.
  73565. **
  73566. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  73567. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  73568. ** of x. If x is text, then we actually count UTF-8 characters.
  73569. ** If x is a blob, then we count bytes.
  73570. **
  73571. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  73572. **
  73573. ** If p2 is negative, return the p2 characters preceding p1.
  73574. */
  73575. static void substrFunc(
  73576. sqlite3_context *context,
  73577. int argc,
  73578. sqlite3_value **argv
  73579. ){
  73580. const unsigned char *z;
  73581. const unsigned char *z2;
  73582. int len;
  73583. int p0type;
  73584. i64 p1, p2;
  73585. int negP2 = 0;
  73586. assert( argc==3 || argc==2 );
  73587. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  73588. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  73589. ){
  73590. return;
  73591. }
  73592. p0type = sqlite3_value_type(argv[0]);
  73593. p1 = sqlite3_value_int(argv[1]);
  73594. if( p0type==SQLITE_BLOB ){
  73595. len = sqlite3_value_bytes(argv[0]);
  73596. z = sqlite3_value_blob(argv[0]);
  73597. if( z==0 ) return;
  73598. assert( len==sqlite3_value_bytes(argv[0]) );
  73599. }else{
  73600. z = sqlite3_value_text(argv[0]);
  73601. if( z==0 ) return;
  73602. len = 0;
  73603. if( p1<0 ){
  73604. for(z2=z; *z2; len++){
  73605. SQLITE_SKIP_UTF8(z2);
  73606. }
  73607. }
  73608. }
  73609. if( argc==3 ){
  73610. p2 = sqlite3_value_int(argv[2]);
  73611. if( p2<0 ){
  73612. p2 = -p2;
  73613. negP2 = 1;
  73614. }
  73615. }else{
  73616. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  73617. }
  73618. if( p1<0 ){
  73619. p1 += len;
  73620. if( p1<0 ){
  73621. p2 += p1;
  73622. if( p2<0 ) p2 = 0;
  73623. p1 = 0;
  73624. }
  73625. }else if( p1>0 ){
  73626. p1--;
  73627. }else if( p2>0 ){
  73628. p2--;
  73629. }
  73630. if( negP2 ){
  73631. p1 -= p2;
  73632. if( p1<0 ){
  73633. p2 += p1;
  73634. p1 = 0;
  73635. }
  73636. }
  73637. assert( p1>=0 && p2>=0 );
  73638. if( p0type!=SQLITE_BLOB ){
  73639. while( *z && p1 ){
  73640. SQLITE_SKIP_UTF8(z);
  73641. p1--;
  73642. }
  73643. for(z2=z; *z2 && p2; p2--){
  73644. SQLITE_SKIP_UTF8(z2);
  73645. }
  73646. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  73647. }else{
  73648. if( p1+p2>len ){
  73649. p2 = len-p1;
  73650. if( p2<0 ) p2 = 0;
  73651. }
  73652. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  73653. }
  73654. }
  73655. /*
  73656. ** Implementation of the round() function
  73657. */
  73658. #ifndef SQLITE_OMIT_FLOATING_POINT
  73659. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73660. int n = 0;
  73661. double r;
  73662. char *zBuf;
  73663. assert( argc==1 || argc==2 );
  73664. if( argc==2 ){
  73665. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  73666. n = sqlite3_value_int(argv[1]);
  73667. if( n>30 ) n = 30;
  73668. if( n<0 ) n = 0;
  73669. }
  73670. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  73671. r = sqlite3_value_double(argv[0]);
  73672. /* If Y==0 and X will fit in a 64-bit int,
  73673. ** handle the rounding directly,
  73674. ** otherwise use printf.
  73675. */
  73676. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  73677. r = (double)((sqlite_int64)(r+0.5));
  73678. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  73679. r = -(double)((sqlite_int64)((-r)+0.5));
  73680. }else{
  73681. zBuf = sqlite3_mprintf("%.*f",n,r);
  73682. if( zBuf==0 ){
  73683. sqlite3_result_error_nomem(context);
  73684. return;
  73685. }
  73686. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  73687. sqlite3_free(zBuf);
  73688. }
  73689. sqlite3_result_double(context, r);
  73690. }
  73691. #endif
  73692. /*
  73693. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  73694. ** allocation fails, call sqlite3_result_error_nomem() to notify
  73695. ** the database handle that malloc() has failed and return NULL.
  73696. ** If nByte is larger than the maximum string or blob length, then
  73697. ** raise an SQLITE_TOOBIG exception and return NULL.
  73698. */
  73699. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  73700. char *z;
  73701. sqlite3 *db = sqlite3_context_db_handle(context);
  73702. assert( nByte>0 );
  73703. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  73704. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  73705. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73706. sqlite3_result_error_toobig(context);
  73707. z = 0;
  73708. }else{
  73709. z = sqlite3Malloc((int)nByte);
  73710. if( !z ){
  73711. sqlite3_result_error_nomem(context);
  73712. }
  73713. }
  73714. return z;
  73715. }
  73716. /*
  73717. ** Implementation of the upper() and lower() SQL functions.
  73718. */
  73719. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73720. char *z1;
  73721. const char *z2;
  73722. int i, n;
  73723. UNUSED_PARAMETER(argc);
  73724. z2 = (char*)sqlite3_value_text(argv[0]);
  73725. n = sqlite3_value_bytes(argv[0]);
  73726. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  73727. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  73728. if( z2 ){
  73729. z1 = contextMalloc(context, ((i64)n)+1);
  73730. if( z1 ){
  73731. for(i=0; i<n; i++){
  73732. z1[i] = (char)sqlite3Toupper(z2[i]);
  73733. }
  73734. sqlite3_result_text(context, z1, n, sqlite3_free);
  73735. }
  73736. }
  73737. }
  73738. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73739. char *z1;
  73740. const char *z2;
  73741. int i, n;
  73742. UNUSED_PARAMETER(argc);
  73743. z2 = (char*)sqlite3_value_text(argv[0]);
  73744. n = sqlite3_value_bytes(argv[0]);
  73745. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  73746. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  73747. if( z2 ){
  73748. z1 = contextMalloc(context, ((i64)n)+1);
  73749. if( z1 ){
  73750. for(i=0; i<n; i++){
  73751. z1[i] = sqlite3Tolower(z2[i]);
  73752. }
  73753. sqlite3_result_text(context, z1, n, sqlite3_free);
  73754. }
  73755. }
  73756. }
  73757. /*
  73758. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  73759. ** as VDBE code so that unused argument values do not have to be computed.
  73760. ** However, we still need some kind of function implementation for this
  73761. ** routines in the function table. The noopFunc macro provides this.
  73762. ** noopFunc will never be called so it doesn't matter what the implementation
  73763. ** is. We might as well use the "version()" function as a substitute.
  73764. */
  73765. #define noopFunc versionFunc /* Substitute function - never called */
  73766. /*
  73767. ** Implementation of random(). Return a random integer.
  73768. */
  73769. static void randomFunc(
  73770. sqlite3_context *context,
  73771. int NotUsed,
  73772. sqlite3_value **NotUsed2
  73773. ){
  73774. sqlite_int64 r;
  73775. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73776. sqlite3_randomness(sizeof(r), &r);
  73777. if( r<0 ){
  73778. /* We need to prevent a random number of 0x8000000000000000
  73779. ** (or -9223372036854775808) since when you do abs() of that
  73780. ** number of you get the same value back again. To do this
  73781. ** in a way that is testable, mask the sign bit off of negative
  73782. ** values, resulting in a positive value. Then take the
  73783. ** 2s complement of that positive value. The end result can
  73784. ** therefore be no less than -9223372036854775807.
  73785. */
  73786. r = -(r & LARGEST_INT64);
  73787. }
  73788. sqlite3_result_int64(context, r);
  73789. }
  73790. /*
  73791. ** Implementation of randomblob(N). Return a random blob
  73792. ** that is N bytes long.
  73793. */
  73794. static void randomBlob(
  73795. sqlite3_context *context,
  73796. int argc,
  73797. sqlite3_value **argv
  73798. ){
  73799. int n;
  73800. unsigned char *p;
  73801. assert( argc==1 );
  73802. UNUSED_PARAMETER(argc);
  73803. n = sqlite3_value_int(argv[0]);
  73804. if( n<1 ){
  73805. n = 1;
  73806. }
  73807. p = contextMalloc(context, n);
  73808. if( p ){
  73809. sqlite3_randomness(n, p);
  73810. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  73811. }
  73812. }
  73813. /*
  73814. ** Implementation of the last_insert_rowid() SQL function. The return
  73815. ** value is the same as the sqlite3_last_insert_rowid() API function.
  73816. */
  73817. static void last_insert_rowid(
  73818. sqlite3_context *context,
  73819. int NotUsed,
  73820. sqlite3_value **NotUsed2
  73821. ){
  73822. sqlite3 *db = sqlite3_context_db_handle(context);
  73823. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73824. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  73825. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  73826. ** function. */
  73827. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  73828. }
  73829. /*
  73830. ** Implementation of the changes() SQL function.
  73831. **
  73832. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  73833. ** around the sqlite3_changes() C/C++ function and hence follows the same
  73834. ** rules for counting changes.
  73835. */
  73836. static void changes(
  73837. sqlite3_context *context,
  73838. int NotUsed,
  73839. sqlite3_value **NotUsed2
  73840. ){
  73841. sqlite3 *db = sqlite3_context_db_handle(context);
  73842. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73843. sqlite3_result_int(context, sqlite3_changes(db));
  73844. }
  73845. /*
  73846. ** Implementation of the total_changes() SQL function. The return value is
  73847. ** the same as the sqlite3_total_changes() API function.
  73848. */
  73849. static void total_changes(
  73850. sqlite3_context *context,
  73851. int NotUsed,
  73852. sqlite3_value **NotUsed2
  73853. ){
  73854. sqlite3 *db = sqlite3_context_db_handle(context);
  73855. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73856. /* IMP: R-52756-41993 This function is a wrapper around the
  73857. ** sqlite3_total_changes() C/C++ interface. */
  73858. sqlite3_result_int(context, sqlite3_total_changes(db));
  73859. }
  73860. /*
  73861. ** A structure defining how to do GLOB-style comparisons.
  73862. */
  73863. struct compareInfo {
  73864. u8 matchAll;
  73865. u8 matchOne;
  73866. u8 matchSet;
  73867. u8 noCase;
  73868. };
  73869. /*
  73870. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  73871. ** character is exactly one byte in size. Also, all characters are
  73872. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  73873. ** whereas only characters less than 0x80 do in ASCII.
  73874. */
  73875. #if defined(SQLITE_EBCDIC)
  73876. # define sqlite3Utf8Read(A) (*((*A)++))
  73877. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  73878. #else
  73879. # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  73880. #endif
  73881. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  73882. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  73883. ** case. Thus 'a' LIKE 'A' would be true. */
  73884. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  73885. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  73886. ** is case sensitive causing 'a' LIKE 'A' to be false */
  73887. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  73888. /*
  73889. ** Compare two UTF-8 strings for equality where the first string can
  73890. ** potentially be a "glob" expression. Return true (1) if they
  73891. ** are the same and false (0) if they are different.
  73892. **
  73893. ** Globbing rules:
  73894. **
  73895. ** '*' Matches any sequence of zero or more characters.
  73896. **
  73897. ** '?' Matches exactly one character.
  73898. **
  73899. ** [...] Matches one character from the enclosed list of
  73900. ** characters.
  73901. **
  73902. ** [^...] Matches one character not in the enclosed list.
  73903. **
  73904. ** With the [...] and [^...] matching, a ']' character can be included
  73905. ** in the list by making it the first character after '[' or '^'. A
  73906. ** range of characters can be specified using '-'. Example:
  73907. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  73908. ** it the last character in the list.
  73909. **
  73910. ** This routine is usually quick, but can be N**2 in the worst case.
  73911. **
  73912. ** Hints: to match '*' or '?', put them in "[]". Like this:
  73913. **
  73914. ** abc[*]xyz Matches "abc*xyz" only
  73915. */
  73916. static int patternCompare(
  73917. const u8 *zPattern, /* The glob pattern */
  73918. const u8 *zString, /* The string to compare against the glob */
  73919. const struct compareInfo *pInfo, /* Information about how to do the compare */
  73920. u32 esc /* The escape character */
  73921. ){
  73922. u32 c, c2;
  73923. int invert;
  73924. int seen;
  73925. u8 matchOne = pInfo->matchOne;
  73926. u8 matchAll = pInfo->matchAll;
  73927. u8 matchSet = pInfo->matchSet;
  73928. u8 noCase = pInfo->noCase;
  73929. int prevEscape = 0; /* True if the previous character was 'escape' */
  73930. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  73931. if( c==matchAll && !prevEscape ){
  73932. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  73933. || c == matchOne ){
  73934. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  73935. return 0;
  73936. }
  73937. }
  73938. if( c==0 ){
  73939. return 1;
  73940. }else if( c==esc ){
  73941. c = sqlite3Utf8Read(&zPattern);
  73942. if( c==0 ){
  73943. return 0;
  73944. }
  73945. }else if( c==matchSet ){
  73946. assert( esc==0 ); /* This is GLOB, not LIKE */
  73947. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  73948. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  73949. SQLITE_SKIP_UTF8(zString);
  73950. }
  73951. return *zString!=0;
  73952. }
  73953. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  73954. if( noCase ){
  73955. GlobUpperToLower(c2);
  73956. GlobUpperToLower(c);
  73957. while( c2 != 0 && c2 != c ){
  73958. c2 = sqlite3Utf8Read(&zString);
  73959. GlobUpperToLower(c2);
  73960. }
  73961. }else{
  73962. while( c2 != 0 && c2 != c ){
  73963. c2 = sqlite3Utf8Read(&zString);
  73964. }
  73965. }
  73966. if( c2==0 ) return 0;
  73967. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  73968. }
  73969. return 0;
  73970. }else if( c==matchOne && !prevEscape ){
  73971. if( sqlite3Utf8Read(&zString)==0 ){
  73972. return 0;
  73973. }
  73974. }else if( c==matchSet ){
  73975. u32 prior_c = 0;
  73976. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  73977. seen = 0;
  73978. invert = 0;
  73979. c = sqlite3Utf8Read(&zString);
  73980. if( c==0 ) return 0;
  73981. c2 = sqlite3Utf8Read(&zPattern);
  73982. if( c2=='^' ){
  73983. invert = 1;
  73984. c2 = sqlite3Utf8Read(&zPattern);
  73985. }
  73986. if( c2==']' ){
  73987. if( c==']' ) seen = 1;
  73988. c2 = sqlite3Utf8Read(&zPattern);
  73989. }
  73990. while( c2 && c2!=']' ){
  73991. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  73992. c2 = sqlite3Utf8Read(&zPattern);
  73993. if( c>=prior_c && c<=c2 ) seen = 1;
  73994. prior_c = 0;
  73995. }else{
  73996. if( c==c2 ){
  73997. seen = 1;
  73998. }
  73999. prior_c = c2;
  74000. }
  74001. c2 = sqlite3Utf8Read(&zPattern);
  74002. }
  74003. if( c2==0 || (seen ^ invert)==0 ){
  74004. return 0;
  74005. }
  74006. }else if( esc==c && !prevEscape ){
  74007. prevEscape = 1;
  74008. }else{
  74009. c2 = sqlite3Utf8Read(&zString);
  74010. if( noCase ){
  74011. GlobUpperToLower(c);
  74012. GlobUpperToLower(c2);
  74013. }
  74014. if( c!=c2 ){
  74015. return 0;
  74016. }
  74017. prevEscape = 0;
  74018. }
  74019. }
  74020. return *zString==0;
  74021. }
  74022. /*
  74023. ** The sqlite3_strglob() interface.
  74024. */
  74025. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  74026. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  74027. }
  74028. /*
  74029. ** Count the number of times that the LIKE operator (or GLOB which is
  74030. ** just a variation of LIKE) gets called. This is used for testing
  74031. ** only.
  74032. */
  74033. #ifdef SQLITE_TEST
  74034. SQLITE_API int sqlite3_like_count = 0;
  74035. #endif
  74036. /*
  74037. ** Implementation of the like() SQL function. This function implements
  74038. ** the build-in LIKE operator. The first argument to the function is the
  74039. ** pattern and the second argument is the string. So, the SQL statements:
  74040. **
  74041. ** A LIKE B
  74042. **
  74043. ** is implemented as like(B,A).
  74044. **
  74045. ** This same function (with a different compareInfo structure) computes
  74046. ** the GLOB operator.
  74047. */
  74048. static void likeFunc(
  74049. sqlite3_context *context,
  74050. int argc,
  74051. sqlite3_value **argv
  74052. ){
  74053. const unsigned char *zA, *zB;
  74054. u32 escape = 0;
  74055. int nPat;
  74056. sqlite3 *db = sqlite3_context_db_handle(context);
  74057. zB = sqlite3_value_text(argv[0]);
  74058. zA = sqlite3_value_text(argv[1]);
  74059. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  74060. ** of deep recursion and N*N behavior in patternCompare().
  74061. */
  74062. nPat = sqlite3_value_bytes(argv[0]);
  74063. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  74064. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  74065. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  74066. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  74067. return;
  74068. }
  74069. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  74070. if( argc==3 ){
  74071. /* The escape character string must consist of a single UTF-8 character.
  74072. ** Otherwise, return an error.
  74073. */
  74074. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  74075. if( zEsc==0 ) return;
  74076. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  74077. sqlite3_result_error(context,
  74078. "ESCAPE expression must be a single character", -1);
  74079. return;
  74080. }
  74081. escape = sqlite3Utf8Read(&zEsc);
  74082. }
  74083. if( zA && zB ){
  74084. struct compareInfo *pInfo = sqlite3_user_data(context);
  74085. #ifdef SQLITE_TEST
  74086. sqlite3_like_count++;
  74087. #endif
  74088. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  74089. }
  74090. }
  74091. /*
  74092. ** Implementation of the NULLIF(x,y) function. The result is the first
  74093. ** argument if the arguments are different. The result is NULL if the
  74094. ** arguments are equal to each other.
  74095. */
  74096. static void nullifFunc(
  74097. sqlite3_context *context,
  74098. int NotUsed,
  74099. sqlite3_value **argv
  74100. ){
  74101. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  74102. UNUSED_PARAMETER(NotUsed);
  74103. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  74104. sqlite3_result_value(context, argv[0]);
  74105. }
  74106. }
  74107. /*
  74108. ** Implementation of the sqlite_version() function. The result is the version
  74109. ** of the SQLite library that is running.
  74110. */
  74111. static void versionFunc(
  74112. sqlite3_context *context,
  74113. int NotUsed,
  74114. sqlite3_value **NotUsed2
  74115. ){
  74116. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74117. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  74118. ** sqlite3_libversion() C-interface. */
  74119. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  74120. }
  74121. /*
  74122. ** Implementation of the sqlite_source_id() function. The result is a string
  74123. ** that identifies the particular version of the source code used to build
  74124. ** SQLite.
  74125. */
  74126. static void sourceidFunc(
  74127. sqlite3_context *context,
  74128. int NotUsed,
  74129. sqlite3_value **NotUsed2
  74130. ){
  74131. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74132. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  74133. ** sqlite3_sourceid() C interface. */
  74134. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  74135. }
  74136. /*
  74137. ** Implementation of the sqlite_log() function. This is a wrapper around
  74138. ** sqlite3_log(). The return value is NULL. The function exists purely for
  74139. ** its side-effects.
  74140. */
  74141. static void errlogFunc(
  74142. sqlite3_context *context,
  74143. int argc,
  74144. sqlite3_value **argv
  74145. ){
  74146. UNUSED_PARAMETER(argc);
  74147. UNUSED_PARAMETER(context);
  74148. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  74149. }
  74150. /*
  74151. ** Implementation of the sqlite_compileoption_used() function.
  74152. ** The result is an integer that identifies if the compiler option
  74153. ** was used to build SQLite.
  74154. */
  74155. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74156. static void compileoptionusedFunc(
  74157. sqlite3_context *context,
  74158. int argc,
  74159. sqlite3_value **argv
  74160. ){
  74161. const char *zOptName;
  74162. assert( argc==1 );
  74163. UNUSED_PARAMETER(argc);
  74164. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  74165. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  74166. ** function.
  74167. */
  74168. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  74169. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  74170. }
  74171. }
  74172. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74173. /*
  74174. ** Implementation of the sqlite_compileoption_get() function.
  74175. ** The result is a string that identifies the compiler options
  74176. ** used to build SQLite.
  74177. */
  74178. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74179. static void compileoptiongetFunc(
  74180. sqlite3_context *context,
  74181. int argc,
  74182. sqlite3_value **argv
  74183. ){
  74184. int n;
  74185. assert( argc==1 );
  74186. UNUSED_PARAMETER(argc);
  74187. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  74188. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  74189. */
  74190. n = sqlite3_value_int(argv[0]);
  74191. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  74192. }
  74193. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74194. /* Array for converting from half-bytes (nybbles) into ASCII hex
  74195. ** digits. */
  74196. static const char hexdigits[] = {
  74197. '0', '1', '2', '3', '4', '5', '6', '7',
  74198. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  74199. };
  74200. /*
  74201. ** Implementation of the QUOTE() function. This function takes a single
  74202. ** argument. If the argument is numeric, the return value is the same as
  74203. ** the argument. If the argument is NULL, the return value is the string
  74204. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  74205. ** single-quote escapes.
  74206. */
  74207. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  74208. assert( argc==1 );
  74209. UNUSED_PARAMETER(argc);
  74210. switch( sqlite3_value_type(argv[0]) ){
  74211. case SQLITE_FLOAT: {
  74212. double r1, r2;
  74213. char zBuf[50];
  74214. r1 = sqlite3_value_double(argv[0]);
  74215. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  74216. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  74217. if( r1!=r2 ){
  74218. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  74219. }
  74220. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  74221. break;
  74222. }
  74223. case SQLITE_INTEGER: {
  74224. sqlite3_result_value(context, argv[0]);
  74225. break;
  74226. }
  74227. case SQLITE_BLOB: {
  74228. char *zText = 0;
  74229. char const *zBlob = sqlite3_value_blob(argv[0]);
  74230. int nBlob = sqlite3_value_bytes(argv[0]);
  74231. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  74232. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  74233. if( zText ){
  74234. int i;
  74235. for(i=0; i<nBlob; i++){
  74236. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  74237. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  74238. }
  74239. zText[(nBlob*2)+2] = '\'';
  74240. zText[(nBlob*2)+3] = '\0';
  74241. zText[0] = 'X';
  74242. zText[1] = '\'';
  74243. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  74244. sqlite3_free(zText);
  74245. }
  74246. break;
  74247. }
  74248. case SQLITE_TEXT: {
  74249. int i,j;
  74250. u64 n;
  74251. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  74252. char *z;
  74253. if( zArg==0 ) return;
  74254. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  74255. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  74256. if( z ){
  74257. z[0] = '\'';
  74258. for(i=0, j=1; zArg[i]; i++){
  74259. z[j++] = zArg[i];
  74260. if( zArg[i]=='\'' ){
  74261. z[j++] = '\'';
  74262. }
  74263. }
  74264. z[j++] = '\'';
  74265. z[j] = 0;
  74266. sqlite3_result_text(context, z, j, sqlite3_free);
  74267. }
  74268. break;
  74269. }
  74270. default: {
  74271. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  74272. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  74273. break;
  74274. }
  74275. }
  74276. }
  74277. /*
  74278. ** The unicode() function. Return the integer unicode code-point value
  74279. ** for the first character of the input string.
  74280. */
  74281. static void unicodeFunc(
  74282. sqlite3_context *context,
  74283. int argc,
  74284. sqlite3_value **argv
  74285. ){
  74286. const unsigned char *z = sqlite3_value_text(argv[0]);
  74287. (void)argc;
  74288. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  74289. }
  74290. /*
  74291. ** The char() function takes zero or more arguments, each of which is
  74292. ** an integer. It constructs a string where each character of the string
  74293. ** is the unicode character for the corresponding integer argument.
  74294. */
  74295. static void charFunc(
  74296. sqlite3_context *context,
  74297. int argc,
  74298. sqlite3_value **argv
  74299. ){
  74300. unsigned char *z, *zOut;
  74301. int i;
  74302. zOut = z = sqlite3_malloc( argc*4 );
  74303. if( z==0 ){
  74304. sqlite3_result_error_nomem(context);
  74305. return;
  74306. }
  74307. for(i=0; i<argc; i++){
  74308. sqlite3_int64 x;
  74309. unsigned c;
  74310. x = sqlite3_value_int64(argv[i]);
  74311. if( x<0 || x>0x10ffff ) x = 0xfffd;
  74312. c = (unsigned)(x & 0x1fffff);
  74313. if( c<0x00080 ){
  74314. *zOut++ = (u8)(c&0xFF);
  74315. }else if( c<0x00800 ){
  74316. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  74317. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74318. }else if( c<0x10000 ){
  74319. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  74320. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  74321. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74322. }else{
  74323. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  74324. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  74325. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  74326. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74327. } \
  74328. }
  74329. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  74330. }
  74331. /*
  74332. ** The hex() function. Interpret the argument as a blob. Return
  74333. ** a hexadecimal rendering as text.
  74334. */
  74335. static void hexFunc(
  74336. sqlite3_context *context,
  74337. int argc,
  74338. sqlite3_value **argv
  74339. ){
  74340. int i, n;
  74341. const unsigned char *pBlob;
  74342. char *zHex, *z;
  74343. assert( argc==1 );
  74344. UNUSED_PARAMETER(argc);
  74345. pBlob = sqlite3_value_blob(argv[0]);
  74346. n = sqlite3_value_bytes(argv[0]);
  74347. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  74348. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  74349. if( zHex ){
  74350. for(i=0; i<n; i++, pBlob++){
  74351. unsigned char c = *pBlob;
  74352. *(z++) = hexdigits[(c>>4)&0xf];
  74353. *(z++) = hexdigits[c&0xf];
  74354. }
  74355. *z = 0;
  74356. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  74357. }
  74358. }
  74359. /*
  74360. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  74361. */
  74362. static void zeroblobFunc(
  74363. sqlite3_context *context,
  74364. int argc,
  74365. sqlite3_value **argv
  74366. ){
  74367. i64 n;
  74368. sqlite3 *db = sqlite3_context_db_handle(context);
  74369. assert( argc==1 );
  74370. UNUSED_PARAMETER(argc);
  74371. n = sqlite3_value_int64(argv[0]);
  74372. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74373. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  74374. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74375. sqlite3_result_error_toobig(context);
  74376. }else{
  74377. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  74378. }
  74379. }
  74380. /*
  74381. ** The replace() function. Three arguments are all strings: call
  74382. ** them A, B, and C. The result is also a string which is derived
  74383. ** from A by replacing every occurrence of B with C. The match
  74384. ** must be exact. Collating sequences are not used.
  74385. */
  74386. static void replaceFunc(
  74387. sqlite3_context *context,
  74388. int argc,
  74389. sqlite3_value **argv
  74390. ){
  74391. const unsigned char *zStr; /* The input string A */
  74392. const unsigned char *zPattern; /* The pattern string B */
  74393. const unsigned char *zRep; /* The replacement string C */
  74394. unsigned char *zOut; /* The output */
  74395. int nStr; /* Size of zStr */
  74396. int nPattern; /* Size of zPattern */
  74397. int nRep; /* Size of zRep */
  74398. i64 nOut; /* Maximum size of zOut */
  74399. int loopLimit; /* Last zStr[] that might match zPattern[] */
  74400. int i, j; /* Loop counters */
  74401. assert( argc==3 );
  74402. UNUSED_PARAMETER(argc);
  74403. zStr = sqlite3_value_text(argv[0]);
  74404. if( zStr==0 ) return;
  74405. nStr = sqlite3_value_bytes(argv[0]);
  74406. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  74407. zPattern = sqlite3_value_text(argv[1]);
  74408. if( zPattern==0 ){
  74409. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  74410. || sqlite3_context_db_handle(context)->mallocFailed );
  74411. return;
  74412. }
  74413. if( zPattern[0]==0 ){
  74414. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  74415. sqlite3_result_value(context, argv[0]);
  74416. return;
  74417. }
  74418. nPattern = sqlite3_value_bytes(argv[1]);
  74419. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  74420. zRep = sqlite3_value_text(argv[2]);
  74421. if( zRep==0 ) return;
  74422. nRep = sqlite3_value_bytes(argv[2]);
  74423. assert( zRep==sqlite3_value_text(argv[2]) );
  74424. nOut = nStr + 1;
  74425. assert( nOut<SQLITE_MAX_LENGTH );
  74426. zOut = contextMalloc(context, (i64)nOut);
  74427. if( zOut==0 ){
  74428. return;
  74429. }
  74430. loopLimit = nStr - nPattern;
  74431. for(i=j=0; i<=loopLimit; i++){
  74432. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  74433. zOut[j++] = zStr[i];
  74434. }else{
  74435. u8 *zOld;
  74436. sqlite3 *db = sqlite3_context_db_handle(context);
  74437. nOut += nRep - nPattern;
  74438. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74439. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74440. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74441. sqlite3_result_error_toobig(context);
  74442. sqlite3_free(zOut);
  74443. return;
  74444. }
  74445. zOld = zOut;
  74446. zOut = sqlite3_realloc(zOut, (int)nOut);
  74447. if( zOut==0 ){
  74448. sqlite3_result_error_nomem(context);
  74449. sqlite3_free(zOld);
  74450. return;
  74451. }
  74452. memcpy(&zOut[j], zRep, nRep);
  74453. j += nRep;
  74454. i += nPattern-1;
  74455. }
  74456. }
  74457. assert( j+nStr-i+1==nOut );
  74458. memcpy(&zOut[j], &zStr[i], nStr-i);
  74459. j += nStr - i;
  74460. assert( j<=nOut );
  74461. zOut[j] = 0;
  74462. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  74463. }
  74464. /*
  74465. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  74466. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  74467. */
  74468. static void trimFunc(
  74469. sqlite3_context *context,
  74470. int argc,
  74471. sqlite3_value **argv
  74472. ){
  74473. const unsigned char *zIn; /* Input string */
  74474. const unsigned char *zCharSet; /* Set of characters to trim */
  74475. int nIn; /* Number of bytes in input */
  74476. int flags; /* 1: trimleft 2: trimright 3: trim */
  74477. int i; /* Loop counter */
  74478. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  74479. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  74480. int nChar; /* Number of characters in zCharSet */
  74481. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  74482. return;
  74483. }
  74484. zIn = sqlite3_value_text(argv[0]);
  74485. if( zIn==0 ) return;
  74486. nIn = sqlite3_value_bytes(argv[0]);
  74487. assert( zIn==sqlite3_value_text(argv[0]) );
  74488. if( argc==1 ){
  74489. static const unsigned char lenOne[] = { 1 };
  74490. static unsigned char * const azOne[] = { (u8*)" " };
  74491. nChar = 1;
  74492. aLen = (u8*)lenOne;
  74493. azChar = (unsigned char **)azOne;
  74494. zCharSet = 0;
  74495. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  74496. return;
  74497. }else{
  74498. const unsigned char *z;
  74499. for(z=zCharSet, nChar=0; *z; nChar++){
  74500. SQLITE_SKIP_UTF8(z);
  74501. }
  74502. if( nChar>0 ){
  74503. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  74504. if( azChar==0 ){
  74505. return;
  74506. }
  74507. aLen = (unsigned char*)&azChar[nChar];
  74508. for(z=zCharSet, nChar=0; *z; nChar++){
  74509. azChar[nChar] = (unsigned char *)z;
  74510. SQLITE_SKIP_UTF8(z);
  74511. aLen[nChar] = (u8)(z - azChar[nChar]);
  74512. }
  74513. }
  74514. }
  74515. if( nChar>0 ){
  74516. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  74517. if( flags & 1 ){
  74518. while( nIn>0 ){
  74519. int len = 0;
  74520. for(i=0; i<nChar; i++){
  74521. len = aLen[i];
  74522. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  74523. }
  74524. if( i>=nChar ) break;
  74525. zIn += len;
  74526. nIn -= len;
  74527. }
  74528. }
  74529. if( flags & 2 ){
  74530. while( nIn>0 ){
  74531. int len = 0;
  74532. for(i=0; i<nChar; i++){
  74533. len = aLen[i];
  74534. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  74535. }
  74536. if( i>=nChar ) break;
  74537. nIn -= len;
  74538. }
  74539. }
  74540. if( zCharSet ){
  74541. sqlite3_free(azChar);
  74542. }
  74543. }
  74544. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  74545. }
  74546. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  74547. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  74548. ** when SQLite is built.
  74549. */
  74550. #ifdef SQLITE_SOUNDEX
  74551. /*
  74552. ** Compute the soundex encoding of a word.
  74553. **
  74554. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  74555. ** soundex encoding of the string X.
  74556. */
  74557. static void soundexFunc(
  74558. sqlite3_context *context,
  74559. int argc,
  74560. sqlite3_value **argv
  74561. ){
  74562. char zResult[8];
  74563. const u8 *zIn;
  74564. int i, j;
  74565. static const unsigned char iCode[] = {
  74566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74570. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  74571. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  74572. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  74573. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  74574. };
  74575. assert( argc==1 );
  74576. zIn = (u8*)sqlite3_value_text(argv[0]);
  74577. if( zIn==0 ) zIn = (u8*)"";
  74578. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  74579. if( zIn[i] ){
  74580. u8 prevcode = iCode[zIn[i]&0x7f];
  74581. zResult[0] = sqlite3Toupper(zIn[i]);
  74582. for(j=1; j<4 && zIn[i]; i++){
  74583. int code = iCode[zIn[i]&0x7f];
  74584. if( code>0 ){
  74585. if( code!=prevcode ){
  74586. prevcode = code;
  74587. zResult[j++] = code + '0';
  74588. }
  74589. }else{
  74590. prevcode = 0;
  74591. }
  74592. }
  74593. while( j<4 ){
  74594. zResult[j++] = '0';
  74595. }
  74596. zResult[j] = 0;
  74597. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  74598. }else{
  74599. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  74600. ** is NULL or contains no ASCII alphabetic characters. */
  74601. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  74602. }
  74603. }
  74604. #endif /* SQLITE_SOUNDEX */
  74605. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  74606. /*
  74607. ** A function that loads a shared-library extension then returns NULL.
  74608. */
  74609. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  74610. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  74611. const char *zProc;
  74612. sqlite3 *db = sqlite3_context_db_handle(context);
  74613. char *zErrMsg = 0;
  74614. if( argc==2 ){
  74615. zProc = (const char *)sqlite3_value_text(argv[1]);
  74616. }else{
  74617. zProc = 0;
  74618. }
  74619. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  74620. sqlite3_result_error(context, zErrMsg, -1);
  74621. sqlite3_free(zErrMsg);
  74622. }
  74623. }
  74624. #endif
  74625. /*
  74626. ** An instance of the following structure holds the context of a
  74627. ** sum() or avg() aggregate computation.
  74628. */
  74629. typedef struct SumCtx SumCtx;
  74630. struct SumCtx {
  74631. double rSum; /* Floating point sum */
  74632. i64 iSum; /* Integer sum */
  74633. i64 cnt; /* Number of elements summed */
  74634. u8 overflow; /* True if integer overflow seen */
  74635. u8 approx; /* True if non-integer value was input to the sum */
  74636. };
  74637. /*
  74638. ** Routines used to compute the sum, average, and total.
  74639. **
  74640. ** The SUM() function follows the (broken) SQL standard which means
  74641. ** that it returns NULL if it sums over no inputs. TOTAL returns
  74642. ** 0.0 in that case. In addition, TOTAL always returns a float where
  74643. ** SUM might return an integer if it never encounters a floating point
  74644. ** value. TOTAL never fails, but SUM might through an exception if
  74645. ** it overflows an integer.
  74646. */
  74647. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  74648. SumCtx *p;
  74649. int type;
  74650. assert( argc==1 );
  74651. UNUSED_PARAMETER(argc);
  74652. p = sqlite3_aggregate_context(context, sizeof(*p));
  74653. type = sqlite3_value_numeric_type(argv[0]);
  74654. if( p && type!=SQLITE_NULL ){
  74655. p->cnt++;
  74656. if( type==SQLITE_INTEGER ){
  74657. i64 v = sqlite3_value_int64(argv[0]);
  74658. p->rSum += v;
  74659. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  74660. p->overflow = 1;
  74661. }
  74662. }else{
  74663. p->rSum += sqlite3_value_double(argv[0]);
  74664. p->approx = 1;
  74665. }
  74666. }
  74667. }
  74668. static void sumFinalize(sqlite3_context *context){
  74669. SumCtx *p;
  74670. p = sqlite3_aggregate_context(context, 0);
  74671. if( p && p->cnt>0 ){
  74672. if( p->overflow ){
  74673. sqlite3_result_error(context,"integer overflow",-1);
  74674. }else if( p->approx ){
  74675. sqlite3_result_double(context, p->rSum);
  74676. }else{
  74677. sqlite3_result_int64(context, p->iSum);
  74678. }
  74679. }
  74680. }
  74681. static void avgFinalize(sqlite3_context *context){
  74682. SumCtx *p;
  74683. p = sqlite3_aggregate_context(context, 0);
  74684. if( p && p->cnt>0 ){
  74685. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  74686. }
  74687. }
  74688. static void totalFinalize(sqlite3_context *context){
  74689. SumCtx *p;
  74690. p = sqlite3_aggregate_context(context, 0);
  74691. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  74692. sqlite3_result_double(context, p ? p->rSum : (double)0);
  74693. }
  74694. /*
  74695. ** The following structure keeps track of state information for the
  74696. ** count() aggregate function.
  74697. */
  74698. typedef struct CountCtx CountCtx;
  74699. struct CountCtx {
  74700. i64 n;
  74701. };
  74702. /*
  74703. ** Routines to implement the count() aggregate function.
  74704. */
  74705. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  74706. CountCtx *p;
  74707. p = sqlite3_aggregate_context(context, sizeof(*p));
  74708. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  74709. p->n++;
  74710. }
  74711. #ifndef SQLITE_OMIT_DEPRECATED
  74712. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  74713. ** sure it still operates correctly, verify that its count agrees with our
  74714. ** internal count when using count(*) and when the total count can be
  74715. ** expressed as a 32-bit integer. */
  74716. assert( argc==1 || p==0 || p->n>0x7fffffff
  74717. || p->n==sqlite3_aggregate_count(context) );
  74718. #endif
  74719. }
  74720. static void countFinalize(sqlite3_context *context){
  74721. CountCtx *p;
  74722. p = sqlite3_aggregate_context(context, 0);
  74723. sqlite3_result_int64(context, p ? p->n : 0);
  74724. }
  74725. /*
  74726. ** Routines to implement min() and max() aggregate functions.
  74727. */
  74728. static void minmaxStep(
  74729. sqlite3_context *context,
  74730. int NotUsed,
  74731. sqlite3_value **argv
  74732. ){
  74733. Mem *pArg = (Mem *)argv[0];
  74734. Mem *pBest;
  74735. UNUSED_PARAMETER(NotUsed);
  74736. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  74737. if( !pBest ) return;
  74738. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  74739. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  74740. }else if( pBest->flags ){
  74741. int max;
  74742. int cmp;
  74743. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  74744. /* This step function is used for both the min() and max() aggregates,
  74745. ** the only difference between the two being that the sense of the
  74746. ** comparison is inverted. For the max() aggregate, the
  74747. ** sqlite3_user_data() function returns (void *)-1. For min() it
  74748. ** returns (void *)db, where db is the sqlite3* database pointer.
  74749. ** Therefore the next statement sets variable 'max' to 1 for the max()
  74750. ** aggregate, or 0 for min().
  74751. */
  74752. max = sqlite3_user_data(context)!=0;
  74753. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  74754. if( (max && cmp<0) || (!max && cmp>0) ){
  74755. sqlite3VdbeMemCopy(pBest, pArg);
  74756. }else{
  74757. sqlite3SkipAccumulatorLoad(context);
  74758. }
  74759. }else{
  74760. sqlite3VdbeMemCopy(pBest, pArg);
  74761. }
  74762. }
  74763. static void minMaxFinalize(sqlite3_context *context){
  74764. sqlite3_value *pRes;
  74765. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  74766. if( pRes ){
  74767. if( pRes->flags ){
  74768. sqlite3_result_value(context, pRes);
  74769. }
  74770. sqlite3VdbeMemRelease(pRes);
  74771. }
  74772. }
  74773. /*
  74774. ** group_concat(EXPR, ?SEPARATOR?)
  74775. */
  74776. static void groupConcatStep(
  74777. sqlite3_context *context,
  74778. int argc,
  74779. sqlite3_value **argv
  74780. ){
  74781. const char *zVal;
  74782. StrAccum *pAccum;
  74783. const char *zSep;
  74784. int nVal, nSep;
  74785. assert( argc==1 || argc==2 );
  74786. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  74787. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  74788. if( pAccum ){
  74789. sqlite3 *db = sqlite3_context_db_handle(context);
  74790. int firstTerm = pAccum->useMalloc==0;
  74791. pAccum->useMalloc = 2;
  74792. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  74793. if( !firstTerm ){
  74794. if( argc==2 ){
  74795. zSep = (char*)sqlite3_value_text(argv[1]);
  74796. nSep = sqlite3_value_bytes(argv[1]);
  74797. }else{
  74798. zSep = ",";
  74799. nSep = 1;
  74800. }
  74801. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  74802. }
  74803. zVal = (char*)sqlite3_value_text(argv[0]);
  74804. nVal = sqlite3_value_bytes(argv[0]);
  74805. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  74806. }
  74807. }
  74808. static void groupConcatFinalize(sqlite3_context *context){
  74809. StrAccum *pAccum;
  74810. pAccum = sqlite3_aggregate_context(context, 0);
  74811. if( pAccum ){
  74812. if( pAccum->accError==STRACCUM_TOOBIG ){
  74813. sqlite3_result_error_toobig(context);
  74814. }else if( pAccum->accError==STRACCUM_NOMEM ){
  74815. sqlite3_result_error_nomem(context);
  74816. }else{
  74817. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  74818. sqlite3_free);
  74819. }
  74820. }
  74821. }
  74822. /*
  74823. ** This routine does per-connection function registration. Most
  74824. ** of the built-in functions above are part of the global function set.
  74825. ** This routine only deals with those that are not global.
  74826. */
  74827. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  74828. int rc = sqlite3_overload_function(db, "MATCH", 2);
  74829. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  74830. if( rc==SQLITE_NOMEM ){
  74831. db->mallocFailed = 1;
  74832. }
  74833. }
  74834. /*
  74835. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  74836. */
  74837. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  74838. FuncDef *pDef;
  74839. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  74840. 2, SQLITE_UTF8, 0);
  74841. if( ALWAYS(pDef) ){
  74842. pDef->funcFlags |= flagVal;
  74843. }
  74844. }
  74845. /*
  74846. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  74847. ** parameter determines whether or not the LIKE operator is case
  74848. ** sensitive. GLOB is always case sensitive.
  74849. */
  74850. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  74851. struct compareInfo *pInfo;
  74852. if( caseSensitive ){
  74853. pInfo = (struct compareInfo*)&likeInfoAlt;
  74854. }else{
  74855. pInfo = (struct compareInfo*)&likeInfoNorm;
  74856. }
  74857. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  74858. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  74859. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  74860. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  74861. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  74862. setLikeOptFlag(db, "like",
  74863. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  74864. }
  74865. /*
  74866. ** pExpr points to an expression which implements a function. If
  74867. ** it is appropriate to apply the LIKE optimization to that function
  74868. ** then set aWc[0] through aWc[2] to the wildcard characters and
  74869. ** return TRUE. If the function is not a LIKE-style function then
  74870. ** return FALSE.
  74871. */
  74872. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  74873. FuncDef *pDef;
  74874. if( pExpr->op!=TK_FUNCTION
  74875. || !pExpr->x.pList
  74876. || pExpr->x.pList->nExpr!=2
  74877. ){
  74878. return 0;
  74879. }
  74880. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74881. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  74882. sqlite3Strlen30(pExpr->u.zToken),
  74883. 2, SQLITE_UTF8, 0);
  74884. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  74885. return 0;
  74886. }
  74887. /* The memcpy() statement assumes that the wildcard characters are
  74888. ** the first three statements in the compareInfo structure. The
  74889. ** asserts() that follow verify that assumption
  74890. */
  74891. memcpy(aWc, pDef->pUserData, 3);
  74892. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  74893. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  74894. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  74895. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  74896. return 1;
  74897. }
  74898. /*
  74899. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  74900. ** to the global function hash table. This occurs at start-time (as
  74901. ** a consequence of calling sqlite3_initialize()).
  74902. **
  74903. ** After this routine runs
  74904. */
  74905. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  74906. /*
  74907. ** The following array holds FuncDef structures for all of the functions
  74908. ** defined in this file.
  74909. **
  74910. ** The array cannot be constant since changes are made to the
  74911. ** FuncDef.pHash elements at start-time. The elements of this array
  74912. ** are read-only after initialization is complete.
  74913. */
  74914. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  74915. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  74916. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  74917. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  74918. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  74919. FUNCTION(trim, 1, 3, 0, trimFunc ),
  74920. FUNCTION(trim, 2, 3, 0, trimFunc ),
  74921. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  74922. FUNCTION(min, 0, 0, 1, 0 ),
  74923. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  74924. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  74925. FUNCTION(max, 0, 1, 1, 0 ),
  74926. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  74927. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  74928. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  74929. FUNCTION(instr, 2, 0, 0, instrFunc ),
  74930. FUNCTION(substr, 2, 0, 0, substrFunc ),
  74931. FUNCTION(substr, 3, 0, 0, substrFunc ),
  74932. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  74933. FUNCTION(char, -1, 0, 0, charFunc ),
  74934. FUNCTION(abs, 1, 0, 0, absFunc ),
  74935. #ifndef SQLITE_OMIT_FLOATING_POINT
  74936. FUNCTION(round, 1, 0, 0, roundFunc ),
  74937. FUNCTION(round, 2, 0, 0, roundFunc ),
  74938. #endif
  74939. FUNCTION(upper, 1, 0, 0, upperFunc ),
  74940. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  74941. FUNCTION(coalesce, 1, 0, 0, 0 ),
  74942. FUNCTION(coalesce, 0, 0, 0, 0 ),
  74943. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  74944. FUNCTION(hex, 1, 0, 0, hexFunc ),
  74945. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  74946. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  74947. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  74948. FUNCTION(random, 0, 0, 0, randomFunc ),
  74949. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  74950. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  74951. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  74952. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  74953. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  74954. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74955. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  74956. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  74957. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74958. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  74959. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  74960. FUNCTION(changes, 0, 0, 0, changes ),
  74961. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  74962. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  74963. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  74964. #ifdef SQLITE_SOUNDEX
  74965. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  74966. #endif
  74967. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  74968. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  74969. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  74970. #endif
  74971. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  74972. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  74973. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  74974. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  74975. {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  74976. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  74977. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  74978. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  74979. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74980. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  74981. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74982. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74983. #else
  74984. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  74985. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  74986. #endif
  74987. };
  74988. int i;
  74989. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  74990. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  74991. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  74992. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  74993. }
  74994. sqlite3RegisterDateTimeFunctions();
  74995. #ifndef SQLITE_OMIT_ALTERTABLE
  74996. sqlite3AlterFunctions();
  74997. #endif
  74998. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  74999. sqlite3AnalyzeFunctions();
  75000. #endif
  75001. }
  75002. /************** End of func.c ************************************************/
  75003. /************** Begin file fkey.c ********************************************/
  75004. /*
  75005. **
  75006. ** The author disclaims copyright to this source code. In place of
  75007. ** a legal notice, here is a blessing:
  75008. **
  75009. ** May you do good and not evil.
  75010. ** May you find forgiveness for yourself and forgive others.
  75011. ** May you share freely, never taking more than you give.
  75012. **
  75013. *************************************************************************
  75014. ** This file contains code used by the compiler to add foreign key
  75015. ** support to compiled SQL statements.
  75016. */
  75017. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75018. #ifndef SQLITE_OMIT_TRIGGER
  75019. /*
  75020. ** Deferred and Immediate FKs
  75021. ** --------------------------
  75022. **
  75023. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  75024. ** If an immediate foreign key constraint is violated,
  75025. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  75026. ** statement transaction rolled back. If a
  75027. ** deferred foreign key constraint is violated, no action is taken
  75028. ** immediately. However if the application attempts to commit the
  75029. ** transaction before fixing the constraint violation, the attempt fails.
  75030. **
  75031. ** Deferred constraints are implemented using a simple counter associated
  75032. ** with the database handle. The counter is set to zero each time a
  75033. ** database transaction is opened. Each time a statement is executed
  75034. ** that causes a foreign key violation, the counter is incremented. Each
  75035. ** time a statement is executed that removes an existing violation from
  75036. ** the database, the counter is decremented. When the transaction is
  75037. ** committed, the commit fails if the current value of the counter is
  75038. ** greater than zero. This scheme has two big drawbacks:
  75039. **
  75040. ** * When a commit fails due to a deferred foreign key constraint,
  75041. ** there is no way to tell which foreign constraint is not satisfied,
  75042. ** or which row it is not satisfied for.
  75043. **
  75044. ** * If the database contains foreign key violations when the
  75045. ** transaction is opened, this may cause the mechanism to malfunction.
  75046. **
  75047. ** Despite these problems, this approach is adopted as it seems simpler
  75048. ** than the alternatives.
  75049. **
  75050. ** INSERT operations:
  75051. **
  75052. ** I.1) For each FK for which the table is the child table, search
  75053. ** the parent table for a match. If none is found increment the
  75054. ** constraint counter.
  75055. **
  75056. ** I.2) For each FK for which the table is the parent table,
  75057. ** search the child table for rows that correspond to the new
  75058. ** row in the parent table. Decrement the counter for each row
  75059. ** found (as the constraint is now satisfied).
  75060. **
  75061. ** DELETE operations:
  75062. **
  75063. ** D.1) For each FK for which the table is the child table,
  75064. ** search the parent table for a row that corresponds to the
  75065. ** deleted row in the child table. If such a row is not found,
  75066. ** decrement the counter.
  75067. **
  75068. ** D.2) For each FK for which the table is the parent table, search
  75069. ** the child table for rows that correspond to the deleted row
  75070. ** in the parent table. For each found increment the counter.
  75071. **
  75072. ** UPDATE operations:
  75073. **
  75074. ** An UPDATE command requires that all 4 steps above are taken, but only
  75075. ** for FK constraints for which the affected columns are actually
  75076. ** modified (values must be compared at runtime).
  75077. **
  75078. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  75079. ** This simplifies the implementation a bit.
  75080. **
  75081. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  75082. ** resolution is considered to delete rows before the new row is inserted.
  75083. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  75084. ** is thrown, even if the FK constraint would be satisfied after the new
  75085. ** row is inserted.
  75086. **
  75087. ** Immediate constraints are usually handled similarly. The only difference
  75088. ** is that the counter used is stored as part of each individual statement
  75089. ** object (struct Vdbe). If, after the statement has run, its immediate
  75090. ** constraint counter is greater than zero,
  75091. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  75092. ** and the statement transaction is rolled back. An exception is an INSERT
  75093. ** statement that inserts a single row only (no triggers). In this case,
  75094. ** instead of using a counter, an exception is thrown immediately if the
  75095. ** INSERT violates a foreign key constraint. This is necessary as such
  75096. ** an INSERT does not open a statement transaction.
  75097. **
  75098. ** TODO: How should dropping a table be handled? How should renaming a
  75099. ** table be handled?
  75100. **
  75101. **
  75102. ** Query API Notes
  75103. ** ---------------
  75104. **
  75105. ** Before coding an UPDATE or DELETE row operation, the code-generator
  75106. ** for those two operations needs to know whether or not the operation
  75107. ** requires any FK processing and, if so, which columns of the original
  75108. ** row are required by the FK processing VDBE code (i.e. if FKs were
  75109. ** implemented using triggers, which of the old.* columns would be
  75110. ** accessed). No information is required by the code-generator before
  75111. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  75112. ** generation code to query for this information are:
  75113. **
  75114. ** sqlite3FkRequired() - Test to see if FK processing is required.
  75115. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  75116. **
  75117. **
  75118. ** Externally accessible module functions
  75119. ** --------------------------------------
  75120. **
  75121. ** sqlite3FkCheck() - Check for foreign key violations.
  75122. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  75123. ** sqlite3FkDelete() - Delete an FKey structure.
  75124. */
  75125. /*
  75126. ** VDBE Calling Convention
  75127. ** -----------------------
  75128. **
  75129. ** Example:
  75130. **
  75131. ** For the following INSERT statement:
  75132. **
  75133. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  75134. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  75135. **
  75136. ** Register (x): 2 (type integer)
  75137. ** Register (x+1): 1 (type integer)
  75138. ** Register (x+2): NULL (type NULL)
  75139. ** Register (x+3): 3.1 (type real)
  75140. */
  75141. /*
  75142. ** A foreign key constraint requires that the key columns in the parent
  75143. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  75144. ** Given that pParent is the parent table for foreign key constraint pFKey,
  75145. ** search the schema for a unique index on the parent key columns.
  75146. **
  75147. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  75148. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  75149. ** is set to point to the unique index.
  75150. **
  75151. ** If the parent key consists of a single column (the foreign key constraint
  75152. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  75153. ** Otherwise, it is set to point to an allocated array of size N, where
  75154. ** N is the number of columns in the parent key. The first element of the
  75155. ** array is the index of the child table column that is mapped by the FK
  75156. ** constraint to the parent table column stored in the left-most column
  75157. ** of index *ppIdx. The second element of the array is the index of the
  75158. ** child table column that corresponds to the second left-most column of
  75159. ** *ppIdx, and so on.
  75160. **
  75161. ** If the required index cannot be found, either because:
  75162. **
  75163. ** 1) The named parent key columns do not exist, or
  75164. **
  75165. ** 2) The named parent key columns do exist, but are not subject to a
  75166. ** UNIQUE or PRIMARY KEY constraint, or
  75167. **
  75168. ** 3) No parent key columns were provided explicitly as part of the
  75169. ** foreign key definition, and the parent table does not have a
  75170. ** PRIMARY KEY, or
  75171. **
  75172. ** 4) No parent key columns were provided explicitly as part of the
  75173. ** foreign key definition, and the PRIMARY KEY of the parent table
  75174. ** consists of a a different number of columns to the child key in
  75175. ** the child table.
  75176. **
  75177. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  75178. ** into pParse. If an OOM error occurs, non-zero is returned and the
  75179. ** pParse->db->mallocFailed flag is set.
  75180. */
  75181. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  75182. Parse *pParse, /* Parse context to store any error in */
  75183. Table *pParent, /* Parent table of FK constraint pFKey */
  75184. FKey *pFKey, /* Foreign key to find index for */
  75185. Index **ppIdx, /* OUT: Unique index on parent table */
  75186. int **paiCol /* OUT: Map of index columns in pFKey */
  75187. ){
  75188. Index *pIdx = 0; /* Value to return via *ppIdx */
  75189. int *aiCol = 0; /* Value to return via *paiCol */
  75190. int nCol = pFKey->nCol; /* Number of columns in parent key */
  75191. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  75192. /* The caller is responsible for zeroing output parameters. */
  75193. assert( ppIdx && *ppIdx==0 );
  75194. assert( !paiCol || *paiCol==0 );
  75195. assert( pParse );
  75196. /* If this is a non-composite (single column) foreign key, check if it
  75197. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  75198. ** and *paiCol set to zero and return early.
  75199. **
  75200. ** Otherwise, for a composite foreign key (more than one column), allocate
  75201. ** space for the aiCol array (returned via output parameter *paiCol).
  75202. ** Non-composite foreign keys do not require the aiCol array.
  75203. */
  75204. if( nCol==1 ){
  75205. /* The FK maps to the IPK if any of the following are true:
  75206. **
  75207. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  75208. ** mapped to the primary key of table pParent, or
  75209. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  75210. ** PRIMARY KEY.
  75211. */
  75212. if( pParent->iPKey>=0 ){
  75213. if( !zKey ) return 0;
  75214. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  75215. }
  75216. }else if( paiCol ){
  75217. assert( nCol>1 );
  75218. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  75219. if( !aiCol ) return 1;
  75220. *paiCol = aiCol;
  75221. }
  75222. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  75223. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  75224. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  75225. ** of columns. If each indexed column corresponds to a foreign key
  75226. ** column of pFKey, then this index is a winner. */
  75227. if( zKey==0 ){
  75228. /* If zKey is NULL, then this foreign key is implicitly mapped to
  75229. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  75230. ** identified by the test (Index.autoIndex==2). */
  75231. if( pIdx->autoIndex==2 ){
  75232. if( aiCol ){
  75233. int i;
  75234. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  75235. }
  75236. break;
  75237. }
  75238. }else{
  75239. /* If zKey is non-NULL, then this foreign key was declared to
  75240. ** map to an explicit list of columns in table pParent. Check if this
  75241. ** index matches those columns. Also, check that the index uses
  75242. ** the default collation sequences for each column. */
  75243. int i, j;
  75244. for(i=0; i<nCol; i++){
  75245. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  75246. char *zDfltColl; /* Def. collation for column */
  75247. char *zIdxCol; /* Name of indexed column */
  75248. /* If the index uses a collation sequence that is different from
  75249. ** the default collation sequence for the column, this index is
  75250. ** unusable. Bail out early in this case. */
  75251. zDfltColl = pParent->aCol[iCol].zColl;
  75252. if( !zDfltColl ){
  75253. zDfltColl = "BINARY";
  75254. }
  75255. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  75256. zIdxCol = pParent->aCol[iCol].zName;
  75257. for(j=0; j<nCol; j++){
  75258. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  75259. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  75260. break;
  75261. }
  75262. }
  75263. if( j==nCol ) break;
  75264. }
  75265. if( i==nCol ) break; /* pIdx is usable */
  75266. }
  75267. }
  75268. }
  75269. if( !pIdx ){
  75270. if( !pParse->disableTriggers ){
  75271. sqlite3ErrorMsg(pParse,
  75272. "foreign key mismatch - \"%w\" referencing \"%w\"",
  75273. pFKey->pFrom->zName, pFKey->zTo);
  75274. }
  75275. sqlite3DbFree(pParse->db, aiCol);
  75276. return 1;
  75277. }
  75278. *ppIdx = pIdx;
  75279. return 0;
  75280. }
  75281. /*
  75282. ** This function is called when a row is inserted into or deleted from the
  75283. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  75284. ** on the child table of pFKey, this function is invoked twice for each row
  75285. ** affected - once to "delete" the old row, and then again to "insert" the
  75286. ** new row.
  75287. **
  75288. ** Each time it is called, this function generates VDBE code to locate the
  75289. ** row in the parent table that corresponds to the row being inserted into
  75290. ** or deleted from the child table. If the parent row can be found, no
  75291. ** special action is taken. Otherwise, if the parent row can *not* be
  75292. ** found in the parent table:
  75293. **
  75294. ** Operation | FK type | Action taken
  75295. ** --------------------------------------------------------------------------
  75296. ** INSERT immediate Increment the "immediate constraint counter".
  75297. **
  75298. ** DELETE immediate Decrement the "immediate constraint counter".
  75299. **
  75300. ** INSERT deferred Increment the "deferred constraint counter".
  75301. **
  75302. ** DELETE deferred Decrement the "deferred constraint counter".
  75303. **
  75304. ** These operations are identified in the comment at the top of this file
  75305. ** (fkey.c) as "I.1" and "D.1".
  75306. */
  75307. static void fkLookupParent(
  75308. Parse *pParse, /* Parse context */
  75309. int iDb, /* Index of database housing pTab */
  75310. Table *pTab, /* Parent table of FK pFKey */
  75311. Index *pIdx, /* Unique index on parent key columns in pTab */
  75312. FKey *pFKey, /* Foreign key constraint */
  75313. int *aiCol, /* Map from parent key columns to child table columns */
  75314. int regData, /* Address of array containing child table row */
  75315. int nIncr, /* Increment constraint counter by this */
  75316. int isIgnore /* If true, pretend pTab contains all NULL values */
  75317. ){
  75318. int i; /* Iterator variable */
  75319. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  75320. int iCur = pParse->nTab - 1; /* Cursor number to use */
  75321. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  75322. /* If nIncr is less than zero, then check at runtime if there are any
  75323. ** outstanding constraints to resolve. If there are not, there is no need
  75324. ** to check if deleting this row resolves any outstanding violations.
  75325. **
  75326. ** Check if any of the key columns in the child table row are NULL. If
  75327. ** any are, then the constraint is considered satisfied. No need to
  75328. ** search for a matching row in the parent table. */
  75329. if( nIncr<0 ){
  75330. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  75331. }
  75332. for(i=0; i<pFKey->nCol; i++){
  75333. int iReg = aiCol[i] + regData + 1;
  75334. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  75335. }
  75336. if( isIgnore==0 ){
  75337. if( pIdx==0 ){
  75338. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  75339. ** column of the parent table (table pTab). */
  75340. int iMustBeInt; /* Address of MustBeInt instruction */
  75341. int regTemp = sqlite3GetTempReg(pParse);
  75342. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  75343. ** apply the affinity of the parent key). If this fails, then there
  75344. ** is no matching parent key. Before using MustBeInt, make a copy of
  75345. ** the value. Otherwise, the value inserted into the child key column
  75346. ** will have INTEGER affinity applied to it, which may not be correct. */
  75347. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  75348. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  75349. /* If the parent table is the same as the child table, and we are about
  75350. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  75351. ** then check if the row being inserted matches itself. If so, do not
  75352. ** increment the constraint-counter. */
  75353. if( pTab==pFKey->pFrom && nIncr==1 ){
  75354. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  75355. }
  75356. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  75357. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  75358. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  75359. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  75360. sqlite3VdbeJumpHere(v, iMustBeInt);
  75361. sqlite3ReleaseTempReg(pParse, regTemp);
  75362. }else{
  75363. int nCol = pFKey->nCol;
  75364. int regTemp = sqlite3GetTempRange(pParse, nCol);
  75365. int regRec = sqlite3GetTempReg(pParse);
  75366. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  75367. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  75368. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  75369. for(i=0; i<nCol; i++){
  75370. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  75371. }
  75372. /* If the parent table is the same as the child table, and we are about
  75373. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  75374. ** then check if the row being inserted matches itself. If so, do not
  75375. ** increment the constraint-counter.
  75376. **
  75377. ** If any of the parent-key values are NULL, then the row cannot match
  75378. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  75379. ** of the parent-key values are NULL (at this point it is known that
  75380. ** none of the child key values are).
  75381. */
  75382. if( pTab==pFKey->pFrom && nIncr==1 ){
  75383. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  75384. for(i=0; i<nCol; i++){
  75385. int iChild = aiCol[i]+1+regData;
  75386. int iParent = pIdx->aiColumn[i]+1+regData;
  75387. assert( aiCol[i]!=pTab->iPKey );
  75388. if( pIdx->aiColumn[i]==pTab->iPKey ){
  75389. /* The parent key is a composite key that includes the IPK column */
  75390. iParent = regData;
  75391. }
  75392. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  75393. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  75394. }
  75395. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  75396. }
  75397. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  75398. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  75399. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  75400. sqlite3ReleaseTempReg(pParse, regRec);
  75401. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  75402. }
  75403. }
  75404. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  75405. && !pParse->pToplevel
  75406. && !pParse->isMultiWrite
  75407. ){
  75408. /* Special case: If this is an INSERT statement that will insert exactly
  75409. ** one row into the table, raise a constraint immediately instead of
  75410. ** incrementing a counter. This is necessary as the VM code is being
  75411. ** generated for will not open a statement transaction. */
  75412. assert( nIncr==1 );
  75413. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  75414. OE_Abort, "foreign key constraint failed", P4_STATIC
  75415. );
  75416. }else{
  75417. if( nIncr>0 && pFKey->isDeferred==0 ){
  75418. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  75419. }
  75420. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  75421. }
  75422. sqlite3VdbeResolveLabel(v, iOk);
  75423. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  75424. }
  75425. /*
  75426. ** This function is called to generate code executed when a row is deleted
  75427. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  75428. ** deferred, when a row is inserted into the same table. When generating
  75429. ** code for an SQL UPDATE operation, this function may be called twice -
  75430. ** once to "delete" the old row and once to "insert" the new row.
  75431. **
  75432. ** The code generated by this function scans through the rows in the child
  75433. ** table that correspond to the parent table row being deleted or inserted.
  75434. ** For each child row found, one of the following actions is taken:
  75435. **
  75436. ** Operation | FK type | Action taken
  75437. ** --------------------------------------------------------------------------
  75438. ** DELETE immediate Increment the "immediate constraint counter".
  75439. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  75440. ** throw a "foreign key constraint failed" exception.
  75441. **
  75442. ** INSERT immediate Decrement the "immediate constraint counter".
  75443. **
  75444. ** DELETE deferred Increment the "deferred constraint counter".
  75445. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  75446. ** throw a "foreign key constraint failed" exception.
  75447. **
  75448. ** INSERT deferred Decrement the "deferred constraint counter".
  75449. **
  75450. ** These operations are identified in the comment at the top of this file
  75451. ** (fkey.c) as "I.2" and "D.2".
  75452. */
  75453. static void fkScanChildren(
  75454. Parse *pParse, /* Parse context */
  75455. SrcList *pSrc, /* SrcList containing the table to scan */
  75456. Table *pTab,
  75457. Index *pIdx, /* Foreign key index */
  75458. FKey *pFKey, /* Foreign key relationship */
  75459. int *aiCol, /* Map from pIdx cols to child table cols */
  75460. int regData, /* Referenced table data starts here */
  75461. int nIncr /* Amount to increment deferred counter by */
  75462. ){
  75463. sqlite3 *db = pParse->db; /* Database handle */
  75464. int i; /* Iterator variable */
  75465. Expr *pWhere = 0; /* WHERE clause to scan with */
  75466. NameContext sNameContext; /* Context used to resolve WHERE clause */
  75467. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  75468. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  75469. Vdbe *v = sqlite3GetVdbe(pParse);
  75470. assert( !pIdx || pIdx->pTable==pTab );
  75471. if( nIncr<0 ){
  75472. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  75473. }
  75474. /* Create an Expr object representing an SQL expression like:
  75475. **
  75476. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  75477. **
  75478. ** The collation sequence used for the comparison should be that of
  75479. ** the parent key columns. The affinity of the parent key column should
  75480. ** be applied to each child key value before the comparison takes place.
  75481. */
  75482. for(i=0; i<pFKey->nCol; i++){
  75483. Expr *pLeft; /* Value from parent table row */
  75484. Expr *pRight; /* Column ref to child table */
  75485. Expr *pEq; /* Expression (pLeft = pRight) */
  75486. int iCol; /* Index of column in child table */
  75487. const char *zCol; /* Name of column in child table */
  75488. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  75489. if( pLeft ){
  75490. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  75491. ** expression to the parent key column defaults. */
  75492. if( pIdx ){
  75493. Column *pCol;
  75494. const char *zColl;
  75495. iCol = pIdx->aiColumn[i];
  75496. pCol = &pTab->aCol[iCol];
  75497. if( pTab->iPKey==iCol ) iCol = -1;
  75498. pLeft->iTable = regData+iCol+1;
  75499. pLeft->affinity = pCol->affinity;
  75500. zColl = pCol->zColl;
  75501. if( zColl==0 ) zColl = db->pDfltColl->zName;
  75502. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  75503. }else{
  75504. pLeft->iTable = regData;
  75505. pLeft->affinity = SQLITE_AFF_INTEGER;
  75506. }
  75507. }
  75508. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  75509. assert( iCol>=0 );
  75510. zCol = pFKey->pFrom->aCol[iCol].zName;
  75511. pRight = sqlite3Expr(db, TK_ID, zCol);
  75512. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  75513. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  75514. }
  75515. /* If the child table is the same as the parent table, and this scan
  75516. ** is taking place as part of a DELETE operation (operation D.2), omit the
  75517. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  75518. ** clause, where $rowid is the rowid of the row being deleted. */
  75519. if( pTab==pFKey->pFrom && nIncr>0 ){
  75520. Expr *pEq; /* Expression (pLeft = pRight) */
  75521. Expr *pLeft; /* Value from parent table row */
  75522. Expr *pRight; /* Column ref to child table */
  75523. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  75524. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  75525. if( pLeft && pRight ){
  75526. pLeft->iTable = regData;
  75527. pLeft->affinity = SQLITE_AFF_INTEGER;
  75528. pRight->iTable = pSrc->a[0].iCursor;
  75529. pRight->iColumn = -1;
  75530. }
  75531. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  75532. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  75533. }
  75534. /* Resolve the references in the WHERE clause. */
  75535. memset(&sNameContext, 0, sizeof(NameContext));
  75536. sNameContext.pSrcList = pSrc;
  75537. sNameContext.pParse = pParse;
  75538. sqlite3ResolveExprNames(&sNameContext, pWhere);
  75539. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  75540. ** clause. If the constraint is not deferred, throw an exception for
  75541. ** each row found. Otherwise, for deferred constraints, increment the
  75542. ** deferred constraint counter by nIncr for each row selected. */
  75543. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  75544. if( nIncr>0 && pFKey->isDeferred==0 ){
  75545. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  75546. }
  75547. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  75548. if( pWInfo ){
  75549. sqlite3WhereEnd(pWInfo);
  75550. }
  75551. /* Clean up the WHERE clause constructed above. */
  75552. sqlite3ExprDelete(db, pWhere);
  75553. if( iFkIfZero ){
  75554. sqlite3VdbeJumpHere(v, iFkIfZero);
  75555. }
  75556. }
  75557. /*
  75558. ** This function returns a pointer to the head of a linked list of FK
  75559. ** constraints for which table pTab is the parent table. For example,
  75560. ** given the following schema:
  75561. **
  75562. ** CREATE TABLE t1(a PRIMARY KEY);
  75563. ** CREATE TABLE t2(b REFERENCES t1(a);
  75564. **
  75565. ** Calling this function with table "t1" as an argument returns a pointer
  75566. ** to the FKey structure representing the foreign key constraint on table
  75567. ** "t2". Calling this function with "t2" as the argument would return a
  75568. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  75569. ** table).
  75570. */
  75571. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  75572. int nName = sqlite3Strlen30(pTab->zName);
  75573. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  75574. }
  75575. /*
  75576. ** The second argument is a Trigger structure allocated by the
  75577. ** fkActionTrigger() routine. This function deletes the Trigger structure
  75578. ** and all of its sub-components.
  75579. **
  75580. ** The Trigger structure or any of its sub-components may be allocated from
  75581. ** the lookaside buffer belonging to database handle dbMem.
  75582. */
  75583. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  75584. if( p ){
  75585. TriggerStep *pStep = p->step_list;
  75586. sqlite3ExprDelete(dbMem, pStep->pWhere);
  75587. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  75588. sqlite3SelectDelete(dbMem, pStep->pSelect);
  75589. sqlite3ExprDelete(dbMem, p->pWhen);
  75590. sqlite3DbFree(dbMem, p);
  75591. }
  75592. }
  75593. /*
  75594. ** This function is called to generate code that runs when table pTab is
  75595. ** being dropped from the database. The SrcList passed as the second argument
  75596. ** to this function contains a single entry guaranteed to resolve to
  75597. ** table pTab.
  75598. **
  75599. ** Normally, no code is required. However, if either
  75600. **
  75601. ** (a) The table is the parent table of a FK constraint, or
  75602. ** (b) The table is the child table of a deferred FK constraint and it is
  75603. ** determined at runtime that there are outstanding deferred FK
  75604. ** constraint violations in the database,
  75605. **
  75606. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  75607. ** the table from the database. Triggers are disabled while running this
  75608. ** DELETE, but foreign key actions are not.
  75609. */
  75610. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  75611. sqlite3 *db = pParse->db;
  75612. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  75613. int iSkip = 0;
  75614. Vdbe *v = sqlite3GetVdbe(pParse);
  75615. assert( v ); /* VDBE has already been allocated */
  75616. if( sqlite3FkReferences(pTab)==0 ){
  75617. /* Search for a deferred foreign key constraint for which this table
  75618. ** is the child table. If one cannot be found, return without
  75619. ** generating any VDBE code. If one can be found, then jump over
  75620. ** the entire DELETE if there are no outstanding deferred constraints
  75621. ** when this statement is run. */
  75622. FKey *p;
  75623. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75624. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  75625. }
  75626. if( !p ) return;
  75627. iSkip = sqlite3VdbeMakeLabel(v);
  75628. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  75629. }
  75630. pParse->disableTriggers = 1;
  75631. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  75632. pParse->disableTriggers = 0;
  75633. /* If the DELETE has generated immediate foreign key constraint
  75634. ** violations, halt the VDBE and return an error at this point, before
  75635. ** any modifications to the schema are made. This is because statement
  75636. ** transactions are not able to rollback schema changes.
  75637. **
  75638. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  75639. ** the statement transaction will not be rolled back even if FK
  75640. ** constraints are violated.
  75641. */
  75642. if( (db->flags & SQLITE_DeferFKs)==0 ){
  75643. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  75644. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  75645. OE_Abort, "foreign key constraint failed", P4_STATIC
  75646. );
  75647. }
  75648. if( iSkip ){
  75649. sqlite3VdbeResolveLabel(v, iSkip);
  75650. }
  75651. }
  75652. }
  75653. /*
  75654. ** The second argument points to an FKey object representing a foreign key
  75655. ** for which pTab is the child table. An UPDATE statement against pTab
  75656. ** is currently being processed. For each column of the table that is
  75657. ** actually updated, the corresponding element in the aChange[] array
  75658. ** is zero or greater (if a column is unmodified the corresponding element
  75659. ** is set to -1). If the rowid column is modified by the UPDATE statement
  75660. ** the bChngRowid argument is non-zero.
  75661. **
  75662. ** This function returns true if any of the columns that are part of the
  75663. ** child key for FK constraint *p are modified.
  75664. */
  75665. static int fkChildIsModified(
  75666. Table *pTab, /* Table being updated */
  75667. FKey *p, /* Foreign key for which pTab is the child */
  75668. int *aChange, /* Array indicating modified columns */
  75669. int bChngRowid /* True if rowid is modified by this update */
  75670. ){
  75671. int i;
  75672. for(i=0; i<p->nCol; i++){
  75673. int iChildKey = p->aCol[i].iFrom;
  75674. if( aChange[iChildKey]>=0 ) return 1;
  75675. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  75676. }
  75677. return 0;
  75678. }
  75679. /*
  75680. ** The second argument points to an FKey object representing a foreign key
  75681. ** for which pTab is the parent table. An UPDATE statement against pTab
  75682. ** is currently being processed. For each column of the table that is
  75683. ** actually updated, the corresponding element in the aChange[] array
  75684. ** is zero or greater (if a column is unmodified the corresponding element
  75685. ** is set to -1). If the rowid column is modified by the UPDATE statement
  75686. ** the bChngRowid argument is non-zero.
  75687. **
  75688. ** This function returns true if any of the columns that are part of the
  75689. ** parent key for FK constraint *p are modified.
  75690. */
  75691. static int fkParentIsModified(
  75692. Table *pTab,
  75693. FKey *p,
  75694. int *aChange,
  75695. int bChngRowid
  75696. ){
  75697. int i;
  75698. for(i=0; i<p->nCol; i++){
  75699. char *zKey = p->aCol[i].zCol;
  75700. int iKey;
  75701. for(iKey=0; iKey<pTab->nCol; iKey++){
  75702. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  75703. Column *pCol = &pTab->aCol[iKey];
  75704. if( zKey ){
  75705. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  75706. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  75707. return 1;
  75708. }
  75709. }
  75710. }
  75711. }
  75712. return 0;
  75713. }
  75714. /*
  75715. ** This function is called when inserting, deleting or updating a row of
  75716. ** table pTab to generate VDBE code to perform foreign key constraint
  75717. ** processing for the operation.
  75718. **
  75719. ** For a DELETE operation, parameter regOld is passed the index of the
  75720. ** first register in an array of (pTab->nCol+1) registers containing the
  75721. ** rowid of the row being deleted, followed by each of the column values
  75722. ** of the row being deleted, from left to right. Parameter regNew is passed
  75723. ** zero in this case.
  75724. **
  75725. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  75726. ** first register of an array of (pTab->nCol+1) registers containing the new
  75727. ** row data.
  75728. **
  75729. ** For an UPDATE operation, this function is called twice. Once before
  75730. ** the original record is deleted from the table using the calling convention
  75731. ** described for DELETE. Then again after the original record is deleted
  75732. ** but before the new record is inserted using the INSERT convention.
  75733. */
  75734. SQLITE_PRIVATE void sqlite3FkCheck(
  75735. Parse *pParse, /* Parse context */
  75736. Table *pTab, /* Row is being deleted from this table */
  75737. int regOld, /* Previous row data is stored here */
  75738. int regNew, /* New row data is stored here */
  75739. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  75740. int bChngRowid /* True if rowid is UPDATEd */
  75741. ){
  75742. sqlite3 *db = pParse->db; /* Database handle */
  75743. FKey *pFKey; /* Used to iterate through FKs */
  75744. int iDb; /* Index of database containing pTab */
  75745. const char *zDb; /* Name of database containing pTab */
  75746. int isIgnoreErrors = pParse->disableTriggers;
  75747. /* Exactly one of regOld and regNew should be non-zero. */
  75748. assert( (regOld==0)!=(regNew==0) );
  75749. /* If foreign-keys are disabled, this function is a no-op. */
  75750. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  75751. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75752. zDb = db->aDb[iDb].zName;
  75753. /* Loop through all the foreign key constraints for which pTab is the
  75754. ** child table (the table that the foreign key definition is part of). */
  75755. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  75756. Table *pTo; /* Parent table of foreign key pFKey */
  75757. Index *pIdx = 0; /* Index on key columns in pTo */
  75758. int *aiFree = 0;
  75759. int *aiCol;
  75760. int iCol;
  75761. int i;
  75762. int isIgnore = 0;
  75763. if( aChange
  75764. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  75765. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  75766. ){
  75767. continue;
  75768. }
  75769. /* Find the parent table of this foreign key. Also find a unique index
  75770. ** on the parent key columns in the parent table. If either of these
  75771. ** schema items cannot be located, set an error in pParse and return
  75772. ** early. */
  75773. if( pParse->disableTriggers ){
  75774. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  75775. }else{
  75776. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  75777. }
  75778. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  75779. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  75780. if( !isIgnoreErrors || db->mallocFailed ) return;
  75781. if( pTo==0 ){
  75782. /* If isIgnoreErrors is true, then a table is being dropped. In this
  75783. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  75784. ** before actually dropping it in order to check FK constraints.
  75785. ** If the parent table of an FK constraint on the current table is
  75786. ** missing, behave as if it is empty. i.e. decrement the relevant
  75787. ** FK counter for each row of the current table with non-NULL keys.
  75788. */
  75789. Vdbe *v = sqlite3GetVdbe(pParse);
  75790. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  75791. for(i=0; i<pFKey->nCol; i++){
  75792. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  75793. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  75794. }
  75795. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  75796. }
  75797. continue;
  75798. }
  75799. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  75800. if( aiFree ){
  75801. aiCol = aiFree;
  75802. }else{
  75803. iCol = pFKey->aCol[0].iFrom;
  75804. aiCol = &iCol;
  75805. }
  75806. for(i=0; i<pFKey->nCol; i++){
  75807. if( aiCol[i]==pTab->iPKey ){
  75808. aiCol[i] = -1;
  75809. }
  75810. #ifndef SQLITE_OMIT_AUTHORIZATION
  75811. /* Request permission to read the parent key columns. If the
  75812. ** authorization callback returns SQLITE_IGNORE, behave as if any
  75813. ** values read from the parent table are NULL. */
  75814. if( db->xAuth ){
  75815. int rcauth;
  75816. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  75817. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  75818. isIgnore = (rcauth==SQLITE_IGNORE);
  75819. }
  75820. #endif
  75821. }
  75822. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  75823. ** a cursor to use to search the unique index on the parent key columns
  75824. ** in the parent table. */
  75825. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  75826. pParse->nTab++;
  75827. if( regOld!=0 ){
  75828. /* A row is being removed from the child table. Search for the parent.
  75829. ** If the parent does not exist, removing the child row resolves an
  75830. ** outstanding foreign key constraint violation. */
  75831. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  75832. }
  75833. if( regNew!=0 ){
  75834. /* A row is being added to the child table. If a parent row cannot
  75835. ** be found, adding the child row has violated the FK constraint. */
  75836. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  75837. }
  75838. sqlite3DbFree(db, aiFree);
  75839. }
  75840. /* Loop through all the foreign key constraints that refer to this table */
  75841. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  75842. Index *pIdx = 0; /* Foreign key index for pFKey */
  75843. SrcList *pSrc;
  75844. int *aiCol = 0;
  75845. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  75846. continue;
  75847. }
  75848. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  75849. && !pParse->pToplevel && !pParse->isMultiWrite
  75850. ){
  75851. assert( regOld==0 && regNew!=0 );
  75852. /* Inserting a single row into a parent table cannot cause an immediate
  75853. ** foreign key violation. So do nothing in this case. */
  75854. continue;
  75855. }
  75856. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  75857. if( !isIgnoreErrors || db->mallocFailed ) return;
  75858. continue;
  75859. }
  75860. assert( aiCol || pFKey->nCol==1 );
  75861. /* Create a SrcList structure containing a single table (the table
  75862. ** the foreign key that refers to this table is attached to). This
  75863. ** is required for the sqlite3WhereXXX() interface. */
  75864. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  75865. if( pSrc ){
  75866. struct SrcList_item *pItem = pSrc->a;
  75867. pItem->pTab = pFKey->pFrom;
  75868. pItem->zName = pFKey->pFrom->zName;
  75869. pItem->pTab->nRef++;
  75870. pItem->iCursor = pParse->nTab++;
  75871. if( regNew!=0 ){
  75872. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  75873. }
  75874. if( regOld!=0 ){
  75875. /* If there is a RESTRICT action configured for the current operation
  75876. ** on the parent table of this FK, then throw an exception
  75877. ** immediately if the FK constraint is violated, even if this is a
  75878. ** deferred trigger. That's what RESTRICT means. To defer checking
  75879. ** the constraint, the FK should specify NO ACTION (represented
  75880. ** using OE_None). NO ACTION is the default. */
  75881. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  75882. }
  75883. pItem->zName = 0;
  75884. sqlite3SrcListDelete(db, pSrc);
  75885. }
  75886. sqlite3DbFree(db, aiCol);
  75887. }
  75888. }
  75889. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  75890. /*
  75891. ** This function is called before generating code to update or delete a
  75892. ** row contained in table pTab.
  75893. */
  75894. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  75895. Parse *pParse, /* Parse context */
  75896. Table *pTab /* Table being modified */
  75897. ){
  75898. u32 mask = 0;
  75899. if( pParse->db->flags&SQLITE_ForeignKeys ){
  75900. FKey *p;
  75901. int i;
  75902. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75903. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  75904. }
  75905. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75906. Index *pIdx = 0;
  75907. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  75908. if( pIdx ){
  75909. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  75910. }
  75911. }
  75912. }
  75913. return mask;
  75914. }
  75915. /*
  75916. ** This function is called before generating code to update or delete a
  75917. ** row contained in table pTab. If the operation is a DELETE, then
  75918. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  75919. ** to an array of size N, where N is the number of columns in table pTab.
  75920. ** If the i'th column is not modified by the UPDATE, then the corresponding
  75921. ** entry in the aChange[] array is set to -1. If the column is modified,
  75922. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  75923. ** UPDATE statement modifies the rowid fields of the table.
  75924. **
  75925. ** If any foreign key processing will be required, this function returns
  75926. ** true. If there is no foreign key related processing, this function
  75927. ** returns false.
  75928. */
  75929. SQLITE_PRIVATE int sqlite3FkRequired(
  75930. Parse *pParse, /* Parse context */
  75931. Table *pTab, /* Table being modified */
  75932. int *aChange, /* Non-NULL for UPDATE operations */
  75933. int chngRowid /* True for UPDATE that affects rowid */
  75934. ){
  75935. if( pParse->db->flags&SQLITE_ForeignKeys ){
  75936. if( !aChange ){
  75937. /* A DELETE operation. Foreign key processing is required if the
  75938. ** table in question is either the child or parent table for any
  75939. ** foreign key constraint. */
  75940. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  75941. }else{
  75942. /* This is an UPDATE. Foreign key processing is only required if the
  75943. ** operation modifies one or more child or parent key columns. */
  75944. FKey *p;
  75945. /* Check if any child key columns are being modified. */
  75946. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75947. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  75948. }
  75949. /* Check if any parent key columns are being modified. */
  75950. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75951. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  75952. }
  75953. }
  75954. }
  75955. return 0;
  75956. }
  75957. /*
  75958. ** This function is called when an UPDATE or DELETE operation is being
  75959. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  75960. ** If the current operation is an UPDATE, then the pChanges parameter is
  75961. ** passed a pointer to the list of columns being modified. If it is a
  75962. ** DELETE, pChanges is passed a NULL pointer.
  75963. **
  75964. ** It returns a pointer to a Trigger structure containing a trigger
  75965. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  75966. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  75967. ** returned (these actions require no special handling by the triggers
  75968. ** sub-system, code for them is created by fkScanChildren()).
  75969. **
  75970. ** For example, if pFKey is the foreign key and pTab is table "p" in
  75971. ** the following schema:
  75972. **
  75973. ** CREATE TABLE p(pk PRIMARY KEY);
  75974. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  75975. **
  75976. ** then the returned trigger structure is equivalent to:
  75977. **
  75978. ** CREATE TRIGGER ... DELETE ON p BEGIN
  75979. ** DELETE FROM c WHERE ck = old.pk;
  75980. ** END;
  75981. **
  75982. ** The returned pointer is cached as part of the foreign key object. It
  75983. ** is eventually freed along with the rest of the foreign key object by
  75984. ** sqlite3FkDelete().
  75985. */
  75986. static Trigger *fkActionTrigger(
  75987. Parse *pParse, /* Parse context */
  75988. Table *pTab, /* Table being updated or deleted from */
  75989. FKey *pFKey, /* Foreign key to get action for */
  75990. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  75991. ){
  75992. sqlite3 *db = pParse->db; /* Database handle */
  75993. int action; /* One of OE_None, OE_Cascade etc. */
  75994. Trigger *pTrigger; /* Trigger definition to return */
  75995. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  75996. action = pFKey->aAction[iAction];
  75997. pTrigger = pFKey->apTrigger[iAction];
  75998. if( action!=OE_None && !pTrigger ){
  75999. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  76000. char const *zFrom; /* Name of child table */
  76001. int nFrom; /* Length in bytes of zFrom */
  76002. Index *pIdx = 0; /* Parent key index for this FK */
  76003. int *aiCol = 0; /* child table cols -> parent key cols */
  76004. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  76005. Expr *pWhere = 0; /* WHERE clause of trigger step */
  76006. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  76007. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  76008. int i; /* Iterator variable */
  76009. Expr *pWhen = 0; /* WHEN clause for the trigger */
  76010. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  76011. assert( aiCol || pFKey->nCol==1 );
  76012. for(i=0; i<pFKey->nCol; i++){
  76013. Token tOld = { "old", 3 }; /* Literal "old" token */
  76014. Token tNew = { "new", 3 }; /* Literal "new" token */
  76015. Token tFromCol; /* Name of column in child table */
  76016. Token tToCol; /* Name of column in parent table */
  76017. int iFromCol; /* Idx of column in child table */
  76018. Expr *pEq; /* tFromCol = OLD.tToCol */
  76019. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  76020. assert( iFromCol>=0 );
  76021. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  76022. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  76023. tToCol.n = sqlite3Strlen30(tToCol.z);
  76024. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  76025. /* Create the expression "OLD.zToCol = zFromCol". It is important
  76026. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  76027. ** that the affinity and collation sequence associated with the
  76028. ** parent table are used for the comparison. */
  76029. pEq = sqlite3PExpr(pParse, TK_EQ,
  76030. sqlite3PExpr(pParse, TK_DOT,
  76031. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  76032. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  76033. , 0),
  76034. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  76035. , 0);
  76036. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  76037. /* For ON UPDATE, construct the next term of the WHEN clause.
  76038. ** The final WHEN clause will be like this:
  76039. **
  76040. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  76041. */
  76042. if( pChanges ){
  76043. pEq = sqlite3PExpr(pParse, TK_IS,
  76044. sqlite3PExpr(pParse, TK_DOT,
  76045. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  76046. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  76047. 0),
  76048. sqlite3PExpr(pParse, TK_DOT,
  76049. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  76050. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  76051. 0),
  76052. 0);
  76053. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  76054. }
  76055. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  76056. Expr *pNew;
  76057. if( action==OE_Cascade ){
  76058. pNew = sqlite3PExpr(pParse, TK_DOT,
  76059. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  76060. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  76061. , 0);
  76062. }else if( action==OE_SetDflt ){
  76063. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  76064. if( pDflt ){
  76065. pNew = sqlite3ExprDup(db, pDflt, 0);
  76066. }else{
  76067. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  76068. }
  76069. }else{
  76070. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  76071. }
  76072. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  76073. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  76074. }
  76075. }
  76076. sqlite3DbFree(db, aiCol);
  76077. zFrom = pFKey->pFrom->zName;
  76078. nFrom = sqlite3Strlen30(zFrom);
  76079. if( action==OE_Restrict ){
  76080. Token tFrom;
  76081. Expr *pRaise;
  76082. tFrom.z = zFrom;
  76083. tFrom.n = nFrom;
  76084. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  76085. if( pRaise ){
  76086. pRaise->affinity = OE_Abort;
  76087. }
  76088. pSelect = sqlite3SelectNew(pParse,
  76089. sqlite3ExprListAppend(pParse, 0, pRaise),
  76090. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  76091. pWhere,
  76092. 0, 0, 0, 0, 0, 0
  76093. );
  76094. pWhere = 0;
  76095. }
  76096. /* Disable lookaside memory allocation */
  76097. enableLookaside = db->lookaside.bEnabled;
  76098. db->lookaside.bEnabled = 0;
  76099. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  76100. sizeof(Trigger) + /* struct Trigger */
  76101. sizeof(TriggerStep) + /* Single step in trigger program */
  76102. nFrom + 1 /* Space for pStep->target.z */
  76103. );
  76104. if( pTrigger ){
  76105. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  76106. pStep->target.z = (char *)&pStep[1];
  76107. pStep->target.n = nFrom;
  76108. memcpy((char *)pStep->target.z, zFrom, nFrom);
  76109. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  76110. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  76111. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  76112. if( pWhen ){
  76113. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  76114. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  76115. }
  76116. }
  76117. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  76118. db->lookaside.bEnabled = enableLookaside;
  76119. sqlite3ExprDelete(db, pWhere);
  76120. sqlite3ExprDelete(db, pWhen);
  76121. sqlite3ExprListDelete(db, pList);
  76122. sqlite3SelectDelete(db, pSelect);
  76123. if( db->mallocFailed==1 ){
  76124. fkTriggerDelete(db, pTrigger);
  76125. return 0;
  76126. }
  76127. assert( pStep!=0 );
  76128. switch( action ){
  76129. case OE_Restrict:
  76130. pStep->op = TK_SELECT;
  76131. break;
  76132. case OE_Cascade:
  76133. if( !pChanges ){
  76134. pStep->op = TK_DELETE;
  76135. break;
  76136. }
  76137. default:
  76138. pStep->op = TK_UPDATE;
  76139. }
  76140. pStep->pTrig = pTrigger;
  76141. pTrigger->pSchema = pTab->pSchema;
  76142. pTrigger->pTabSchema = pTab->pSchema;
  76143. pFKey->apTrigger[iAction] = pTrigger;
  76144. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  76145. }
  76146. return pTrigger;
  76147. }
  76148. /*
  76149. ** This function is called when deleting or updating a row to implement
  76150. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  76151. */
  76152. SQLITE_PRIVATE void sqlite3FkActions(
  76153. Parse *pParse, /* Parse context */
  76154. Table *pTab, /* Table being updated or deleted from */
  76155. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  76156. int regOld, /* Address of array containing old row */
  76157. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  76158. int bChngRowid /* True if rowid is UPDATEd */
  76159. ){
  76160. /* If foreign-key support is enabled, iterate through all FKs that
  76161. ** refer to table pTab. If there is an action associated with the FK
  76162. ** for this operation (either update or delete), invoke the associated
  76163. ** trigger sub-program. */
  76164. if( pParse->db->flags&SQLITE_ForeignKeys ){
  76165. FKey *pFKey; /* Iterator variable */
  76166. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  76167. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  76168. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  76169. if( pAct ){
  76170. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  76171. }
  76172. }
  76173. }
  76174. }
  76175. }
  76176. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  76177. /*
  76178. ** Free all memory associated with foreign key definitions attached to
  76179. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  76180. ** hash table.
  76181. */
  76182. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  76183. FKey *pFKey; /* Iterator variable */
  76184. FKey *pNext; /* Copy of pFKey->pNextFrom */
  76185. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  76186. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  76187. /* Remove the FK from the fkeyHash hash table. */
  76188. if( !db || db->pnBytesFreed==0 ){
  76189. if( pFKey->pPrevTo ){
  76190. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  76191. }else{
  76192. void *p = (void *)pFKey->pNextTo;
  76193. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  76194. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  76195. }
  76196. if( pFKey->pNextTo ){
  76197. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  76198. }
  76199. }
  76200. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  76201. ** classified as either immediate or deferred.
  76202. */
  76203. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  76204. /* Delete any triggers created to implement actions for this FK. */
  76205. #ifndef SQLITE_OMIT_TRIGGER
  76206. fkTriggerDelete(db, pFKey->apTrigger[0]);
  76207. fkTriggerDelete(db, pFKey->apTrigger[1]);
  76208. #endif
  76209. pNext = pFKey->pNextFrom;
  76210. sqlite3DbFree(db, pFKey);
  76211. }
  76212. }
  76213. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  76214. /************** End of fkey.c ************************************************/
  76215. /************** Begin file insert.c ******************************************/
  76216. /*
  76217. ** 2001 September 15
  76218. **
  76219. ** The author disclaims copyright to this source code. In place of
  76220. ** a legal notice, here is a blessing:
  76221. **
  76222. ** May you do good and not evil.
  76223. ** May you find forgiveness for yourself and forgive others.
  76224. ** May you share freely, never taking more than you give.
  76225. **
  76226. *************************************************************************
  76227. ** This file contains C code routines that are called by the parser
  76228. ** to handle INSERT statements in SQLite.
  76229. */
  76230. /*
  76231. ** Generate code that will open a table for reading.
  76232. */
  76233. SQLITE_PRIVATE void sqlite3OpenTable(
  76234. Parse *p, /* Generate code into this VDBE */
  76235. int iCur, /* The cursor number of the table */
  76236. int iDb, /* The database index in sqlite3.aDb[] */
  76237. Table *pTab, /* The table to be opened */
  76238. int opcode /* OP_OpenRead or OP_OpenWrite */
  76239. ){
  76240. Vdbe *v;
  76241. assert( !IsVirtual(pTab) );
  76242. v = sqlite3GetVdbe(p);
  76243. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  76244. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  76245. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  76246. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  76247. VdbeComment((v, "%s", pTab->zName));
  76248. }
  76249. /*
  76250. ** Return a pointer to the column affinity string associated with index
  76251. ** pIdx. A column affinity string has one character for each column in
  76252. ** the table, according to the affinity of the column:
  76253. **
  76254. ** Character Column affinity
  76255. ** ------------------------------
  76256. ** 'a' TEXT
  76257. ** 'b' NONE
  76258. ** 'c' NUMERIC
  76259. ** 'd' INTEGER
  76260. ** 'e' REAL
  76261. **
  76262. ** An extra 'd' is appended to the end of the string to cover the
  76263. ** rowid that appears as the last column in every index.
  76264. **
  76265. ** Memory for the buffer containing the column index affinity string
  76266. ** is managed along with the rest of the Index structure. It will be
  76267. ** released when sqlite3DeleteIndex() is called.
  76268. */
  76269. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  76270. if( !pIdx->zColAff ){
  76271. /* The first time a column affinity string for a particular index is
  76272. ** required, it is allocated and populated here. It is then stored as
  76273. ** a member of the Index structure for subsequent use.
  76274. **
  76275. ** The column affinity string will eventually be deleted by
  76276. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  76277. ** up.
  76278. */
  76279. int n;
  76280. Table *pTab = pIdx->pTable;
  76281. sqlite3 *db = sqlite3VdbeDb(v);
  76282. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  76283. if( !pIdx->zColAff ){
  76284. db->mallocFailed = 1;
  76285. return 0;
  76286. }
  76287. for(n=0; n<pIdx->nColumn; n++){
  76288. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  76289. }
  76290. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  76291. pIdx->zColAff[n] = 0;
  76292. }
  76293. return pIdx->zColAff;
  76294. }
  76295. /*
  76296. ** Set P4 of the most recently inserted opcode to a column affinity
  76297. ** string for table pTab. A column affinity string has one character
  76298. ** for each column indexed by the index, according to the affinity of the
  76299. ** column:
  76300. **
  76301. ** Character Column affinity
  76302. ** ------------------------------
  76303. ** 'a' TEXT
  76304. ** 'b' NONE
  76305. ** 'c' NUMERIC
  76306. ** 'd' INTEGER
  76307. ** 'e' REAL
  76308. */
  76309. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  76310. /* The first time a column affinity string for a particular table
  76311. ** is required, it is allocated and populated here. It is then
  76312. ** stored as a member of the Table structure for subsequent use.
  76313. **
  76314. ** The column affinity string will eventually be deleted by
  76315. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  76316. */
  76317. if( !pTab->zColAff ){
  76318. char *zColAff;
  76319. int i;
  76320. sqlite3 *db = sqlite3VdbeDb(v);
  76321. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  76322. if( !zColAff ){
  76323. db->mallocFailed = 1;
  76324. return;
  76325. }
  76326. for(i=0; i<pTab->nCol; i++){
  76327. zColAff[i] = pTab->aCol[i].affinity;
  76328. }
  76329. zColAff[pTab->nCol] = '\0';
  76330. pTab->zColAff = zColAff;
  76331. }
  76332. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  76333. }
  76334. /*
  76335. ** Return non-zero if the table pTab in database iDb or any of its indices
  76336. ** have been opened at any point in the VDBE program beginning at location
  76337. ** iStartAddr throught the end of the program. This is used to see if
  76338. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  76339. ** run without using temporary table for the results of the SELECT.
  76340. */
  76341. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  76342. Vdbe *v = sqlite3GetVdbe(p);
  76343. int i;
  76344. int iEnd = sqlite3VdbeCurrentAddr(v);
  76345. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76346. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  76347. #endif
  76348. for(i=iStartAddr; i<iEnd; i++){
  76349. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  76350. assert( pOp!=0 );
  76351. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  76352. Index *pIndex;
  76353. int tnum = pOp->p2;
  76354. if( tnum==pTab->tnum ){
  76355. return 1;
  76356. }
  76357. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  76358. if( tnum==pIndex->tnum ){
  76359. return 1;
  76360. }
  76361. }
  76362. }
  76363. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76364. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  76365. assert( pOp->p4.pVtab!=0 );
  76366. assert( pOp->p4type==P4_VTAB );
  76367. return 1;
  76368. }
  76369. #endif
  76370. }
  76371. return 0;
  76372. }
  76373. #ifndef SQLITE_OMIT_AUTOINCREMENT
  76374. /*
  76375. ** Locate or create an AutoincInfo structure associated with table pTab
  76376. ** which is in database iDb. Return the register number for the register
  76377. ** that holds the maximum rowid.
  76378. **
  76379. ** There is at most one AutoincInfo structure per table even if the
  76380. ** same table is autoincremented multiple times due to inserts within
  76381. ** triggers. A new AutoincInfo structure is created if this is the
  76382. ** first use of table pTab. On 2nd and subsequent uses, the original
  76383. ** AutoincInfo structure is used.
  76384. **
  76385. ** Three memory locations are allocated:
  76386. **
  76387. ** (1) Register to hold the name of the pTab table.
  76388. ** (2) Register to hold the maximum ROWID of pTab.
  76389. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  76390. **
  76391. ** The 2nd register is the one that is returned. That is all the
  76392. ** insert routine needs to know about.
  76393. */
  76394. static int autoIncBegin(
  76395. Parse *pParse, /* Parsing context */
  76396. int iDb, /* Index of the database holding pTab */
  76397. Table *pTab /* The table we are writing to */
  76398. ){
  76399. int memId = 0; /* Register holding maximum rowid */
  76400. if( pTab->tabFlags & TF_Autoincrement ){
  76401. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  76402. AutoincInfo *pInfo;
  76403. pInfo = pToplevel->pAinc;
  76404. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  76405. if( pInfo==0 ){
  76406. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  76407. if( pInfo==0 ) return 0;
  76408. pInfo->pNext = pToplevel->pAinc;
  76409. pToplevel->pAinc = pInfo;
  76410. pInfo->pTab = pTab;
  76411. pInfo->iDb = iDb;
  76412. pToplevel->nMem++; /* Register to hold name of table */
  76413. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  76414. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  76415. }
  76416. memId = pInfo->regCtr;
  76417. }
  76418. return memId;
  76419. }
  76420. /*
  76421. ** This routine generates code that will initialize all of the
  76422. ** register used by the autoincrement tracker.
  76423. */
  76424. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  76425. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  76426. sqlite3 *db = pParse->db; /* The database connection */
  76427. Db *pDb; /* Database only autoinc table */
  76428. int memId; /* Register holding max rowid */
  76429. int addr; /* A VDBE address */
  76430. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  76431. /* This routine is never called during trigger-generation. It is
  76432. ** only called from the top-level */
  76433. assert( pParse->pTriggerTab==0 );
  76434. assert( pParse==sqlite3ParseToplevel(pParse) );
  76435. assert( v ); /* We failed long ago if this is not so */
  76436. for(p = pParse->pAinc; p; p = p->pNext){
  76437. pDb = &db->aDb[p->iDb];
  76438. memId = p->regCtr;
  76439. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  76440. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  76441. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  76442. addr = sqlite3VdbeCurrentAddr(v);
  76443. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  76444. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  76445. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  76446. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  76447. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  76448. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  76449. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  76450. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  76451. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  76452. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  76453. sqlite3VdbeAddOp0(v, OP_Close);
  76454. }
  76455. }
  76456. /*
  76457. ** Update the maximum rowid for an autoincrement calculation.
  76458. **
  76459. ** This routine should be called when the top of the stack holds a
  76460. ** new rowid that is about to be inserted. If that new rowid is
  76461. ** larger than the maximum rowid in the memId memory cell, then the
  76462. ** memory cell is updated. The stack is unchanged.
  76463. */
  76464. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  76465. if( memId>0 ){
  76466. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  76467. }
  76468. }
  76469. /*
  76470. ** This routine generates the code needed to write autoincrement
  76471. ** maximum rowid values back into the sqlite_sequence register.
  76472. ** Every statement that might do an INSERT into an autoincrement
  76473. ** table (either directly or through triggers) needs to call this
  76474. ** routine just before the "exit" code.
  76475. */
  76476. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  76477. AutoincInfo *p;
  76478. Vdbe *v = pParse->pVdbe;
  76479. sqlite3 *db = pParse->db;
  76480. assert( v );
  76481. for(p = pParse->pAinc; p; p = p->pNext){
  76482. Db *pDb = &db->aDb[p->iDb];
  76483. int j1, j2, j3, j4, j5;
  76484. int iRec;
  76485. int memId = p->regCtr;
  76486. iRec = sqlite3GetTempReg(pParse);
  76487. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  76488. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  76489. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  76490. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  76491. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  76492. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  76493. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  76494. sqlite3VdbeJumpHere(v, j2);
  76495. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  76496. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  76497. sqlite3VdbeJumpHere(v, j4);
  76498. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  76499. sqlite3VdbeJumpHere(v, j1);
  76500. sqlite3VdbeJumpHere(v, j5);
  76501. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  76502. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  76503. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  76504. sqlite3VdbeAddOp0(v, OP_Close);
  76505. sqlite3ReleaseTempReg(pParse, iRec);
  76506. }
  76507. }
  76508. #else
  76509. /*
  76510. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  76511. ** above are all no-ops
  76512. */
  76513. # define autoIncBegin(A,B,C) (0)
  76514. # define autoIncStep(A,B,C)
  76515. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  76516. /*
  76517. ** Generate code for a co-routine that will evaluate a subquery one
  76518. ** row at a time.
  76519. **
  76520. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  76521. ** Information about the location of co-routine and the registers it will use
  76522. ** is returned by filling in the pDest object.
  76523. **
  76524. ** Registers are allocated as follows:
  76525. **
  76526. ** pDest->iSDParm The register holding the next entry-point of the
  76527. ** co-routine. Run the co-routine to its next breakpoint
  76528. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  76529. **
  76530. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  76531. ** co-routine. This register is 0 if the previous Yield
  76532. ** generated a new result row, or 1 if the subquery
  76533. ** has completed. If the Yield is called again
  76534. ** after this register becomes 1, then the VDBE will
  76535. ** halt with an SQLITE_INTERNAL error.
  76536. **
  76537. ** pDest->iSdst First result register.
  76538. **
  76539. ** pDest->nSdst Number of result registers.
  76540. **
  76541. ** This routine handles all of the register allocation and fills in the
  76542. ** pDest structure appropriately.
  76543. **
  76544. ** Here is a schematic of the generated code assuming that X is the
  76545. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  76546. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  76547. ** registers that hold the result set, reg[pDest->iSdst] through
  76548. ** reg[pDest->iSdst+pDest->nSdst-1]:
  76549. **
  76550. ** X <- A
  76551. ** EOF <- 0
  76552. ** goto B
  76553. ** A: setup for the SELECT
  76554. ** loop rows in the SELECT
  76555. ** load results into registers R..S
  76556. ** yield X
  76557. ** end loop
  76558. ** cleanup after the SELECT
  76559. ** EOF <- 1
  76560. ** yield X
  76561. ** halt-error
  76562. ** B:
  76563. **
  76564. ** To use this subroutine, the caller generates code as follows:
  76565. **
  76566. ** [ Co-routine generated by this subroutine, shown above ]
  76567. ** S: yield X
  76568. ** if EOF goto E
  76569. ** if skip this row, goto C
  76570. ** if terminate loop, goto E
  76571. ** deal with this row
  76572. ** C: goto S
  76573. ** E:
  76574. */
  76575. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  76576. int regYield; /* Register holding co-routine entry-point */
  76577. int regEof; /* Register holding co-routine completion flag */
  76578. int addrTop; /* Top of the co-routine */
  76579. int j1; /* Jump instruction */
  76580. int rc; /* Result code */
  76581. Vdbe *v; /* VDBE under construction */
  76582. regYield = ++pParse->nMem;
  76583. regEof = ++pParse->nMem;
  76584. v = sqlite3GetVdbe(pParse);
  76585. addrTop = sqlite3VdbeCurrentAddr(v);
  76586. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  76587. VdbeComment((v, "Co-routine entry point"));
  76588. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  76589. VdbeComment((v, "Co-routine completion flag"));
  76590. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  76591. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  76592. rc = sqlite3Select(pParse, pSelect, pDest);
  76593. assert( pParse->nErr==0 || rc );
  76594. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  76595. if( rc ) return rc;
  76596. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  76597. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  76598. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  76599. VdbeComment((v, "End of coroutine"));
  76600. sqlite3VdbeJumpHere(v, j1); /* label B: */
  76601. return rc;
  76602. }
  76603. /* Forward declaration */
  76604. static int xferOptimization(
  76605. Parse *pParse, /* Parser context */
  76606. Table *pDest, /* The table we are inserting into */
  76607. Select *pSelect, /* A SELECT statement to use as the data source */
  76608. int onError, /* How to handle constraint errors */
  76609. int iDbDest /* The database of pDest */
  76610. );
  76611. /*
  76612. ** This routine is call to handle SQL of the following forms:
  76613. **
  76614. ** insert into TABLE (IDLIST) values(EXPRLIST)
  76615. ** insert into TABLE (IDLIST) select
  76616. **
  76617. ** The IDLIST following the table name is always optional. If omitted,
  76618. ** then a list of all columns for the table is substituted. The IDLIST
  76619. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  76620. **
  76621. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  76622. ** statement above, and pSelect is NULL. For the second form, pList is
  76623. ** NULL and pSelect is a pointer to the select statement used to generate
  76624. ** data for the insert.
  76625. **
  76626. ** The code generated follows one of four templates. For a simple
  76627. ** select with data coming from a VALUES clause, the code executes
  76628. ** once straight down through. Pseudo-code follows (we call this
  76629. ** the "1st template"):
  76630. **
  76631. ** open write cursor to <table> and its indices
  76632. ** puts VALUES clause expressions onto the stack
  76633. ** write the resulting record into <table>
  76634. ** cleanup
  76635. **
  76636. ** The three remaining templates assume the statement is of the form
  76637. **
  76638. ** INSERT INTO <table> SELECT ...
  76639. **
  76640. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  76641. ** in other words if the SELECT pulls all columns from a single table
  76642. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  76643. ** if <table2> and <table1> are distinct tables but have identical
  76644. ** schemas, including all the same indices, then a special optimization
  76645. ** is invoked that copies raw records from <table2> over to <table1>.
  76646. ** See the xferOptimization() function for the implementation of this
  76647. ** template. This is the 2nd template.
  76648. **
  76649. ** open a write cursor to <table>
  76650. ** open read cursor on <table2>
  76651. ** transfer all records in <table2> over to <table>
  76652. ** close cursors
  76653. ** foreach index on <table>
  76654. ** open a write cursor on the <table> index
  76655. ** open a read cursor on the corresponding <table2> index
  76656. ** transfer all records from the read to the write cursors
  76657. ** close cursors
  76658. ** end foreach
  76659. **
  76660. ** The 3rd template is for when the second template does not apply
  76661. ** and the SELECT clause does not read from <table> at any time.
  76662. ** The generated code follows this template:
  76663. **
  76664. ** EOF <- 0
  76665. ** X <- A
  76666. ** goto B
  76667. ** A: setup for the SELECT
  76668. ** loop over the rows in the SELECT
  76669. ** load values into registers R..R+n
  76670. ** yield X
  76671. ** end loop
  76672. ** cleanup after the SELECT
  76673. ** EOF <- 1
  76674. ** yield X
  76675. ** goto A
  76676. ** B: open write cursor to <table> and its indices
  76677. ** C: yield X
  76678. ** if EOF goto D
  76679. ** insert the select result into <table> from R..R+n
  76680. ** goto C
  76681. ** D: cleanup
  76682. **
  76683. ** The 4th template is used if the insert statement takes its
  76684. ** values from a SELECT but the data is being inserted into a table
  76685. ** that is also read as part of the SELECT. In the third form,
  76686. ** we have to use a intermediate table to store the results of
  76687. ** the select. The template is like this:
  76688. **
  76689. ** EOF <- 0
  76690. ** X <- A
  76691. ** goto B
  76692. ** A: setup for the SELECT
  76693. ** loop over the tables in the SELECT
  76694. ** load value into register R..R+n
  76695. ** yield X
  76696. ** end loop
  76697. ** cleanup after the SELECT
  76698. ** EOF <- 1
  76699. ** yield X
  76700. ** halt-error
  76701. ** B: open temp table
  76702. ** L: yield X
  76703. ** if EOF goto M
  76704. ** insert row from R..R+n into temp table
  76705. ** goto L
  76706. ** M: open write cursor to <table> and its indices
  76707. ** rewind temp table
  76708. ** C: loop over rows of intermediate table
  76709. ** transfer values form intermediate table into <table>
  76710. ** end loop
  76711. ** D: cleanup
  76712. */
  76713. SQLITE_PRIVATE void sqlite3Insert(
  76714. Parse *pParse, /* Parser context */
  76715. SrcList *pTabList, /* Name of table into which we are inserting */
  76716. ExprList *pList, /* List of values to be inserted */
  76717. Select *pSelect, /* A SELECT statement to use as the data source */
  76718. IdList *pColumn, /* Column names corresponding to IDLIST. */
  76719. int onError /* How to handle constraint errors */
  76720. ){
  76721. sqlite3 *db; /* The main database structure */
  76722. Table *pTab; /* The table to insert into. aka TABLE */
  76723. char *zTab; /* Name of the table into which we are inserting */
  76724. const char *zDb; /* Name of the database holding this table */
  76725. int i, j, idx; /* Loop counters */
  76726. Vdbe *v; /* Generate code into this virtual machine */
  76727. Index *pIdx; /* For looping over indices of the table */
  76728. int nColumn; /* Number of columns in the data */
  76729. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  76730. int baseCur = 0; /* VDBE Cursor number for pTab */
  76731. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  76732. int endOfLoop; /* Label for the end of the insertion loop */
  76733. int useTempTable = 0; /* Store SELECT results in intermediate table */
  76734. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  76735. int addrInsTop = 0; /* Jump to label "D" */
  76736. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  76737. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  76738. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  76739. int iDb; /* Index of database holding TABLE */
  76740. Db *pDb; /* The database containing table being inserted into */
  76741. int appendFlag = 0; /* True if the insert is likely to be an append */
  76742. /* Register allocations */
  76743. int regFromSelect = 0;/* Base register for data coming from SELECT */
  76744. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  76745. int regRowCount = 0; /* Memory cell used for the row counter */
  76746. int regIns; /* Block of regs holding rowid+data being inserted */
  76747. int regRowid; /* registers holding insert rowid */
  76748. int regData; /* register holding first column to insert */
  76749. int regEof = 0; /* Register recording end of SELECT data */
  76750. int *aRegIdx = 0; /* One register allocated to each index */
  76751. #ifndef SQLITE_OMIT_TRIGGER
  76752. int isView; /* True if attempting to insert into a view */
  76753. Trigger *pTrigger; /* List of triggers on pTab, if required */
  76754. int tmask; /* Mask of trigger times */
  76755. #endif
  76756. db = pParse->db;
  76757. memset(&dest, 0, sizeof(dest));
  76758. if( pParse->nErr || db->mallocFailed ){
  76759. goto insert_cleanup;
  76760. }
  76761. /* Locate the table into which we will be inserting new information.
  76762. */
  76763. assert( pTabList->nSrc==1 );
  76764. zTab = pTabList->a[0].zName;
  76765. if( NEVER(zTab==0) ) goto insert_cleanup;
  76766. pTab = sqlite3SrcListLookup(pParse, pTabList);
  76767. if( pTab==0 ){
  76768. goto insert_cleanup;
  76769. }
  76770. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  76771. assert( iDb<db->nDb );
  76772. pDb = &db->aDb[iDb];
  76773. zDb = pDb->zName;
  76774. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  76775. goto insert_cleanup;
  76776. }
  76777. /* Figure out if we have any triggers and if the table being
  76778. ** inserted into is a view
  76779. */
  76780. #ifndef SQLITE_OMIT_TRIGGER
  76781. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  76782. isView = pTab->pSelect!=0;
  76783. #else
  76784. # define pTrigger 0
  76785. # define tmask 0
  76786. # define isView 0
  76787. #endif
  76788. #ifdef SQLITE_OMIT_VIEW
  76789. # undef isView
  76790. # define isView 0
  76791. #endif
  76792. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  76793. /* If pTab is really a view, make sure it has been initialized.
  76794. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  76795. ** module table).
  76796. */
  76797. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  76798. goto insert_cleanup;
  76799. }
  76800. /* Ensure that:
  76801. * (a) the table is not read-only,
  76802. * (b) that if it is a view then ON INSERT triggers exist
  76803. */
  76804. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  76805. goto insert_cleanup;
  76806. }
  76807. /* Allocate a VDBE
  76808. */
  76809. v = sqlite3GetVdbe(pParse);
  76810. if( v==0 ) goto insert_cleanup;
  76811. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  76812. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  76813. #ifndef SQLITE_OMIT_XFER_OPT
  76814. /* If the statement is of the form
  76815. **
  76816. ** INSERT INTO <table1> SELECT * FROM <table2>;
  76817. **
  76818. ** Then special optimizations can be applied that make the transfer
  76819. ** very fast and which reduce fragmentation of indices.
  76820. **
  76821. ** This is the 2nd template.
  76822. */
  76823. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  76824. assert( !pTrigger );
  76825. assert( pList==0 );
  76826. goto insert_end;
  76827. }
  76828. #endif /* SQLITE_OMIT_XFER_OPT */
  76829. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  76830. ** sqlite_sequence table and store it in memory cell regAutoinc.
  76831. */
  76832. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  76833. /* Figure out how many columns of data are supplied. If the data
  76834. ** is coming from a SELECT statement, then generate a co-routine that
  76835. ** produces a single row of the SELECT on each invocation. The
  76836. ** co-routine is the common header to the 3rd and 4th templates.
  76837. */
  76838. if( pSelect ){
  76839. /* Data is coming from a SELECT. Generate a co-routine to run that
  76840. ** SELECT. */
  76841. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  76842. if( rc ) goto insert_cleanup;
  76843. regEof = dest.iSDParm + 1;
  76844. regFromSelect = dest.iSdst;
  76845. assert( pSelect->pEList );
  76846. nColumn = pSelect->pEList->nExpr;
  76847. assert( dest.nSdst==nColumn );
  76848. /* Set useTempTable to TRUE if the result of the SELECT statement
  76849. ** should be written into a temporary table (template 4). Set to
  76850. ** FALSE if each* row of the SELECT can be written directly into
  76851. ** the destination table (template 3).
  76852. **
  76853. ** A temp table must be used if the table being updated is also one
  76854. ** of the tables being read by the SELECT statement. Also use a
  76855. ** temp table in the case of row triggers.
  76856. */
  76857. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  76858. useTempTable = 1;
  76859. }
  76860. if( useTempTable ){
  76861. /* Invoke the coroutine to extract information from the SELECT
  76862. ** and add it to a transient table srcTab. The code generated
  76863. ** here is from the 4th template:
  76864. **
  76865. ** B: open temp table
  76866. ** L: yield X
  76867. ** if EOF goto M
  76868. ** insert row from R..R+n into temp table
  76869. ** goto L
  76870. ** M: ...
  76871. */
  76872. int regRec; /* Register to hold packed record */
  76873. int regTempRowid; /* Register to hold temp table ROWID */
  76874. int addrTop; /* Label "L" */
  76875. int addrIf; /* Address of jump to M */
  76876. srcTab = pParse->nTab++;
  76877. regRec = sqlite3GetTempReg(pParse);
  76878. regTempRowid = sqlite3GetTempReg(pParse);
  76879. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  76880. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  76881. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  76882. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  76883. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  76884. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  76885. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  76886. sqlite3VdbeJumpHere(v, addrIf);
  76887. sqlite3ReleaseTempReg(pParse, regRec);
  76888. sqlite3ReleaseTempReg(pParse, regTempRowid);
  76889. }
  76890. }else{
  76891. /* This is the case if the data for the INSERT is coming from a VALUES
  76892. ** clause
  76893. */
  76894. NameContext sNC;
  76895. memset(&sNC, 0, sizeof(sNC));
  76896. sNC.pParse = pParse;
  76897. srcTab = -1;
  76898. assert( useTempTable==0 );
  76899. nColumn = pList ? pList->nExpr : 0;
  76900. for(i=0; i<nColumn; i++){
  76901. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  76902. goto insert_cleanup;
  76903. }
  76904. }
  76905. }
  76906. /* Make sure the number of columns in the source data matches the number
  76907. ** of columns to be inserted into the table.
  76908. */
  76909. if( IsVirtual(pTab) ){
  76910. for(i=0; i<pTab->nCol; i++){
  76911. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  76912. }
  76913. }
  76914. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  76915. sqlite3ErrorMsg(pParse,
  76916. "table %S has %d columns but %d values were supplied",
  76917. pTabList, 0, pTab->nCol-nHidden, nColumn);
  76918. goto insert_cleanup;
  76919. }
  76920. if( pColumn!=0 && nColumn!=pColumn->nId ){
  76921. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  76922. goto insert_cleanup;
  76923. }
  76924. /* If the INSERT statement included an IDLIST term, then make sure
  76925. ** all elements of the IDLIST really are columns of the table and
  76926. ** remember the column indices.
  76927. **
  76928. ** If the table has an INTEGER PRIMARY KEY column and that column
  76929. ** is named in the IDLIST, then record in the keyColumn variable
  76930. ** the index into IDLIST of the primary key column. keyColumn is
  76931. ** the index of the primary key as it appears in IDLIST, not as
  76932. ** is appears in the original table. (The index of the primary
  76933. ** key in the original table is pTab->iPKey.)
  76934. */
  76935. if( pColumn ){
  76936. for(i=0; i<pColumn->nId; i++){
  76937. pColumn->a[i].idx = -1;
  76938. }
  76939. for(i=0; i<pColumn->nId; i++){
  76940. for(j=0; j<pTab->nCol; j++){
  76941. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  76942. pColumn->a[i].idx = j;
  76943. if( j==pTab->iPKey ){
  76944. keyColumn = i;
  76945. }
  76946. break;
  76947. }
  76948. }
  76949. if( j>=pTab->nCol ){
  76950. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  76951. keyColumn = i;
  76952. }else{
  76953. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  76954. pTabList, 0, pColumn->a[i].zName);
  76955. pParse->checkSchema = 1;
  76956. goto insert_cleanup;
  76957. }
  76958. }
  76959. }
  76960. }
  76961. /* If there is no IDLIST term but the table has an integer primary
  76962. ** key, the set the keyColumn variable to the primary key column index
  76963. ** in the original table definition.
  76964. */
  76965. if( pColumn==0 && nColumn>0 ){
  76966. keyColumn = pTab->iPKey;
  76967. }
  76968. /* Initialize the count of rows to be inserted
  76969. */
  76970. if( db->flags & SQLITE_CountRows ){
  76971. regRowCount = ++pParse->nMem;
  76972. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  76973. }
  76974. /* If this is not a view, open the table and and all indices */
  76975. if( !isView ){
  76976. int nIdx;
  76977. baseCur = pParse->nTab;
  76978. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  76979. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  76980. if( aRegIdx==0 ){
  76981. goto insert_cleanup;
  76982. }
  76983. for(i=0; i<nIdx; i++){
  76984. aRegIdx[i] = ++pParse->nMem;
  76985. }
  76986. }
  76987. /* This is the top of the main insertion loop */
  76988. if( useTempTable ){
  76989. /* This block codes the top of loop only. The complete loop is the
  76990. ** following pseudocode (template 4):
  76991. **
  76992. ** rewind temp table
  76993. ** C: loop over rows of intermediate table
  76994. ** transfer values form intermediate table into <table>
  76995. ** end loop
  76996. ** D: ...
  76997. */
  76998. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  76999. addrCont = sqlite3VdbeCurrentAddr(v);
  77000. }else if( pSelect ){
  77001. /* This block codes the top of loop only. The complete loop is the
  77002. ** following pseudocode (template 3):
  77003. **
  77004. ** C: yield X
  77005. ** if EOF goto D
  77006. ** insert the select result into <table> from R..R+n
  77007. ** goto C
  77008. ** D: ...
  77009. */
  77010. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  77011. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  77012. }
  77013. /* Allocate registers for holding the rowid of the new row,
  77014. ** the content of the new row, and the assemblied row record.
  77015. */
  77016. regRowid = regIns = pParse->nMem+1;
  77017. pParse->nMem += pTab->nCol + 1;
  77018. if( IsVirtual(pTab) ){
  77019. regRowid++;
  77020. pParse->nMem++;
  77021. }
  77022. regData = regRowid+1;
  77023. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  77024. */
  77025. endOfLoop = sqlite3VdbeMakeLabel(v);
  77026. if( tmask & TRIGGER_BEFORE ){
  77027. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  77028. /* build the NEW.* reference row. Note that if there is an INTEGER
  77029. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  77030. ** translated into a unique ID for the row. But on a BEFORE trigger,
  77031. ** we do not know what the unique ID will be (because the insert has
  77032. ** not happened yet) so we substitute a rowid of -1
  77033. */
  77034. if( keyColumn<0 ){
  77035. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  77036. }else{
  77037. int j1;
  77038. if( useTempTable ){
  77039. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  77040. }else{
  77041. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  77042. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  77043. }
  77044. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  77045. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  77046. sqlite3VdbeJumpHere(v, j1);
  77047. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  77048. }
  77049. /* Cannot have triggers on a virtual table. If it were possible,
  77050. ** this block would have to account for hidden column.
  77051. */
  77052. assert( !IsVirtual(pTab) );
  77053. /* Create the new column data
  77054. */
  77055. for(i=0; i<pTab->nCol; i++){
  77056. if( pColumn==0 ){
  77057. j = i;
  77058. }else{
  77059. for(j=0; j<pColumn->nId; j++){
  77060. if( pColumn->a[j].idx==i ) break;
  77061. }
  77062. }
  77063. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  77064. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  77065. }else if( useTempTable ){
  77066. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  77067. }else{
  77068. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  77069. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  77070. }
  77071. }
  77072. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  77073. ** do not attempt any conversions before assembling the record.
  77074. ** If this is a real table, attempt conversions as required by the
  77075. ** table column affinities.
  77076. */
  77077. if( !isView ){
  77078. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  77079. sqlite3TableAffinityStr(v, pTab);
  77080. }
  77081. /* Fire BEFORE or INSTEAD OF triggers */
  77082. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  77083. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  77084. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  77085. }
  77086. /* Push the record number for the new entry onto the stack. The
  77087. ** record number is a randomly generate integer created by NewRowid
  77088. ** except when the table has an INTEGER PRIMARY KEY column, in which
  77089. ** case the record number is the same as that column.
  77090. */
  77091. if( !isView ){
  77092. if( IsVirtual(pTab) ){
  77093. /* The row that the VUpdate opcode will delete: none */
  77094. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  77095. }
  77096. if( keyColumn>=0 ){
  77097. if( useTempTable ){
  77098. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  77099. }else if( pSelect ){
  77100. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  77101. }else{
  77102. VdbeOp *pOp;
  77103. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  77104. pOp = sqlite3VdbeGetOp(v, -1);
  77105. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  77106. appendFlag = 1;
  77107. pOp->opcode = OP_NewRowid;
  77108. pOp->p1 = baseCur;
  77109. pOp->p2 = regRowid;
  77110. pOp->p3 = regAutoinc;
  77111. }
  77112. }
  77113. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  77114. ** to generate a unique primary key value.
  77115. */
  77116. if( !appendFlag ){
  77117. int j1;
  77118. if( !IsVirtual(pTab) ){
  77119. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  77120. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  77121. sqlite3VdbeJumpHere(v, j1);
  77122. }else{
  77123. j1 = sqlite3VdbeCurrentAddr(v);
  77124. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  77125. }
  77126. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  77127. }
  77128. }else if( IsVirtual(pTab) ){
  77129. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  77130. }else{
  77131. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  77132. appendFlag = 1;
  77133. }
  77134. autoIncStep(pParse, regAutoinc, regRowid);
  77135. /* Push onto the stack, data for all columns of the new entry, beginning
  77136. ** with the first column.
  77137. */
  77138. nHidden = 0;
  77139. for(i=0; i<pTab->nCol; i++){
  77140. int iRegStore = regRowid+1+i;
  77141. if( i==pTab->iPKey ){
  77142. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  77143. ** Whenever this column is read, the record number will be substituted
  77144. ** in its place. So will fill this column with a NULL to avoid
  77145. ** taking up data space with information that will never be used. */
  77146. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  77147. continue;
  77148. }
  77149. if( pColumn==0 ){
  77150. if( IsHiddenColumn(&pTab->aCol[i]) ){
  77151. assert( IsVirtual(pTab) );
  77152. j = -1;
  77153. nHidden++;
  77154. }else{
  77155. j = i - nHidden;
  77156. }
  77157. }else{
  77158. for(j=0; j<pColumn->nId; j++){
  77159. if( pColumn->a[j].idx==i ) break;
  77160. }
  77161. }
  77162. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  77163. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  77164. }else if( useTempTable ){
  77165. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  77166. }else if( pSelect ){
  77167. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  77168. }else{
  77169. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  77170. }
  77171. }
  77172. /* Generate code to check constraints and generate index keys and
  77173. ** do the insertion.
  77174. */
  77175. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77176. if( IsVirtual(pTab) ){
  77177. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  77178. sqlite3VtabMakeWritable(pParse, pTab);
  77179. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  77180. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  77181. sqlite3MayAbort(pParse);
  77182. }else
  77183. #endif
  77184. {
  77185. int isReplace; /* Set to true if constraints may cause a replace */
  77186. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  77187. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  77188. );
  77189. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  77190. sqlite3CompleteInsertion(
  77191. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  77192. );
  77193. }
  77194. }
  77195. /* Update the count of rows that are inserted
  77196. */
  77197. if( (db->flags & SQLITE_CountRows)!=0 ){
  77198. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  77199. }
  77200. if( pTrigger ){
  77201. /* Code AFTER triggers */
  77202. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  77203. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  77204. }
  77205. /* The bottom of the main insertion loop, if the data source
  77206. ** is a SELECT statement.
  77207. */
  77208. sqlite3VdbeResolveLabel(v, endOfLoop);
  77209. if( useTempTable ){
  77210. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  77211. sqlite3VdbeJumpHere(v, addrInsTop);
  77212. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  77213. }else if( pSelect ){
  77214. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  77215. sqlite3VdbeJumpHere(v, addrInsTop);
  77216. }
  77217. if( !IsVirtual(pTab) && !isView ){
  77218. /* Close all tables opened */
  77219. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  77220. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  77221. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  77222. }
  77223. }
  77224. insert_end:
  77225. /* Update the sqlite_sequence table by storing the content of the
  77226. ** maximum rowid counter values recorded while inserting into
  77227. ** autoincrement tables.
  77228. */
  77229. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  77230. sqlite3AutoincrementEnd(pParse);
  77231. }
  77232. /*
  77233. ** Return the number of rows inserted. If this routine is
  77234. ** generating code because of a call to sqlite3NestedParse(), do not
  77235. ** invoke the callback function.
  77236. */
  77237. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  77238. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  77239. sqlite3VdbeSetNumCols(v, 1);
  77240. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  77241. }
  77242. insert_cleanup:
  77243. sqlite3SrcListDelete(db, pTabList);
  77244. sqlite3ExprListDelete(db, pList);
  77245. sqlite3SelectDelete(db, pSelect);
  77246. sqlite3IdListDelete(db, pColumn);
  77247. sqlite3DbFree(db, aRegIdx);
  77248. }
  77249. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  77250. ** thely may interfere with compilation of other functions in this file
  77251. ** (or in another file, if this file becomes part of the amalgamation). */
  77252. #ifdef isView
  77253. #undef isView
  77254. #endif
  77255. #ifdef pTrigger
  77256. #undef pTrigger
  77257. #endif
  77258. #ifdef tmask
  77259. #undef tmask
  77260. #endif
  77261. /*
  77262. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  77263. **
  77264. ** The input is a range of consecutive registers as follows:
  77265. **
  77266. ** 1. The rowid of the row after the update.
  77267. **
  77268. ** 2. The data in the first column of the entry after the update.
  77269. **
  77270. ** i. Data from middle columns...
  77271. **
  77272. ** N. The data in the last column of the entry after the update.
  77273. **
  77274. ** The regRowid parameter is the index of the register containing (1).
  77275. **
  77276. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  77277. ** the address of a register containing the rowid before the update takes
  77278. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  77279. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  77280. ** indicates that the rowid was explicitly specified as part of the
  77281. ** INSERT statement. If rowidChng is false, it means that the rowid is
  77282. ** computed automatically in an insert or that the rowid value is not
  77283. ** modified by an update.
  77284. **
  77285. ** The code generated by this routine store new index entries into
  77286. ** registers identified by aRegIdx[]. No index entry is created for
  77287. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  77288. ** the same as the order of indices on the linked list of indices
  77289. ** attached to the table.
  77290. **
  77291. ** This routine also generates code to check constraints. NOT NULL,
  77292. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  77293. ** then the appropriate action is performed. There are five possible
  77294. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  77295. **
  77296. ** Constraint type Action What Happens
  77297. ** --------------- ---------- ----------------------------------------
  77298. ** any ROLLBACK The current transaction is rolled back and
  77299. ** sqlite3_exec() returns immediately with a
  77300. ** return code of SQLITE_CONSTRAINT.
  77301. **
  77302. ** any ABORT Back out changes from the current command
  77303. ** only (do not do a complete rollback) then
  77304. ** cause sqlite3_exec() to return immediately
  77305. ** with SQLITE_CONSTRAINT.
  77306. **
  77307. ** any FAIL Sqlite3_exec() returns immediately with a
  77308. ** return code of SQLITE_CONSTRAINT. The
  77309. ** transaction is not rolled back and any
  77310. ** prior changes are retained.
  77311. **
  77312. ** any IGNORE The record number and data is popped from
  77313. ** the stack and there is an immediate jump
  77314. ** to label ignoreDest.
  77315. **
  77316. ** NOT NULL REPLACE The NULL value is replace by the default
  77317. ** value for that column. If the default value
  77318. ** is NULL, the action is the same as ABORT.
  77319. **
  77320. ** UNIQUE REPLACE The other row that conflicts with the row
  77321. ** being inserted is removed.
  77322. **
  77323. ** CHECK REPLACE Illegal. The results in an exception.
  77324. **
  77325. ** Which action to take is determined by the overrideError parameter.
  77326. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  77327. ** is used. Or if pParse->onError==OE_Default then the onError value
  77328. ** for the constraint is used.
  77329. **
  77330. ** The calling routine must open a read/write cursor for pTab with
  77331. ** cursor number "baseCur". All indices of pTab must also have open
  77332. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  77333. ** Except, if there is no possibility of a REPLACE action then
  77334. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  77335. */
  77336. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  77337. Parse *pParse, /* The parser context */
  77338. Table *pTab, /* the table into which we are inserting */
  77339. int baseCur, /* Index of a read/write cursor pointing at pTab */
  77340. int regRowid, /* Index of the range of input registers */
  77341. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  77342. int rowidChng, /* True if the rowid might collide with existing entry */
  77343. int isUpdate, /* True for UPDATE, False for INSERT */
  77344. int overrideError, /* Override onError to this if not OE_Default */
  77345. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  77346. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  77347. ){
  77348. int i; /* loop counter */
  77349. Vdbe *v; /* VDBE under constrution */
  77350. int nCol; /* Number of columns */
  77351. int onError; /* Conflict resolution strategy */
  77352. int j1; /* Addresss of jump instruction */
  77353. int j2 = 0, j3; /* Addresses of jump instructions */
  77354. int regData; /* Register containing first data column */
  77355. int iCur; /* Table cursor number */
  77356. Index *pIdx; /* Pointer to one of the indices */
  77357. sqlite3 *db; /* Database connection */
  77358. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  77359. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  77360. db = pParse->db;
  77361. v = sqlite3GetVdbe(pParse);
  77362. assert( v!=0 );
  77363. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  77364. nCol = pTab->nCol;
  77365. regData = regRowid + 1;
  77366. /* Test all NOT NULL constraints.
  77367. */
  77368. for(i=0; i<nCol; i++){
  77369. if( i==pTab->iPKey ){
  77370. continue;
  77371. }
  77372. onError = pTab->aCol[i].notNull;
  77373. if( onError==OE_None ) continue;
  77374. if( overrideError!=OE_Default ){
  77375. onError = overrideError;
  77376. }else if( onError==OE_Default ){
  77377. onError = OE_Abort;
  77378. }
  77379. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  77380. onError = OE_Abort;
  77381. }
  77382. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  77383. || onError==OE_Ignore || onError==OE_Replace );
  77384. switch( onError ){
  77385. case OE_Abort:
  77386. sqlite3MayAbort(pParse);
  77387. case OE_Rollback:
  77388. case OE_Fail: {
  77389. char *zMsg;
  77390. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  77391. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  77392. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  77393. pTab->zName, pTab->aCol[i].zName);
  77394. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  77395. break;
  77396. }
  77397. case OE_Ignore: {
  77398. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  77399. break;
  77400. }
  77401. default: {
  77402. assert( onError==OE_Replace );
  77403. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  77404. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  77405. sqlite3VdbeJumpHere(v, j1);
  77406. break;
  77407. }
  77408. }
  77409. }
  77410. /* Test all CHECK constraints
  77411. */
  77412. #ifndef SQLITE_OMIT_CHECK
  77413. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  77414. ExprList *pCheck = pTab->pCheck;
  77415. pParse->ckBase = regData;
  77416. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  77417. for(i=0; i<pCheck->nExpr; i++){
  77418. int allOk = sqlite3VdbeMakeLabel(v);
  77419. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  77420. if( onError==OE_Ignore ){
  77421. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77422. }else{
  77423. char *zConsName = pCheck->a[i].zName;
  77424. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  77425. if( zConsName ){
  77426. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  77427. }else{
  77428. zConsName = 0;
  77429. }
  77430. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  77431. onError, zConsName, P4_DYNAMIC);
  77432. }
  77433. sqlite3VdbeResolveLabel(v, allOk);
  77434. }
  77435. }
  77436. #endif /* !defined(SQLITE_OMIT_CHECK) */
  77437. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  77438. ** of the new record does not previously exist. Except, if this
  77439. ** is an UPDATE and the primary key is not changing, that is OK.
  77440. */
  77441. if( rowidChng ){
  77442. onError = pTab->keyConf;
  77443. if( overrideError!=OE_Default ){
  77444. onError = overrideError;
  77445. }else if( onError==OE_Default ){
  77446. onError = OE_Abort;
  77447. }
  77448. if( isUpdate ){
  77449. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  77450. }
  77451. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  77452. switch( onError ){
  77453. default: {
  77454. onError = OE_Abort;
  77455. /* Fall thru into the next case */
  77456. }
  77457. case OE_Rollback:
  77458. case OE_Abort:
  77459. case OE_Fail: {
  77460. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  77461. onError, "PRIMARY KEY must be unique", P4_STATIC);
  77462. break;
  77463. }
  77464. case OE_Replace: {
  77465. /* If there are DELETE triggers on this table and the
  77466. ** recursive-triggers flag is set, call GenerateRowDelete() to
  77467. ** remove the conflicting row from the table. This will fire
  77468. ** the triggers and remove both the table and index b-tree entries.
  77469. **
  77470. ** Otherwise, if there are no triggers or the recursive-triggers
  77471. ** flag is not set, but the table has one or more indexes, call
  77472. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  77473. ** only. The table b-tree entry will be replaced by the new entry
  77474. ** when it is inserted.
  77475. **
  77476. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  77477. ** also invoke MultiWrite() to indicate that this VDBE may require
  77478. ** statement rollback (if the statement is aborted after the delete
  77479. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  77480. ** but being more selective here allows statements like:
  77481. **
  77482. ** REPLACE INTO t(rowid) VALUES($newrowid)
  77483. **
  77484. ** to run without a statement journal if there are no indexes on the
  77485. ** table.
  77486. */
  77487. Trigger *pTrigger = 0;
  77488. if( db->flags&SQLITE_RecTriggers ){
  77489. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  77490. }
  77491. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  77492. sqlite3MultiWrite(pParse);
  77493. sqlite3GenerateRowDelete(
  77494. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  77495. );
  77496. }else if( pTab->pIndex ){
  77497. sqlite3MultiWrite(pParse);
  77498. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  77499. }
  77500. seenReplace = 1;
  77501. break;
  77502. }
  77503. case OE_Ignore: {
  77504. assert( seenReplace==0 );
  77505. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77506. break;
  77507. }
  77508. }
  77509. sqlite3VdbeJumpHere(v, j3);
  77510. if( isUpdate ){
  77511. sqlite3VdbeJumpHere(v, j2);
  77512. }
  77513. }
  77514. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  77515. ** index and making sure that duplicate entries do not already exist.
  77516. ** Add the new records to the indices as we go.
  77517. */
  77518. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  77519. int regIdx;
  77520. int regR;
  77521. int addrSkipRow = 0;
  77522. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  77523. if( pIdx->pPartIdxWhere ){
  77524. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
  77525. addrSkipRow = sqlite3VdbeMakeLabel(v);
  77526. pParse->ckBase = regData;
  77527. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
  77528. SQLITE_JUMPIFNULL);
  77529. pParse->ckBase = 0;
  77530. }
  77531. /* Create a key for accessing the index entry */
  77532. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  77533. for(i=0; i<pIdx->nColumn; i++){
  77534. int idx = pIdx->aiColumn[i];
  77535. if( idx==pTab->iPKey ){
  77536. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  77537. }else{
  77538. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  77539. }
  77540. }
  77541. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  77542. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  77543. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  77544. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  77545. /* Find out what action to take in case there is an indexing conflict */
  77546. onError = pIdx->onError;
  77547. if( onError==OE_None ){
  77548. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  77549. sqlite3VdbeResolveLabel(v, addrSkipRow);
  77550. continue; /* pIdx is not a UNIQUE index */
  77551. }
  77552. if( overrideError!=OE_Default ){
  77553. onError = overrideError;
  77554. }else if( onError==OE_Default ){
  77555. onError = OE_Abort;
  77556. }
  77557. if( seenReplace ){
  77558. if( onError==OE_Ignore ) onError = OE_Replace;
  77559. else if( onError==OE_Fail ) onError = OE_Abort;
  77560. }
  77561. /* Check to see if the new index entry will be unique */
  77562. regR = sqlite3GetTempReg(pParse);
  77563. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  77564. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  77565. regR, SQLITE_INT_TO_PTR(regIdx),
  77566. P4_INT32);
  77567. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  77568. /* Generate code that executes if the new index entry is not unique */
  77569. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  77570. || onError==OE_Ignore || onError==OE_Replace );
  77571. switch( onError ){
  77572. case OE_Rollback:
  77573. case OE_Abort:
  77574. case OE_Fail: {
  77575. int j;
  77576. StrAccum errMsg;
  77577. const char *zSep;
  77578. char *zErr;
  77579. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  77580. errMsg.db = db;
  77581. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  77582. for(j=0; j<pIdx->nColumn; j++){
  77583. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  77584. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  77585. zSep = ", ";
  77586. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  77587. }
  77588. sqlite3StrAccumAppend(&errMsg,
  77589. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  77590. zErr = sqlite3StrAccumFinish(&errMsg);
  77591. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  77592. onError, zErr, 0);
  77593. sqlite3DbFree(errMsg.db, zErr);
  77594. break;
  77595. }
  77596. case OE_Ignore: {
  77597. assert( seenReplace==0 );
  77598. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77599. break;
  77600. }
  77601. default: {
  77602. Trigger *pTrigger = 0;
  77603. assert( onError==OE_Replace );
  77604. sqlite3MultiWrite(pParse);
  77605. if( db->flags&SQLITE_RecTriggers ){
  77606. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  77607. }
  77608. sqlite3GenerateRowDelete(
  77609. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  77610. );
  77611. seenReplace = 1;
  77612. break;
  77613. }
  77614. }
  77615. sqlite3VdbeJumpHere(v, j3);
  77616. sqlite3VdbeResolveLabel(v, addrSkipRow);
  77617. sqlite3ReleaseTempReg(pParse, regR);
  77618. }
  77619. if( pbMayReplace ){
  77620. *pbMayReplace = seenReplace;
  77621. }
  77622. }
  77623. /*
  77624. ** This routine generates code to finish the INSERT or UPDATE operation
  77625. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  77626. ** A consecutive range of registers starting at regRowid contains the
  77627. ** rowid and the content to be inserted.
  77628. **
  77629. ** The arguments to this routine should be the same as the first six
  77630. ** arguments to sqlite3GenerateConstraintChecks.
  77631. */
  77632. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  77633. Parse *pParse, /* The parser context */
  77634. Table *pTab, /* the table into which we are inserting */
  77635. int baseCur, /* Index of a read/write cursor pointing at pTab */
  77636. int regRowid, /* Range of content */
  77637. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  77638. int isUpdate, /* True for UPDATE, False for INSERT */
  77639. int appendBias, /* True if this is likely to be an append */
  77640. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  77641. ){
  77642. int i;
  77643. Vdbe *v;
  77644. Index *pIdx;
  77645. u8 pik_flags;
  77646. int regData;
  77647. int regRec;
  77648. v = sqlite3GetVdbe(pParse);
  77649. assert( v!=0 );
  77650. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  77651. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  77652. if( aRegIdx[i]==0 ) continue;
  77653. if( pIdx->pPartIdxWhere ){
  77654. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  77655. }
  77656. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  77657. if( useSeekResult ){
  77658. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  77659. }
  77660. }
  77661. regData = regRowid + 1;
  77662. regRec = sqlite3GetTempReg(pParse);
  77663. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  77664. sqlite3TableAffinityStr(v, pTab);
  77665. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  77666. if( pParse->nested ){
  77667. pik_flags = 0;
  77668. }else{
  77669. pik_flags = OPFLAG_NCHANGE;
  77670. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  77671. }
  77672. if( appendBias ){
  77673. pik_flags |= OPFLAG_APPEND;
  77674. }
  77675. if( useSeekResult ){
  77676. pik_flags |= OPFLAG_USESEEKRESULT;
  77677. }
  77678. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  77679. if( !pParse->nested ){
  77680. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  77681. }
  77682. sqlite3VdbeChangeP5(v, pik_flags);
  77683. }
  77684. /*
  77685. ** Generate code that will open cursors for a table and for all
  77686. ** indices of that table. The "baseCur" parameter is the cursor number used
  77687. ** for the table. Indices are opened on subsequent cursors.
  77688. **
  77689. ** Return the number of indices on the table.
  77690. */
  77691. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  77692. Parse *pParse, /* Parsing context */
  77693. Table *pTab, /* Table to be opened */
  77694. int baseCur, /* Cursor number assigned to the table */
  77695. int op /* OP_OpenRead or OP_OpenWrite */
  77696. ){
  77697. int i;
  77698. int iDb;
  77699. Index *pIdx;
  77700. Vdbe *v;
  77701. if( IsVirtual(pTab) ) return 0;
  77702. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  77703. v = sqlite3GetVdbe(pParse);
  77704. assert( v!=0 );
  77705. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  77706. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  77707. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  77708. assert( pIdx->pSchema==pTab->pSchema );
  77709. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  77710. (char*)pKey, P4_KEYINFO_HANDOFF);
  77711. VdbeComment((v, "%s", pIdx->zName));
  77712. }
  77713. if( pParse->nTab<baseCur+i ){
  77714. pParse->nTab = baseCur+i;
  77715. }
  77716. return i-1;
  77717. }
  77718. #ifdef SQLITE_TEST
  77719. /*
  77720. ** The following global variable is incremented whenever the
  77721. ** transfer optimization is used. This is used for testing
  77722. ** purposes only - to make sure the transfer optimization really
  77723. ** is happening when it is suppose to.
  77724. */
  77725. SQLITE_API int sqlite3_xferopt_count;
  77726. #endif /* SQLITE_TEST */
  77727. #ifndef SQLITE_OMIT_XFER_OPT
  77728. /*
  77729. ** Check to collation names to see if they are compatible.
  77730. */
  77731. static int xferCompatibleCollation(const char *z1, const char *z2){
  77732. if( z1==0 ){
  77733. return z2==0;
  77734. }
  77735. if( z2==0 ){
  77736. return 0;
  77737. }
  77738. return sqlite3StrICmp(z1, z2)==0;
  77739. }
  77740. /*
  77741. ** Check to see if index pSrc is compatible as a source of data
  77742. ** for index pDest in an insert transfer optimization. The rules
  77743. ** for a compatible index:
  77744. **
  77745. ** * The index is over the same set of columns
  77746. ** * The same DESC and ASC markings occurs on all columns
  77747. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  77748. ** * The same collating sequence on each column
  77749. ** * The index has the exact same WHERE clause
  77750. */
  77751. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  77752. int i;
  77753. assert( pDest && pSrc );
  77754. assert( pDest->pTable!=pSrc->pTable );
  77755. if( pDest->nColumn!=pSrc->nColumn ){
  77756. return 0; /* Different number of columns */
  77757. }
  77758. if( pDest->onError!=pSrc->onError ){
  77759. return 0; /* Different conflict resolution strategies */
  77760. }
  77761. for(i=0; i<pSrc->nColumn; i++){
  77762. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  77763. return 0; /* Different columns indexed */
  77764. }
  77765. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  77766. return 0; /* Different sort orders */
  77767. }
  77768. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  77769. return 0; /* Different collating sequences */
  77770. }
  77771. }
  77772. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  77773. return 0; /* Different WHERE clauses */
  77774. }
  77775. /* If no test above fails then the indices must be compatible */
  77776. return 1;
  77777. }
  77778. /*
  77779. ** Attempt the transfer optimization on INSERTs of the form
  77780. **
  77781. ** INSERT INTO tab1 SELECT * FROM tab2;
  77782. **
  77783. ** The xfer optimization transfers raw records from tab2 over to tab1.
  77784. ** Columns are not decoded and reassemblied, which greatly improves
  77785. ** performance. Raw index records are transferred in the same way.
  77786. **
  77787. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  77788. ** There are lots of rules for determining compatibility - see comments
  77789. ** embedded in the code for details.
  77790. **
  77791. ** This routine returns TRUE if the optimization is guaranteed to be used.
  77792. ** Sometimes the xfer optimization will only work if the destination table
  77793. ** is empty - a factor that can only be determined at run-time. In that
  77794. ** case, this routine generates code for the xfer optimization but also
  77795. ** does a test to see if the destination table is empty and jumps over the
  77796. ** xfer optimization code if the test fails. In that case, this routine
  77797. ** returns FALSE so that the caller will know to go ahead and generate
  77798. ** an unoptimized transfer. This routine also returns FALSE if there
  77799. ** is no chance that the xfer optimization can be applied.
  77800. **
  77801. ** This optimization is particularly useful at making VACUUM run faster.
  77802. */
  77803. static int xferOptimization(
  77804. Parse *pParse, /* Parser context */
  77805. Table *pDest, /* The table we are inserting into */
  77806. Select *pSelect, /* A SELECT statement to use as the data source */
  77807. int onError, /* How to handle constraint errors */
  77808. int iDbDest /* The database of pDest */
  77809. ){
  77810. ExprList *pEList; /* The result set of the SELECT */
  77811. Table *pSrc; /* The table in the FROM clause of SELECT */
  77812. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  77813. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  77814. int i; /* Loop counter */
  77815. int iDbSrc; /* The database of pSrc */
  77816. int iSrc, iDest; /* Cursors from source and destination */
  77817. int addr1, addr2; /* Loop addresses */
  77818. int emptyDestTest; /* Address of test for empty pDest */
  77819. int emptySrcTest; /* Address of test for empty pSrc */
  77820. Vdbe *v; /* The VDBE we are building */
  77821. KeyInfo *pKey; /* Key information for an index */
  77822. int regAutoinc; /* Memory register used by AUTOINC */
  77823. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  77824. int regData, regRowid; /* Registers holding data and rowid */
  77825. if( pSelect==0 ){
  77826. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  77827. }
  77828. if( sqlite3TriggerList(pParse, pDest) ){
  77829. return 0; /* tab1 must not have triggers */
  77830. }
  77831. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77832. if( pDest->tabFlags & TF_Virtual ){
  77833. return 0; /* tab1 must not be a virtual table */
  77834. }
  77835. #endif
  77836. if( onError==OE_Default ){
  77837. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  77838. if( onError==OE_Default ) onError = OE_Abort;
  77839. }
  77840. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  77841. if( pSelect->pSrc->nSrc!=1 ){
  77842. return 0; /* FROM clause must have exactly one term */
  77843. }
  77844. if( pSelect->pSrc->a[0].pSelect ){
  77845. return 0; /* FROM clause cannot contain a subquery */
  77846. }
  77847. if( pSelect->pWhere ){
  77848. return 0; /* SELECT may not have a WHERE clause */
  77849. }
  77850. if( pSelect->pOrderBy ){
  77851. return 0; /* SELECT may not have an ORDER BY clause */
  77852. }
  77853. /* Do not need to test for a HAVING clause. If HAVING is present but
  77854. ** there is no ORDER BY, we will get an error. */
  77855. if( pSelect->pGroupBy ){
  77856. return 0; /* SELECT may not have a GROUP BY clause */
  77857. }
  77858. if( pSelect->pLimit ){
  77859. return 0; /* SELECT may not have a LIMIT clause */
  77860. }
  77861. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  77862. if( pSelect->pPrior ){
  77863. return 0; /* SELECT may not be a compound query */
  77864. }
  77865. if( pSelect->selFlags & SF_Distinct ){
  77866. return 0; /* SELECT may not be DISTINCT */
  77867. }
  77868. pEList = pSelect->pEList;
  77869. assert( pEList!=0 );
  77870. if( pEList->nExpr!=1 ){
  77871. return 0; /* The result set must have exactly one column */
  77872. }
  77873. assert( pEList->a[0].pExpr );
  77874. if( pEList->a[0].pExpr->op!=TK_ALL ){
  77875. return 0; /* The result set must be the special operator "*" */
  77876. }
  77877. /* At this point we have established that the statement is of the
  77878. ** correct syntactic form to participate in this optimization. Now
  77879. ** we have to check the semantics.
  77880. */
  77881. pItem = pSelect->pSrc->a;
  77882. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  77883. if( pSrc==0 ){
  77884. return 0; /* FROM clause does not contain a real table */
  77885. }
  77886. if( pSrc==pDest ){
  77887. return 0; /* tab1 and tab2 may not be the same table */
  77888. }
  77889. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77890. if( pSrc->tabFlags & TF_Virtual ){
  77891. return 0; /* tab2 must not be a virtual table */
  77892. }
  77893. #endif
  77894. if( pSrc->pSelect ){
  77895. return 0; /* tab2 may not be a view */
  77896. }
  77897. if( pDest->nCol!=pSrc->nCol ){
  77898. return 0; /* Number of columns must be the same in tab1 and tab2 */
  77899. }
  77900. if( pDest->iPKey!=pSrc->iPKey ){
  77901. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  77902. }
  77903. for(i=0; i<pDest->nCol; i++){
  77904. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  77905. return 0; /* Affinity must be the same on all columns */
  77906. }
  77907. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  77908. return 0; /* Collating sequence must be the same on all columns */
  77909. }
  77910. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  77911. return 0; /* tab2 must be NOT NULL if tab1 is */
  77912. }
  77913. }
  77914. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  77915. if( pDestIdx->onError!=OE_None ){
  77916. destHasUniqueIdx = 1;
  77917. }
  77918. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  77919. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  77920. }
  77921. if( pSrcIdx==0 ){
  77922. return 0; /* pDestIdx has no corresponding index in pSrc */
  77923. }
  77924. }
  77925. #ifndef SQLITE_OMIT_CHECK
  77926. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  77927. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  77928. }
  77929. #endif
  77930. #ifndef SQLITE_OMIT_FOREIGN_KEY
  77931. /* Disallow the transfer optimization if the destination table constains
  77932. ** any foreign key constraints. This is more restrictive than necessary.
  77933. ** But the main beneficiary of the transfer optimization is the VACUUM
  77934. ** command, and the VACUUM command disables foreign key constraints. So
  77935. ** the extra complication to make this rule less restrictive is probably
  77936. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  77937. */
  77938. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  77939. return 0;
  77940. }
  77941. #endif
  77942. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  77943. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  77944. }
  77945. /* If we get this far, it means that the xfer optimization is at
  77946. ** least a possibility, though it might only work if the destination
  77947. ** table (tab1) is initially empty.
  77948. */
  77949. #ifdef SQLITE_TEST
  77950. sqlite3_xferopt_count++;
  77951. #endif
  77952. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  77953. v = sqlite3GetVdbe(pParse);
  77954. sqlite3CodeVerifySchema(pParse, iDbSrc);
  77955. iSrc = pParse->nTab++;
  77956. iDest = pParse->nTab++;
  77957. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  77958. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  77959. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  77960. || destHasUniqueIdx /* (2) */
  77961. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  77962. ){
  77963. /* In some circumstances, we are able to run the xfer optimization
  77964. ** only if the destination table is initially empty. This code makes
  77965. ** that determination. Conditions under which the destination must
  77966. ** be empty:
  77967. **
  77968. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  77969. ** (If the destination is not initially empty, the rowid fields
  77970. ** of index entries might need to change.)
  77971. **
  77972. ** (2) The destination has a unique index. (The xfer optimization
  77973. ** is unable to test uniqueness.)
  77974. **
  77975. ** (3) onError is something other than OE_Abort and OE_Rollback.
  77976. */
  77977. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  77978. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  77979. sqlite3VdbeJumpHere(v, addr1);
  77980. }else{
  77981. emptyDestTest = 0;
  77982. }
  77983. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  77984. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  77985. regData = sqlite3GetTempReg(pParse);
  77986. regRowid = sqlite3GetTempReg(pParse);
  77987. if( pDest->iPKey>=0 ){
  77988. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  77989. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  77990. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  77991. onError, "PRIMARY KEY must be unique", P4_STATIC);
  77992. sqlite3VdbeJumpHere(v, addr2);
  77993. autoIncStep(pParse, regAutoinc, regRowid);
  77994. }else if( pDest->pIndex==0 ){
  77995. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  77996. }else{
  77997. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  77998. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  77999. }
  78000. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  78001. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  78002. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  78003. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  78004. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  78005. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  78006. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  78007. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  78008. }
  78009. assert( pSrcIdx );
  78010. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  78011. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78012. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  78013. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  78014. (char*)pKey, P4_KEYINFO_HANDOFF);
  78015. VdbeComment((v, "%s", pSrcIdx->zName));
  78016. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  78017. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  78018. (char*)pKey, P4_KEYINFO_HANDOFF);
  78019. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  78020. VdbeComment((v, "%s", pDestIdx->zName));
  78021. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  78022. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  78023. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  78024. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  78025. sqlite3VdbeJumpHere(v, addr1);
  78026. }
  78027. sqlite3VdbeJumpHere(v, emptySrcTest);
  78028. sqlite3ReleaseTempReg(pParse, regRowid);
  78029. sqlite3ReleaseTempReg(pParse, regData);
  78030. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  78031. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78032. if( emptyDestTest ){
  78033. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  78034. sqlite3VdbeJumpHere(v, emptyDestTest);
  78035. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78036. return 0;
  78037. }else{
  78038. return 1;
  78039. }
  78040. }
  78041. #endif /* SQLITE_OMIT_XFER_OPT */
  78042. /************** End of insert.c **********************************************/
  78043. /************** Begin file legacy.c ******************************************/
  78044. /*
  78045. ** 2001 September 15
  78046. **
  78047. ** The author disclaims copyright to this source code. In place of
  78048. ** a legal notice, here is a blessing:
  78049. **
  78050. ** May you do good and not evil.
  78051. ** May you find forgiveness for yourself and forgive others.
  78052. ** May you share freely, never taking more than you give.
  78053. **
  78054. *************************************************************************
  78055. ** Main file for the SQLite library. The routines in this file
  78056. ** implement the programmer interface to the library. Routines in
  78057. ** other files are for internal use by SQLite and should not be
  78058. ** accessed by users of the library.
  78059. */
  78060. /*
  78061. ** Execute SQL code. Return one of the SQLITE_ success/failure
  78062. ** codes. Also write an error message into memory obtained from
  78063. ** malloc() and make *pzErrMsg point to that message.
  78064. **
  78065. ** If the SQL is a query, then for each row in the query result
  78066. ** the xCallback() function is called. pArg becomes the first
  78067. ** argument to xCallback(). If xCallback=NULL then no callback
  78068. ** is invoked, even for queries.
  78069. */
  78070. SQLITE_API int sqlite3_exec(
  78071. sqlite3 *db, /* The database on which the SQL executes */
  78072. const char *zSql, /* The SQL to be executed */
  78073. sqlite3_callback xCallback, /* Invoke this callback routine */
  78074. void *pArg, /* First argument to xCallback() */
  78075. char **pzErrMsg /* Write error messages here */
  78076. ){
  78077. int rc = SQLITE_OK; /* Return code */
  78078. const char *zLeftover; /* Tail of unprocessed SQL */
  78079. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  78080. char **azCols = 0; /* Names of result columns */
  78081. int callbackIsInit; /* True if callback data is initialized */
  78082. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  78083. if( zSql==0 ) zSql = "";
  78084. sqlite3_mutex_enter(db->mutex);
  78085. sqlite3Error(db, SQLITE_OK, 0);
  78086. while( rc==SQLITE_OK && zSql[0] ){
  78087. int nCol;
  78088. char **azVals = 0;
  78089. pStmt = 0;
  78090. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  78091. assert( rc==SQLITE_OK || pStmt==0 );
  78092. if( rc!=SQLITE_OK ){
  78093. continue;
  78094. }
  78095. if( !pStmt ){
  78096. /* this happens for a comment or white-space */
  78097. zSql = zLeftover;
  78098. continue;
  78099. }
  78100. callbackIsInit = 0;
  78101. nCol = sqlite3_column_count(pStmt);
  78102. while( 1 ){
  78103. int i;
  78104. rc = sqlite3_step(pStmt);
  78105. /* Invoke the callback function if required */
  78106. if( xCallback && (SQLITE_ROW==rc ||
  78107. (SQLITE_DONE==rc && !callbackIsInit
  78108. && db->flags&SQLITE_NullCallback)) ){
  78109. if( !callbackIsInit ){
  78110. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  78111. if( azCols==0 ){
  78112. goto exec_out;
  78113. }
  78114. for(i=0; i<nCol; i++){
  78115. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  78116. /* sqlite3VdbeSetColName() installs column names as UTF8
  78117. ** strings so there is no way for sqlite3_column_name() to fail. */
  78118. assert( azCols[i]!=0 );
  78119. }
  78120. callbackIsInit = 1;
  78121. }
  78122. if( rc==SQLITE_ROW ){
  78123. azVals = &azCols[nCol];
  78124. for(i=0; i<nCol; i++){
  78125. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  78126. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  78127. db->mallocFailed = 1;
  78128. goto exec_out;
  78129. }
  78130. }
  78131. }
  78132. if( xCallback(pArg, nCol, azVals, azCols) ){
  78133. rc = SQLITE_ABORT;
  78134. sqlite3VdbeFinalize((Vdbe *)pStmt);
  78135. pStmt = 0;
  78136. sqlite3Error(db, SQLITE_ABORT, 0);
  78137. goto exec_out;
  78138. }
  78139. }
  78140. if( rc!=SQLITE_ROW ){
  78141. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  78142. pStmt = 0;
  78143. zSql = zLeftover;
  78144. while( sqlite3Isspace(zSql[0]) ) zSql++;
  78145. break;
  78146. }
  78147. }
  78148. sqlite3DbFree(db, azCols);
  78149. azCols = 0;
  78150. }
  78151. exec_out:
  78152. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  78153. sqlite3DbFree(db, azCols);
  78154. rc = sqlite3ApiExit(db, rc);
  78155. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  78156. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  78157. *pzErrMsg = sqlite3Malloc(nErrMsg);
  78158. if( *pzErrMsg ){
  78159. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  78160. }else{
  78161. rc = SQLITE_NOMEM;
  78162. sqlite3Error(db, SQLITE_NOMEM, 0);
  78163. }
  78164. }else if( pzErrMsg ){
  78165. *pzErrMsg = 0;
  78166. }
  78167. assert( (rc&db->errMask)==rc );
  78168. sqlite3_mutex_leave(db->mutex);
  78169. return rc;
  78170. }
  78171. /************** End of legacy.c **********************************************/
  78172. /************** Begin file loadext.c *****************************************/
  78173. /*
  78174. ** 2006 June 7
  78175. **
  78176. ** The author disclaims copyright to this source code. In place of
  78177. ** a legal notice, here is a blessing:
  78178. **
  78179. ** May you do good and not evil.
  78180. ** May you find forgiveness for yourself and forgive others.
  78181. ** May you share freely, never taking more than you give.
  78182. **
  78183. *************************************************************************
  78184. ** This file contains code used to dynamically load extensions into
  78185. ** the SQLite library.
  78186. */
  78187. #ifndef SQLITE_CORE
  78188. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  78189. #endif
  78190. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  78191. /************** Begin file sqlite3ext.h **************************************/
  78192. /*
  78193. ** 2006 June 7
  78194. **
  78195. ** The author disclaims copyright to this source code. In place of
  78196. ** a legal notice, here is a blessing:
  78197. **
  78198. ** May you do good and not evil.
  78199. ** May you find forgiveness for yourself and forgive others.
  78200. ** May you share freely, never taking more than you give.
  78201. **
  78202. *************************************************************************
  78203. ** This header file defines the SQLite interface for use by
  78204. ** shared libraries that want to be imported as extensions into
  78205. ** an SQLite instance. Shared libraries that intend to be loaded
  78206. ** as extensions by SQLite should #include this file instead of
  78207. ** sqlite3.h.
  78208. */
  78209. #ifndef _SQLITE3EXT_H_
  78210. #define _SQLITE3EXT_H_
  78211. typedef struct sqlite3_api_routines sqlite3_api_routines;
  78212. /*
  78213. ** The following structure holds pointers to all of the SQLite API
  78214. ** routines.
  78215. **
  78216. ** WARNING: In order to maintain backwards compatibility, add new
  78217. ** interfaces to the end of this structure only. If you insert new
  78218. ** interfaces in the middle of this structure, then older different
  78219. ** versions of SQLite will not be able to load each others' shared
  78220. ** libraries!
  78221. */
  78222. struct sqlite3_api_routines {
  78223. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  78224. int (*aggregate_count)(sqlite3_context*);
  78225. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  78226. int (*bind_double)(sqlite3_stmt*,int,double);
  78227. int (*bind_int)(sqlite3_stmt*,int,int);
  78228. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  78229. int (*bind_null)(sqlite3_stmt*,int);
  78230. int (*bind_parameter_count)(sqlite3_stmt*);
  78231. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  78232. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  78233. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  78234. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  78235. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  78236. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  78237. int (*busy_timeout)(sqlite3*,int ms);
  78238. int (*changes)(sqlite3*);
  78239. int (*close)(sqlite3*);
  78240. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  78241. int eTextRep,const char*));
  78242. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  78243. int eTextRep,const void*));
  78244. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  78245. int (*column_bytes)(sqlite3_stmt*,int iCol);
  78246. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  78247. int (*column_count)(sqlite3_stmt*pStmt);
  78248. const char * (*column_database_name)(sqlite3_stmt*,int);
  78249. const void * (*column_database_name16)(sqlite3_stmt*,int);
  78250. const char * (*column_decltype)(sqlite3_stmt*,int i);
  78251. const void * (*column_decltype16)(sqlite3_stmt*,int);
  78252. double (*column_double)(sqlite3_stmt*,int iCol);
  78253. int (*column_int)(sqlite3_stmt*,int iCol);
  78254. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  78255. const char * (*column_name)(sqlite3_stmt*,int);
  78256. const void * (*column_name16)(sqlite3_stmt*,int);
  78257. const char * (*column_origin_name)(sqlite3_stmt*,int);
  78258. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  78259. const char * (*column_table_name)(sqlite3_stmt*,int);
  78260. const void * (*column_table_name16)(sqlite3_stmt*,int);
  78261. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  78262. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  78263. int (*column_type)(sqlite3_stmt*,int iCol);
  78264. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  78265. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  78266. int (*complete)(const char*sql);
  78267. int (*complete16)(const void*sql);
  78268. int (*create_collation)(sqlite3*,const char*,int,void*,
  78269. int(*)(void*,int,const void*,int,const void*));
  78270. int (*create_collation16)(sqlite3*,const void*,int,void*,
  78271. int(*)(void*,int,const void*,int,const void*));
  78272. int (*create_function)(sqlite3*,const char*,int,int,void*,
  78273. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  78274. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  78275. void (*xFinal)(sqlite3_context*));
  78276. int (*create_function16)(sqlite3*,const void*,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_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  78281. int (*data_count)(sqlite3_stmt*pStmt);
  78282. sqlite3 * (*db_handle)(sqlite3_stmt*);
  78283. int (*declare_vtab)(sqlite3*,const char*);
  78284. int (*enable_shared_cache)(int);
  78285. int (*errcode)(sqlite3*db);
  78286. const char * (*errmsg)(sqlite3*);
  78287. const void * (*errmsg16)(sqlite3*);
  78288. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  78289. int (*expired)(sqlite3_stmt*);
  78290. int (*finalize)(sqlite3_stmt*pStmt);
  78291. void (*free)(void*);
  78292. void (*free_table)(char**result);
  78293. int (*get_autocommit)(sqlite3*);
  78294. void * (*get_auxdata)(sqlite3_context*,int);
  78295. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  78296. int (*global_recover)(void);
  78297. void (*interruptx)(sqlite3*);
  78298. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  78299. const char * (*libversion)(void);
  78300. int (*libversion_number)(void);
  78301. void *(*malloc)(int);
  78302. char * (*mprintf)(const char*,...);
  78303. int (*open)(const char*,sqlite3**);
  78304. int (*open16)(const void*,sqlite3**);
  78305. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  78306. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  78307. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  78308. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  78309. void *(*realloc)(void*,int);
  78310. int (*reset)(sqlite3_stmt*pStmt);
  78311. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  78312. void (*result_double)(sqlite3_context*,double);
  78313. void (*result_error)(sqlite3_context*,const char*,int);
  78314. void (*result_error16)(sqlite3_context*,const void*,int);
  78315. void (*result_int)(sqlite3_context*,int);
  78316. void (*result_int64)(sqlite3_context*,sqlite_int64);
  78317. void (*result_null)(sqlite3_context*);
  78318. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  78319. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  78320. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  78321. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  78322. void (*result_value)(sqlite3_context*,sqlite3_value*);
  78323. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  78324. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  78325. const char*,const char*),void*);
  78326. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  78327. char * (*snprintf)(int,char*,const char*,...);
  78328. int (*step)(sqlite3_stmt*);
  78329. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  78330. char const**,char const**,int*,int*,int*);
  78331. void (*thread_cleanup)(void);
  78332. int (*total_changes)(sqlite3*);
  78333. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  78334. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  78335. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  78336. sqlite_int64),void*);
  78337. void * (*user_data)(sqlite3_context*);
  78338. const void * (*value_blob)(sqlite3_value*);
  78339. int (*value_bytes)(sqlite3_value*);
  78340. int (*value_bytes16)(sqlite3_value*);
  78341. double (*value_double)(sqlite3_value*);
  78342. int (*value_int)(sqlite3_value*);
  78343. sqlite_int64 (*value_int64)(sqlite3_value*);
  78344. int (*value_numeric_type)(sqlite3_value*);
  78345. const unsigned char * (*value_text)(sqlite3_value*);
  78346. const void * (*value_text16)(sqlite3_value*);
  78347. const void * (*value_text16be)(sqlite3_value*);
  78348. const void * (*value_text16le)(sqlite3_value*);
  78349. int (*value_type)(sqlite3_value*);
  78350. char *(*vmprintf)(const char*,va_list);
  78351. /* Added ??? */
  78352. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  78353. /* Added by 3.3.13 */
  78354. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  78355. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  78356. int (*clear_bindings)(sqlite3_stmt*);
  78357. /* Added by 3.4.1 */
  78358. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  78359. void (*xDestroy)(void *));
  78360. /* Added by 3.5.0 */
  78361. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  78362. int (*blob_bytes)(sqlite3_blob*);
  78363. int (*blob_close)(sqlite3_blob*);
  78364. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  78365. int,sqlite3_blob**);
  78366. int (*blob_read)(sqlite3_blob*,void*,int,int);
  78367. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  78368. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  78369. int(*)(void*,int,const void*,int,const void*),
  78370. void(*)(void*));
  78371. int (*file_control)(sqlite3*,const char*,int,void*);
  78372. sqlite3_int64 (*memory_highwater)(int);
  78373. sqlite3_int64 (*memory_used)(void);
  78374. sqlite3_mutex *(*mutex_alloc)(int);
  78375. void (*mutex_enter)(sqlite3_mutex*);
  78376. void (*mutex_free)(sqlite3_mutex*);
  78377. void (*mutex_leave)(sqlite3_mutex*);
  78378. int (*mutex_try)(sqlite3_mutex*);
  78379. int (*open_v2)(const char*,sqlite3**,int,const char*);
  78380. int (*release_memory)(int);
  78381. void (*result_error_nomem)(sqlite3_context*);
  78382. void (*result_error_toobig)(sqlite3_context*);
  78383. int (*sleep)(int);
  78384. void (*soft_heap_limit)(int);
  78385. sqlite3_vfs *(*vfs_find)(const char*);
  78386. int (*vfs_register)(sqlite3_vfs*,int);
  78387. int (*vfs_unregister)(sqlite3_vfs*);
  78388. int (*xthreadsafe)(void);
  78389. void (*result_zeroblob)(sqlite3_context*,int);
  78390. void (*result_error_code)(sqlite3_context*,int);
  78391. int (*test_control)(int, ...);
  78392. void (*randomness)(int,void*);
  78393. sqlite3 *(*context_db_handle)(sqlite3_context*);
  78394. int (*extended_result_codes)(sqlite3*,int);
  78395. int (*limit)(sqlite3*,int,int);
  78396. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  78397. const char *(*sql)(sqlite3_stmt*);
  78398. int (*status)(int,int*,int*,int);
  78399. int (*backup_finish)(sqlite3_backup*);
  78400. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  78401. int (*backup_pagecount)(sqlite3_backup*);
  78402. int (*backup_remaining)(sqlite3_backup*);
  78403. int (*backup_step)(sqlite3_backup*,int);
  78404. const char *(*compileoption_get)(int);
  78405. int (*compileoption_used)(const char*);
  78406. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  78407. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  78408. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  78409. void (*xFinal)(sqlite3_context*),
  78410. void(*xDestroy)(void*));
  78411. int (*db_config)(sqlite3*,int,...);
  78412. sqlite3_mutex *(*db_mutex)(sqlite3*);
  78413. int (*db_status)(sqlite3*,int,int*,int*,int);
  78414. int (*extended_errcode)(sqlite3*);
  78415. void (*log)(int,const char*,...);
  78416. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  78417. const char *(*sourceid)(void);
  78418. int (*stmt_status)(sqlite3_stmt*,int,int);
  78419. int (*strnicmp)(const char*,const char*,int);
  78420. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  78421. int (*wal_autocheckpoint)(sqlite3*,int);
  78422. int (*wal_checkpoint)(sqlite3*,const char*);
  78423. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  78424. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  78425. int (*vtab_config)(sqlite3*,int op,...);
  78426. int (*vtab_on_conflict)(sqlite3*);
  78427. /* Version 3.7.16 and later */
  78428. int (*close_v2)(sqlite3*);
  78429. const char *(*db_filename)(sqlite3*,const char*);
  78430. int (*db_readonly)(sqlite3*,const char*);
  78431. int (*db_release_memory)(sqlite3*);
  78432. const char *(*errstr)(int);
  78433. int (*stmt_busy)(sqlite3_stmt*);
  78434. int (*stmt_readonly)(sqlite3_stmt*);
  78435. int (*stricmp)(const char*,const char*);
  78436. int (*uri_boolean)(const char*,const char*,int);
  78437. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  78438. const char *(*uri_parameter)(const char*,const char*);
  78439. char *(*vsnprintf)(int,char*,const char*,va_list);
  78440. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  78441. };
  78442. /*
  78443. ** The following macros redefine the API routines so that they are
  78444. ** redirected throught the global sqlite3_api structure.
  78445. **
  78446. ** This header file is also used by the loadext.c source file
  78447. ** (part of the main SQLite library - not an extension) so that
  78448. ** it can get access to the sqlite3_api_routines structure
  78449. ** definition. But the main library does not want to redefine
  78450. ** the API. So the redefinition macros are only valid if the
  78451. ** SQLITE_CORE macros is undefined.
  78452. */
  78453. #ifndef SQLITE_CORE
  78454. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  78455. #ifndef SQLITE_OMIT_DEPRECATED
  78456. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  78457. #endif
  78458. #define sqlite3_bind_blob sqlite3_api->bind_blob
  78459. #define sqlite3_bind_double sqlite3_api->bind_double
  78460. #define sqlite3_bind_int sqlite3_api->bind_int
  78461. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  78462. #define sqlite3_bind_null sqlite3_api->bind_null
  78463. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  78464. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  78465. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  78466. #define sqlite3_bind_text sqlite3_api->bind_text
  78467. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  78468. #define sqlite3_bind_value sqlite3_api->bind_value
  78469. #define sqlite3_busy_handler sqlite3_api->busy_handler
  78470. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  78471. #define sqlite3_changes sqlite3_api->changes
  78472. #define sqlite3_close sqlite3_api->close
  78473. #define sqlite3_collation_needed sqlite3_api->collation_needed
  78474. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  78475. #define sqlite3_column_blob sqlite3_api->column_blob
  78476. #define sqlite3_column_bytes sqlite3_api->column_bytes
  78477. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  78478. #define sqlite3_column_count sqlite3_api->column_count
  78479. #define sqlite3_column_database_name sqlite3_api->column_database_name
  78480. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  78481. #define sqlite3_column_decltype sqlite3_api->column_decltype
  78482. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  78483. #define sqlite3_column_double sqlite3_api->column_double
  78484. #define sqlite3_column_int sqlite3_api->column_int
  78485. #define sqlite3_column_int64 sqlite3_api->column_int64
  78486. #define sqlite3_column_name sqlite3_api->column_name
  78487. #define sqlite3_column_name16 sqlite3_api->column_name16
  78488. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  78489. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  78490. #define sqlite3_column_table_name sqlite3_api->column_table_name
  78491. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  78492. #define sqlite3_column_text sqlite3_api->column_text
  78493. #define sqlite3_column_text16 sqlite3_api->column_text16
  78494. #define sqlite3_column_type sqlite3_api->column_type
  78495. #define sqlite3_column_value sqlite3_api->column_value
  78496. #define sqlite3_commit_hook sqlite3_api->commit_hook
  78497. #define sqlite3_complete sqlite3_api->complete
  78498. #define sqlite3_complete16 sqlite3_api->complete16
  78499. #define sqlite3_create_collation sqlite3_api->create_collation
  78500. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  78501. #define sqlite3_create_function sqlite3_api->create_function
  78502. #define sqlite3_create_function16 sqlite3_api->create_function16
  78503. #define sqlite3_create_module sqlite3_api->create_module
  78504. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  78505. #define sqlite3_data_count sqlite3_api->data_count
  78506. #define sqlite3_db_handle sqlite3_api->db_handle
  78507. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  78508. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  78509. #define sqlite3_errcode sqlite3_api->errcode
  78510. #define sqlite3_errmsg sqlite3_api->errmsg
  78511. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  78512. #define sqlite3_exec sqlite3_api->exec
  78513. #ifndef SQLITE_OMIT_DEPRECATED
  78514. #define sqlite3_expired sqlite3_api->expired
  78515. #endif
  78516. #define sqlite3_finalize sqlite3_api->finalize
  78517. #define sqlite3_free sqlite3_api->free
  78518. #define sqlite3_free_table sqlite3_api->free_table
  78519. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  78520. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  78521. #define sqlite3_get_table sqlite3_api->get_table
  78522. #ifndef SQLITE_OMIT_DEPRECATED
  78523. #define sqlite3_global_recover sqlite3_api->global_recover
  78524. #endif
  78525. #define sqlite3_interrupt sqlite3_api->interruptx
  78526. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  78527. #define sqlite3_libversion sqlite3_api->libversion
  78528. #define sqlite3_libversion_number sqlite3_api->libversion_number
  78529. #define sqlite3_malloc sqlite3_api->malloc
  78530. #define sqlite3_mprintf sqlite3_api->mprintf
  78531. #define sqlite3_open sqlite3_api->open
  78532. #define sqlite3_open16 sqlite3_api->open16
  78533. #define sqlite3_prepare sqlite3_api->prepare
  78534. #define sqlite3_prepare16 sqlite3_api->prepare16
  78535. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  78536. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  78537. #define sqlite3_profile sqlite3_api->profile
  78538. #define sqlite3_progress_handler sqlite3_api->progress_handler
  78539. #define sqlite3_realloc sqlite3_api->realloc
  78540. #define sqlite3_reset sqlite3_api->reset
  78541. #define sqlite3_result_blob sqlite3_api->result_blob
  78542. #define sqlite3_result_double sqlite3_api->result_double
  78543. #define sqlite3_result_error sqlite3_api->result_error
  78544. #define sqlite3_result_error16 sqlite3_api->result_error16
  78545. #define sqlite3_result_int sqlite3_api->result_int
  78546. #define sqlite3_result_int64 sqlite3_api->result_int64
  78547. #define sqlite3_result_null sqlite3_api->result_null
  78548. #define sqlite3_result_text sqlite3_api->result_text
  78549. #define sqlite3_result_text16 sqlite3_api->result_text16
  78550. #define sqlite3_result_text16be sqlite3_api->result_text16be
  78551. #define sqlite3_result_text16le sqlite3_api->result_text16le
  78552. #define sqlite3_result_value sqlite3_api->result_value
  78553. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  78554. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  78555. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  78556. #define sqlite3_snprintf sqlite3_api->snprintf
  78557. #define sqlite3_step sqlite3_api->step
  78558. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  78559. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  78560. #define sqlite3_total_changes sqlite3_api->total_changes
  78561. #define sqlite3_trace sqlite3_api->trace
  78562. #ifndef SQLITE_OMIT_DEPRECATED
  78563. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  78564. #endif
  78565. #define sqlite3_update_hook sqlite3_api->update_hook
  78566. #define sqlite3_user_data sqlite3_api->user_data
  78567. #define sqlite3_value_blob sqlite3_api->value_blob
  78568. #define sqlite3_value_bytes sqlite3_api->value_bytes
  78569. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  78570. #define sqlite3_value_double sqlite3_api->value_double
  78571. #define sqlite3_value_int sqlite3_api->value_int
  78572. #define sqlite3_value_int64 sqlite3_api->value_int64
  78573. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  78574. #define sqlite3_value_text sqlite3_api->value_text
  78575. #define sqlite3_value_text16 sqlite3_api->value_text16
  78576. #define sqlite3_value_text16be sqlite3_api->value_text16be
  78577. #define sqlite3_value_text16le sqlite3_api->value_text16le
  78578. #define sqlite3_value_type sqlite3_api->value_type
  78579. #define sqlite3_vmprintf sqlite3_api->vmprintf
  78580. #define sqlite3_overload_function sqlite3_api->overload_function
  78581. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  78582. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  78583. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  78584. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  78585. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  78586. #define sqlite3_blob_close sqlite3_api->blob_close
  78587. #define sqlite3_blob_open sqlite3_api->blob_open
  78588. #define sqlite3_blob_read sqlite3_api->blob_read
  78589. #define sqlite3_blob_write sqlite3_api->blob_write
  78590. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  78591. #define sqlite3_file_control sqlite3_api->file_control
  78592. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  78593. #define sqlite3_memory_used sqlite3_api->memory_used
  78594. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  78595. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  78596. #define sqlite3_mutex_free sqlite3_api->mutex_free
  78597. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  78598. #define sqlite3_mutex_try sqlite3_api->mutex_try
  78599. #define sqlite3_open_v2 sqlite3_api->open_v2
  78600. #define sqlite3_release_memory sqlite3_api->release_memory
  78601. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  78602. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  78603. #define sqlite3_sleep sqlite3_api->sleep
  78604. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  78605. #define sqlite3_vfs_find sqlite3_api->vfs_find
  78606. #define sqlite3_vfs_register sqlite3_api->vfs_register
  78607. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  78608. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  78609. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  78610. #define sqlite3_result_error_code sqlite3_api->result_error_code
  78611. #define sqlite3_test_control sqlite3_api->test_control
  78612. #define sqlite3_randomness sqlite3_api->randomness
  78613. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  78614. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  78615. #define sqlite3_limit sqlite3_api->limit
  78616. #define sqlite3_next_stmt sqlite3_api->next_stmt
  78617. #define sqlite3_sql sqlite3_api->sql
  78618. #define sqlite3_status sqlite3_api->status
  78619. #define sqlite3_backup_finish sqlite3_api->backup_finish
  78620. #define sqlite3_backup_init sqlite3_api->backup_init
  78621. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  78622. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  78623. #define sqlite3_backup_step sqlite3_api->backup_step
  78624. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  78625. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  78626. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  78627. #define sqlite3_db_config sqlite3_api->db_config
  78628. #define sqlite3_db_mutex sqlite3_api->db_mutex
  78629. #define sqlite3_db_status sqlite3_api->db_status
  78630. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  78631. #define sqlite3_log sqlite3_api->log
  78632. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  78633. #define sqlite3_sourceid sqlite3_api->sourceid
  78634. #define sqlite3_stmt_status sqlite3_api->stmt_status
  78635. #define sqlite3_strnicmp sqlite3_api->strnicmp
  78636. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  78637. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  78638. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  78639. #define sqlite3_wal_hook sqlite3_api->wal_hook
  78640. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  78641. #define sqlite3_vtab_config sqlite3_api->vtab_config
  78642. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  78643. /* Version 3.7.16 and later */
  78644. #define sqlite3_close_v2 sqlite3_api->close_v2
  78645. #define sqlite3_db_filename sqlite3_api->db_filename
  78646. #define sqlite3_db_readonly sqlite3_api->db_readonly
  78647. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  78648. #define sqlite3_errstr sqlite3_api->errstr
  78649. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  78650. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  78651. #define sqlite3_stricmp sqlite3_api->stricmp
  78652. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  78653. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  78654. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  78655. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  78656. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  78657. #endif /* SQLITE_CORE */
  78658. #ifndef SQLITE_CORE
  78659. /* This case when the file really is being compiled as a loadable
  78660. ** extension */
  78661. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  78662. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  78663. # define SQLITE_EXTENSION_INIT3 \
  78664. extern const sqlite3_api_routines *sqlite3_api;
  78665. #else
  78666. /* This case when the file is being statically linked into the
  78667. ** application */
  78668. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  78669. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  78670. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  78671. #endif
  78672. #endif /* _SQLITE3EXT_H_ */
  78673. /************** End of sqlite3ext.h ******************************************/
  78674. /************** Continuing where we left off in loadext.c ********************/
  78675. /* #include <string.h> */
  78676. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  78677. /*
  78678. ** Some API routines are omitted when various features are
  78679. ** excluded from a build of SQLite. Substitute a NULL pointer
  78680. ** for any missing APIs.
  78681. */
  78682. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  78683. # define sqlite3_column_database_name 0
  78684. # define sqlite3_column_database_name16 0
  78685. # define sqlite3_column_table_name 0
  78686. # define sqlite3_column_table_name16 0
  78687. # define sqlite3_column_origin_name 0
  78688. # define sqlite3_column_origin_name16 0
  78689. # define sqlite3_table_column_metadata 0
  78690. #endif
  78691. #ifdef SQLITE_OMIT_AUTHORIZATION
  78692. # define sqlite3_set_authorizer 0
  78693. #endif
  78694. #ifdef SQLITE_OMIT_UTF16
  78695. # define sqlite3_bind_text16 0
  78696. # define sqlite3_collation_needed16 0
  78697. # define sqlite3_column_decltype16 0
  78698. # define sqlite3_column_name16 0
  78699. # define sqlite3_column_text16 0
  78700. # define sqlite3_complete16 0
  78701. # define sqlite3_create_collation16 0
  78702. # define sqlite3_create_function16 0
  78703. # define sqlite3_errmsg16 0
  78704. # define sqlite3_open16 0
  78705. # define sqlite3_prepare16 0
  78706. # define sqlite3_prepare16_v2 0
  78707. # define sqlite3_result_error16 0
  78708. # define sqlite3_result_text16 0
  78709. # define sqlite3_result_text16be 0
  78710. # define sqlite3_result_text16le 0
  78711. # define sqlite3_value_text16 0
  78712. # define sqlite3_value_text16be 0
  78713. # define sqlite3_value_text16le 0
  78714. # define sqlite3_column_database_name16 0
  78715. # define sqlite3_column_table_name16 0
  78716. # define sqlite3_column_origin_name16 0
  78717. #endif
  78718. #ifdef SQLITE_OMIT_COMPLETE
  78719. # define sqlite3_complete 0
  78720. # define sqlite3_complete16 0
  78721. #endif
  78722. #ifdef SQLITE_OMIT_DECLTYPE
  78723. # define sqlite3_column_decltype16 0
  78724. # define sqlite3_column_decltype 0
  78725. #endif
  78726. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  78727. # define sqlite3_progress_handler 0
  78728. #endif
  78729. #ifdef SQLITE_OMIT_VIRTUALTABLE
  78730. # define sqlite3_create_module 0
  78731. # define sqlite3_create_module_v2 0
  78732. # define sqlite3_declare_vtab 0
  78733. # define sqlite3_vtab_config 0
  78734. # define sqlite3_vtab_on_conflict 0
  78735. #endif
  78736. #ifdef SQLITE_OMIT_SHARED_CACHE
  78737. # define sqlite3_enable_shared_cache 0
  78738. #endif
  78739. #ifdef SQLITE_OMIT_TRACE
  78740. # define sqlite3_profile 0
  78741. # define sqlite3_trace 0
  78742. #endif
  78743. #ifdef SQLITE_OMIT_GET_TABLE
  78744. # define sqlite3_free_table 0
  78745. # define sqlite3_get_table 0
  78746. #endif
  78747. #ifdef SQLITE_OMIT_INCRBLOB
  78748. #define sqlite3_bind_zeroblob 0
  78749. #define sqlite3_blob_bytes 0
  78750. #define sqlite3_blob_close 0
  78751. #define sqlite3_blob_open 0
  78752. #define sqlite3_blob_read 0
  78753. #define sqlite3_blob_write 0
  78754. #define sqlite3_blob_reopen 0
  78755. #endif
  78756. /*
  78757. ** The following structure contains pointers to all SQLite API routines.
  78758. ** A pointer to this structure is passed into extensions when they are
  78759. ** loaded so that the extension can make calls back into the SQLite
  78760. ** library.
  78761. **
  78762. ** When adding new APIs, add them to the bottom of this structure
  78763. ** in order to preserve backwards compatibility.
  78764. **
  78765. ** Extensions that use newer APIs should first call the
  78766. ** sqlite3_libversion_number() to make sure that the API they
  78767. ** intend to use is supported by the library. Extensions should
  78768. ** also check to make sure that the pointer to the function is
  78769. ** not NULL before calling it.
  78770. */
  78771. static const sqlite3_api_routines sqlite3Apis = {
  78772. sqlite3_aggregate_context,
  78773. #ifndef SQLITE_OMIT_DEPRECATED
  78774. sqlite3_aggregate_count,
  78775. #else
  78776. 0,
  78777. #endif
  78778. sqlite3_bind_blob,
  78779. sqlite3_bind_double,
  78780. sqlite3_bind_int,
  78781. sqlite3_bind_int64,
  78782. sqlite3_bind_null,
  78783. sqlite3_bind_parameter_count,
  78784. sqlite3_bind_parameter_index,
  78785. sqlite3_bind_parameter_name,
  78786. sqlite3_bind_text,
  78787. sqlite3_bind_text16,
  78788. sqlite3_bind_value,
  78789. sqlite3_busy_handler,
  78790. sqlite3_busy_timeout,
  78791. sqlite3_changes,
  78792. sqlite3_close,
  78793. sqlite3_collation_needed,
  78794. sqlite3_collation_needed16,
  78795. sqlite3_column_blob,
  78796. sqlite3_column_bytes,
  78797. sqlite3_column_bytes16,
  78798. sqlite3_column_count,
  78799. sqlite3_column_database_name,
  78800. sqlite3_column_database_name16,
  78801. sqlite3_column_decltype,
  78802. sqlite3_column_decltype16,
  78803. sqlite3_column_double,
  78804. sqlite3_column_int,
  78805. sqlite3_column_int64,
  78806. sqlite3_column_name,
  78807. sqlite3_column_name16,
  78808. sqlite3_column_origin_name,
  78809. sqlite3_column_origin_name16,
  78810. sqlite3_column_table_name,
  78811. sqlite3_column_table_name16,
  78812. sqlite3_column_text,
  78813. sqlite3_column_text16,
  78814. sqlite3_column_type,
  78815. sqlite3_column_value,
  78816. sqlite3_commit_hook,
  78817. sqlite3_complete,
  78818. sqlite3_complete16,
  78819. sqlite3_create_collation,
  78820. sqlite3_create_collation16,
  78821. sqlite3_create_function,
  78822. sqlite3_create_function16,
  78823. sqlite3_create_module,
  78824. sqlite3_data_count,
  78825. sqlite3_db_handle,
  78826. sqlite3_declare_vtab,
  78827. sqlite3_enable_shared_cache,
  78828. sqlite3_errcode,
  78829. sqlite3_errmsg,
  78830. sqlite3_errmsg16,
  78831. sqlite3_exec,
  78832. #ifndef SQLITE_OMIT_DEPRECATED
  78833. sqlite3_expired,
  78834. #else
  78835. 0,
  78836. #endif
  78837. sqlite3_finalize,
  78838. sqlite3_free,
  78839. sqlite3_free_table,
  78840. sqlite3_get_autocommit,
  78841. sqlite3_get_auxdata,
  78842. sqlite3_get_table,
  78843. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  78844. sqlite3_interrupt,
  78845. sqlite3_last_insert_rowid,
  78846. sqlite3_libversion,
  78847. sqlite3_libversion_number,
  78848. sqlite3_malloc,
  78849. sqlite3_mprintf,
  78850. sqlite3_open,
  78851. sqlite3_open16,
  78852. sqlite3_prepare,
  78853. sqlite3_prepare16,
  78854. sqlite3_profile,
  78855. sqlite3_progress_handler,
  78856. sqlite3_realloc,
  78857. sqlite3_reset,
  78858. sqlite3_result_blob,
  78859. sqlite3_result_double,
  78860. sqlite3_result_error,
  78861. sqlite3_result_error16,
  78862. sqlite3_result_int,
  78863. sqlite3_result_int64,
  78864. sqlite3_result_null,
  78865. sqlite3_result_text,
  78866. sqlite3_result_text16,
  78867. sqlite3_result_text16be,
  78868. sqlite3_result_text16le,
  78869. sqlite3_result_value,
  78870. sqlite3_rollback_hook,
  78871. sqlite3_set_authorizer,
  78872. sqlite3_set_auxdata,
  78873. sqlite3_snprintf,
  78874. sqlite3_step,
  78875. sqlite3_table_column_metadata,
  78876. #ifndef SQLITE_OMIT_DEPRECATED
  78877. sqlite3_thread_cleanup,
  78878. #else
  78879. 0,
  78880. #endif
  78881. sqlite3_total_changes,
  78882. sqlite3_trace,
  78883. #ifndef SQLITE_OMIT_DEPRECATED
  78884. sqlite3_transfer_bindings,
  78885. #else
  78886. 0,
  78887. #endif
  78888. sqlite3_update_hook,
  78889. sqlite3_user_data,
  78890. sqlite3_value_blob,
  78891. sqlite3_value_bytes,
  78892. sqlite3_value_bytes16,
  78893. sqlite3_value_double,
  78894. sqlite3_value_int,
  78895. sqlite3_value_int64,
  78896. sqlite3_value_numeric_type,
  78897. sqlite3_value_text,
  78898. sqlite3_value_text16,
  78899. sqlite3_value_text16be,
  78900. sqlite3_value_text16le,
  78901. sqlite3_value_type,
  78902. sqlite3_vmprintf,
  78903. /*
  78904. ** The original API set ends here. All extensions can call any
  78905. ** of the APIs above provided that the pointer is not NULL. But
  78906. ** before calling APIs that follow, extension should check the
  78907. ** sqlite3_libversion_number() to make sure they are dealing with
  78908. ** a library that is new enough to support that API.
  78909. *************************************************************************
  78910. */
  78911. sqlite3_overload_function,
  78912. /*
  78913. ** Added after 3.3.13
  78914. */
  78915. sqlite3_prepare_v2,
  78916. sqlite3_prepare16_v2,
  78917. sqlite3_clear_bindings,
  78918. /*
  78919. ** Added for 3.4.1
  78920. */
  78921. sqlite3_create_module_v2,
  78922. /*
  78923. ** Added for 3.5.0
  78924. */
  78925. sqlite3_bind_zeroblob,
  78926. sqlite3_blob_bytes,
  78927. sqlite3_blob_close,
  78928. sqlite3_blob_open,
  78929. sqlite3_blob_read,
  78930. sqlite3_blob_write,
  78931. sqlite3_create_collation_v2,
  78932. sqlite3_file_control,
  78933. sqlite3_memory_highwater,
  78934. sqlite3_memory_used,
  78935. #ifdef SQLITE_MUTEX_OMIT
  78936. 0,
  78937. 0,
  78938. 0,
  78939. 0,
  78940. 0,
  78941. #else
  78942. sqlite3_mutex_alloc,
  78943. sqlite3_mutex_enter,
  78944. sqlite3_mutex_free,
  78945. sqlite3_mutex_leave,
  78946. sqlite3_mutex_try,
  78947. #endif
  78948. sqlite3_open_v2,
  78949. sqlite3_release_memory,
  78950. sqlite3_result_error_nomem,
  78951. sqlite3_result_error_toobig,
  78952. sqlite3_sleep,
  78953. sqlite3_soft_heap_limit,
  78954. sqlite3_vfs_find,
  78955. sqlite3_vfs_register,
  78956. sqlite3_vfs_unregister,
  78957. /*
  78958. ** Added for 3.5.8
  78959. */
  78960. sqlite3_threadsafe,
  78961. sqlite3_result_zeroblob,
  78962. sqlite3_result_error_code,
  78963. sqlite3_test_control,
  78964. sqlite3_randomness,
  78965. sqlite3_context_db_handle,
  78966. /*
  78967. ** Added for 3.6.0
  78968. */
  78969. sqlite3_extended_result_codes,
  78970. sqlite3_limit,
  78971. sqlite3_next_stmt,
  78972. sqlite3_sql,
  78973. sqlite3_status,
  78974. /*
  78975. ** Added for 3.7.4
  78976. */
  78977. sqlite3_backup_finish,
  78978. sqlite3_backup_init,
  78979. sqlite3_backup_pagecount,
  78980. sqlite3_backup_remaining,
  78981. sqlite3_backup_step,
  78982. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  78983. sqlite3_compileoption_get,
  78984. sqlite3_compileoption_used,
  78985. #else
  78986. 0,
  78987. 0,
  78988. #endif
  78989. sqlite3_create_function_v2,
  78990. sqlite3_db_config,
  78991. sqlite3_db_mutex,
  78992. sqlite3_db_status,
  78993. sqlite3_extended_errcode,
  78994. sqlite3_log,
  78995. sqlite3_soft_heap_limit64,
  78996. sqlite3_sourceid,
  78997. sqlite3_stmt_status,
  78998. sqlite3_strnicmp,
  78999. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  79000. sqlite3_unlock_notify,
  79001. #else
  79002. 0,
  79003. #endif
  79004. #ifndef SQLITE_OMIT_WAL
  79005. sqlite3_wal_autocheckpoint,
  79006. sqlite3_wal_checkpoint,
  79007. sqlite3_wal_hook,
  79008. #else
  79009. 0,
  79010. 0,
  79011. 0,
  79012. #endif
  79013. sqlite3_blob_reopen,
  79014. sqlite3_vtab_config,
  79015. sqlite3_vtab_on_conflict,
  79016. sqlite3_close_v2,
  79017. sqlite3_db_filename,
  79018. sqlite3_db_readonly,
  79019. sqlite3_db_release_memory,
  79020. sqlite3_errstr,
  79021. sqlite3_stmt_busy,
  79022. sqlite3_stmt_readonly,
  79023. sqlite3_stricmp,
  79024. sqlite3_uri_boolean,
  79025. sqlite3_uri_int64,
  79026. sqlite3_uri_parameter,
  79027. sqlite3_vsnprintf,
  79028. sqlite3_wal_checkpoint_v2
  79029. };
  79030. /*
  79031. ** Attempt to load an SQLite extension library contained in the file
  79032. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  79033. ** default entry point name (sqlite3_extension_init) is used. Use
  79034. ** of the default name is recommended.
  79035. **
  79036. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  79037. **
  79038. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  79039. ** error message text. The calling function should free this memory
  79040. ** by calling sqlite3DbFree(db, ).
  79041. */
  79042. static int sqlite3LoadExtension(
  79043. sqlite3 *db, /* Load the extension into this database connection */
  79044. const char *zFile, /* Name of the shared library containing extension */
  79045. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  79046. char **pzErrMsg /* Put error message here if not 0 */
  79047. ){
  79048. sqlite3_vfs *pVfs = db->pVfs;
  79049. void *handle;
  79050. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  79051. char *zErrmsg = 0;
  79052. const char *zEntry;
  79053. char *zAltEntry = 0;
  79054. void **aHandle;
  79055. int nMsg = 300 + sqlite3Strlen30(zFile);
  79056. int ii;
  79057. /* Shared library endings to try if zFile cannot be loaded as written */
  79058. static const char *azEndings[] = {
  79059. #if SQLITE_OS_WIN
  79060. "dll"
  79061. #elif defined(__APPLE__)
  79062. "dylib"
  79063. #else
  79064. "so"
  79065. #endif
  79066. };
  79067. if( pzErrMsg ) *pzErrMsg = 0;
  79068. /* Ticket #1863. To avoid a creating security problems for older
  79069. ** applications that relink against newer versions of SQLite, the
  79070. ** ability to run load_extension is turned off by default. One
  79071. ** must call sqlite3_enable_load_extension() to turn on extension
  79072. ** loading. Otherwise you get the following error.
  79073. */
  79074. if( (db->flags & SQLITE_LoadExtension)==0 ){
  79075. if( pzErrMsg ){
  79076. *pzErrMsg = sqlite3_mprintf("not authorized");
  79077. }
  79078. return SQLITE_ERROR;
  79079. }
  79080. zEntry = zProc ? zProc : "sqlite3_extension_init";
  79081. handle = sqlite3OsDlOpen(pVfs, zFile);
  79082. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  79083. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  79084. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  79085. if( zAltFile==0 ) return SQLITE_NOMEM;
  79086. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  79087. sqlite3_free(zAltFile);
  79088. }
  79089. #endif
  79090. if( handle==0 ){
  79091. if( pzErrMsg ){
  79092. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  79093. if( zErrmsg ){
  79094. sqlite3_snprintf(nMsg, zErrmsg,
  79095. "unable to open shared library [%s]", zFile);
  79096. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  79097. }
  79098. }
  79099. return SQLITE_ERROR;
  79100. }
  79101. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79102. sqlite3OsDlSym(pVfs, handle, zEntry);
  79103. /* If no entry point was specified and the default legacy
  79104. ** entry point name "sqlite3_extension_init" was not found, then
  79105. ** construct an entry point name "sqlite3_X_init" where the X is
  79106. ** replaced by the lowercase value of every ASCII alphabetic
  79107. ** character in the filename after the last "/" upto the first ".",
  79108. ** and eliding the first three characters if they are "lib".
  79109. ** Examples:
  79110. **
  79111. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  79112. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  79113. */
  79114. if( xInit==0 && zProc==0 ){
  79115. int iFile, iEntry, c;
  79116. int ncFile = sqlite3Strlen30(zFile);
  79117. zAltEntry = sqlite3_malloc(ncFile+30);
  79118. if( zAltEntry==0 ){
  79119. sqlite3OsDlClose(pVfs, handle);
  79120. return SQLITE_NOMEM;
  79121. }
  79122. memcpy(zAltEntry, "sqlite3_", 8);
  79123. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  79124. iFile++;
  79125. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  79126. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  79127. if( sqlite3Isalpha(c) ){
  79128. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  79129. }
  79130. }
  79131. memcpy(zAltEntry+iEntry, "_init", 6);
  79132. zEntry = zAltEntry;
  79133. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79134. sqlite3OsDlSym(pVfs, handle, zEntry);
  79135. }
  79136. if( xInit==0 ){
  79137. if( pzErrMsg ){
  79138. nMsg += sqlite3Strlen30(zEntry);
  79139. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  79140. if( zErrmsg ){
  79141. sqlite3_snprintf(nMsg, zErrmsg,
  79142. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  79143. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  79144. }
  79145. }
  79146. sqlite3OsDlClose(pVfs, handle);
  79147. sqlite3_free(zAltEntry);
  79148. return SQLITE_ERROR;
  79149. }
  79150. sqlite3_free(zAltEntry);
  79151. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  79152. if( pzErrMsg ){
  79153. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  79154. }
  79155. sqlite3_free(zErrmsg);
  79156. sqlite3OsDlClose(pVfs, handle);
  79157. return SQLITE_ERROR;
  79158. }
  79159. /* Append the new shared library handle to the db->aExtension array. */
  79160. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  79161. if( aHandle==0 ){
  79162. return SQLITE_NOMEM;
  79163. }
  79164. if( db->nExtension>0 ){
  79165. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  79166. }
  79167. sqlite3DbFree(db, db->aExtension);
  79168. db->aExtension = aHandle;
  79169. db->aExtension[db->nExtension++] = handle;
  79170. return SQLITE_OK;
  79171. }
  79172. SQLITE_API int sqlite3_load_extension(
  79173. sqlite3 *db, /* Load the extension into this database connection */
  79174. const char *zFile, /* Name of the shared library containing extension */
  79175. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  79176. char **pzErrMsg /* Put error message here if not 0 */
  79177. ){
  79178. int rc;
  79179. sqlite3_mutex_enter(db->mutex);
  79180. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  79181. rc = sqlite3ApiExit(db, rc);
  79182. sqlite3_mutex_leave(db->mutex);
  79183. return rc;
  79184. }
  79185. /*
  79186. ** Call this routine when the database connection is closing in order
  79187. ** to clean up loaded extensions
  79188. */
  79189. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  79190. int i;
  79191. assert( sqlite3_mutex_held(db->mutex) );
  79192. for(i=0; i<db->nExtension; i++){
  79193. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  79194. }
  79195. sqlite3DbFree(db, db->aExtension);
  79196. }
  79197. /*
  79198. ** Enable or disable extension loading. Extension loading is disabled by
  79199. ** default so as not to open security holes in older applications.
  79200. */
  79201. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  79202. sqlite3_mutex_enter(db->mutex);
  79203. if( onoff ){
  79204. db->flags |= SQLITE_LoadExtension;
  79205. }else{
  79206. db->flags &= ~SQLITE_LoadExtension;
  79207. }
  79208. sqlite3_mutex_leave(db->mutex);
  79209. return SQLITE_OK;
  79210. }
  79211. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  79212. /*
  79213. ** The auto-extension code added regardless of whether or not extension
  79214. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  79215. ** code if regular extension loading is not available. This is that
  79216. ** dummy pointer.
  79217. */
  79218. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  79219. static const sqlite3_api_routines sqlite3Apis = { 0 };
  79220. #endif
  79221. /*
  79222. ** The following object holds the list of automatically loaded
  79223. ** extensions.
  79224. **
  79225. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  79226. ** mutex must be held while accessing this list.
  79227. */
  79228. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  79229. static SQLITE_WSD struct sqlite3AutoExtList {
  79230. int nExt; /* Number of entries in aExt[] */
  79231. void (**aExt)(void); /* Pointers to the extension init functions */
  79232. } sqlite3Autoext = { 0, 0 };
  79233. /* The "wsdAutoext" macro will resolve to the autoextension
  79234. ** state vector. If writable static data is unsupported on the target,
  79235. ** we have to locate the state vector at run-time. In the more common
  79236. ** case where writable static data is supported, wsdStat can refer directly
  79237. ** to the "sqlite3Autoext" state vector declared above.
  79238. */
  79239. #ifdef SQLITE_OMIT_WSD
  79240. # define wsdAutoextInit \
  79241. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  79242. # define wsdAutoext x[0]
  79243. #else
  79244. # define wsdAutoextInit
  79245. # define wsdAutoext sqlite3Autoext
  79246. #endif
  79247. /*
  79248. ** Register a statically linked extension that is automatically
  79249. ** loaded by every new database connection.
  79250. */
  79251. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  79252. int rc = SQLITE_OK;
  79253. #ifndef SQLITE_OMIT_AUTOINIT
  79254. rc = sqlite3_initialize();
  79255. if( rc ){
  79256. return rc;
  79257. }else
  79258. #endif
  79259. {
  79260. int i;
  79261. #if SQLITE_THREADSAFE
  79262. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79263. #endif
  79264. wsdAutoextInit;
  79265. sqlite3_mutex_enter(mutex);
  79266. for(i=0; i<wsdAutoext.nExt; i++){
  79267. if( wsdAutoext.aExt[i]==xInit ) break;
  79268. }
  79269. if( i==wsdAutoext.nExt ){
  79270. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  79271. void (**aNew)(void);
  79272. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  79273. if( aNew==0 ){
  79274. rc = SQLITE_NOMEM;
  79275. }else{
  79276. wsdAutoext.aExt = aNew;
  79277. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  79278. wsdAutoext.nExt++;
  79279. }
  79280. }
  79281. sqlite3_mutex_leave(mutex);
  79282. assert( (rc&0xff)==rc );
  79283. return rc;
  79284. }
  79285. }
  79286. /*
  79287. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  79288. ** set of routines that is invoked for each new database connection, if it
  79289. ** is currently on the list. If xInit is not on the list, then this
  79290. ** routine is a no-op.
  79291. **
  79292. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  79293. ** was not on the list.
  79294. */
  79295. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  79296. #if SQLITE_THREADSAFE
  79297. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79298. #endif
  79299. int i;
  79300. int n = 0;
  79301. wsdAutoextInit;
  79302. sqlite3_mutex_enter(mutex);
  79303. for(i=wsdAutoext.nExt-1; i>=0; i--){
  79304. if( wsdAutoext.aExt[i]==xInit ){
  79305. wsdAutoext.nExt--;
  79306. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  79307. n++;
  79308. break;
  79309. }
  79310. }
  79311. sqlite3_mutex_leave(mutex);
  79312. return n;
  79313. }
  79314. /*
  79315. ** Reset the automatic extension loading mechanism.
  79316. */
  79317. SQLITE_API void sqlite3_reset_auto_extension(void){
  79318. #ifndef SQLITE_OMIT_AUTOINIT
  79319. if( sqlite3_initialize()==SQLITE_OK )
  79320. #endif
  79321. {
  79322. #if SQLITE_THREADSAFE
  79323. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79324. #endif
  79325. wsdAutoextInit;
  79326. sqlite3_mutex_enter(mutex);
  79327. sqlite3_free(wsdAutoext.aExt);
  79328. wsdAutoext.aExt = 0;
  79329. wsdAutoext.nExt = 0;
  79330. sqlite3_mutex_leave(mutex);
  79331. }
  79332. }
  79333. /*
  79334. ** Load all automatic extensions.
  79335. **
  79336. ** If anything goes wrong, set an error in the database connection.
  79337. */
  79338. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  79339. int i;
  79340. int go = 1;
  79341. int rc;
  79342. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  79343. wsdAutoextInit;
  79344. if( wsdAutoext.nExt==0 ){
  79345. /* Common case: early out without every having to acquire a mutex */
  79346. return;
  79347. }
  79348. for(i=0; go; i++){
  79349. char *zErrmsg;
  79350. #if SQLITE_THREADSAFE
  79351. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79352. #endif
  79353. sqlite3_mutex_enter(mutex);
  79354. if( i>=wsdAutoext.nExt ){
  79355. xInit = 0;
  79356. go = 0;
  79357. }else{
  79358. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79359. wsdAutoext.aExt[i];
  79360. }
  79361. sqlite3_mutex_leave(mutex);
  79362. zErrmsg = 0;
  79363. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  79364. sqlite3Error(db, rc,
  79365. "automatic extension loading failed: %s", zErrmsg);
  79366. go = 0;
  79367. }
  79368. sqlite3_free(zErrmsg);
  79369. }
  79370. }
  79371. /************** End of loadext.c *********************************************/
  79372. /************** Begin file pragma.c ******************************************/
  79373. /*
  79374. ** 2003 April 6
  79375. **
  79376. ** The author disclaims copyright to this source code. In place of
  79377. ** a legal notice, here is a blessing:
  79378. **
  79379. ** May you do good and not evil.
  79380. ** May you find forgiveness for yourself and forgive others.
  79381. ** May you share freely, never taking more than you give.
  79382. **
  79383. *************************************************************************
  79384. ** This file contains code used to implement the PRAGMA command.
  79385. */
  79386. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  79387. # if defined(__APPLE__)
  79388. # define SQLITE_ENABLE_LOCKING_STYLE 1
  79389. # else
  79390. # define SQLITE_ENABLE_LOCKING_STYLE 0
  79391. # endif
  79392. #endif
  79393. /***************************************************************************
  79394. ** The next block of code, including the PragTyp_XXXX macro definitions and
  79395. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  79396. **
  79397. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  79398. ** that script. Then copy/paste the output in place of the following:
  79399. */
  79400. #define PragTyp_HEADER_VALUE 0
  79401. #define PragTyp_AUTO_VACUUM 1
  79402. #define PragTyp_FLAG 2
  79403. #define PragTyp_BUSY_TIMEOUT 3
  79404. #define PragTyp_CACHE_SIZE 4
  79405. #define PragTyp_CASE_SENSITIVE_LIKE 5
  79406. #define PragTyp_COLLATION_LIST 6
  79407. #define PragTyp_COMPILE_OPTIONS 7
  79408. #define PragTyp_DATA_STORE_DIRECTORY 8
  79409. #define PragTyp_DATABASE_LIST 9
  79410. #define PragTyp_DEFAULT_CACHE_SIZE 10
  79411. #define PragTyp_ENCODING 11
  79412. #define PragTyp_FOREIGN_KEY_CHECK 12
  79413. #define PragTyp_FOREIGN_KEY_LIST 13
  79414. #define PragTyp_INCREMENTAL_VACUUM 14
  79415. #define PragTyp_INDEX_INFO 15
  79416. #define PragTyp_INDEX_LIST 16
  79417. #define PragTyp_INTEGRITY_CHECK 17
  79418. #define PragTyp_JOURNAL_MODE 18
  79419. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  79420. #define PragTyp_LOCK_PROXY_FILE 20
  79421. #define PragTyp_LOCKING_MODE 21
  79422. #define PragTyp_PAGE_COUNT 22
  79423. #define PragTyp_MMAP_SIZE 23
  79424. #define PragTyp_PAGE_SIZE 24
  79425. #define PragTyp_SECURE_DELETE 25
  79426. #define PragTyp_SHRINK_MEMORY 26
  79427. #define PragTyp_SOFT_HEAP_LIMIT 27
  79428. #define PragTyp_STATS 28
  79429. #define PragTyp_SYNCHRONOUS 29
  79430. #define PragTyp_TABLE_INFO 30
  79431. #define PragTyp_TEMP_STORE 31
  79432. #define PragTyp_TEMP_STORE_DIRECTORY 32
  79433. #define PragTyp_WAL_AUTOCHECKPOINT 33
  79434. #define PragTyp_WAL_CHECKPOINT 34
  79435. #define PragTyp_ACTIVATE_EXTENSIONS 35
  79436. #define PragTyp_HEXKEY 36
  79437. #define PragTyp_KEY 37
  79438. #define PragTyp_REKEY 38
  79439. #define PragTyp_LOCK_STATUS 39
  79440. #define PragTyp_PARSER_TRACE 40
  79441. #define PragFlag_NeedSchema 0x01
  79442. static const struct sPragmaNames {
  79443. const char *const zName; /* Name of pragma */
  79444. u8 ePragTyp; /* PragTyp_XXX value */
  79445. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  79446. u32 iArg; /* Extra argument */
  79447. } aPragmaNames[] = {
  79448. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  79449. { /* zName: */ "activate_extensions",
  79450. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  79451. /* ePragFlag: */ 0,
  79452. /* iArg: */ 0 },
  79453. #endif
  79454. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79455. { /* zName: */ "application_id",
  79456. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79457. /* ePragFlag: */ 0,
  79458. /* iArg: */ 0 },
  79459. #endif
  79460. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79461. { /* zName: */ "auto_vacuum",
  79462. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  79463. /* ePragFlag: */ PragFlag_NeedSchema,
  79464. /* iArg: */ 0 },
  79465. #endif
  79466. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  79467. { /* zName: */ "automatic_index",
  79468. /* ePragTyp: */ PragTyp_FLAG,
  79469. /* ePragFlag: */ 0,
  79470. /* iArg: */ SQLITE_AutoIndex },
  79471. #endif
  79472. { /* zName: */ "busy_timeout",
  79473. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  79474. /* ePragFlag: */ 0,
  79475. /* iArg: */ 0 },
  79476. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79477. { /* zName: */ "cache_size",
  79478. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  79479. /* ePragFlag: */ PragFlag_NeedSchema,
  79480. /* iArg: */ 0 },
  79481. #endif
  79482. { /* zName: */ "cache_spill",
  79483. /* ePragTyp: */ PragTyp_FLAG,
  79484. /* ePragFlag: */ 0,
  79485. /* iArg: */ SQLITE_CacheSpill },
  79486. { /* zName: */ "case_sensitive_like",
  79487. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  79488. /* ePragFlag: */ 0,
  79489. /* iArg: */ 0 },
  79490. { /* zName: */ "checkpoint_fullfsync",
  79491. /* ePragTyp: */ PragTyp_FLAG,
  79492. /* ePragFlag: */ 0,
  79493. /* iArg: */ SQLITE_CkptFullFSync },
  79494. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79495. { /* zName: */ "collation_list",
  79496. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  79497. /* ePragFlag: */ 0,
  79498. /* iArg: */ 0 },
  79499. #endif
  79500. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  79501. { /* zName: */ "compile_options",
  79502. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  79503. /* ePragFlag: */ 0,
  79504. /* iArg: */ 0 },
  79505. #endif
  79506. { /* zName: */ "count_changes",
  79507. /* ePragTyp: */ PragTyp_FLAG,
  79508. /* ePragFlag: */ 0,
  79509. /* iArg: */ SQLITE_CountRows },
  79510. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  79511. { /* zName: */ "data_store_directory",
  79512. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  79513. /* ePragFlag: */ 0,
  79514. /* iArg: */ 0 },
  79515. #endif
  79516. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79517. { /* zName: */ "database_list",
  79518. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  79519. /* ePragFlag: */ PragFlag_NeedSchema,
  79520. /* iArg: */ 0 },
  79521. #endif
  79522. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  79523. { /* zName: */ "default_cache_size",
  79524. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  79525. /* ePragFlag: */ PragFlag_NeedSchema,
  79526. /* iArg: */ 0 },
  79527. #endif
  79528. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79529. { /* zName: */ "defer_foreign_keys",
  79530. /* ePragTyp: */ PragTyp_FLAG,
  79531. /* ePragFlag: */ 0,
  79532. /* iArg: */ SQLITE_DeferFKs },
  79533. #endif
  79534. { /* zName: */ "empty_result_callbacks",
  79535. /* ePragTyp: */ PragTyp_FLAG,
  79536. /* ePragFlag: */ 0,
  79537. /* iArg: */ SQLITE_NullCallback },
  79538. #if !defined(SQLITE_OMIT_UTF16)
  79539. { /* zName: */ "encoding",
  79540. /* ePragTyp: */ PragTyp_ENCODING,
  79541. /* ePragFlag: */ 0,
  79542. /* iArg: */ 0 },
  79543. #endif
  79544. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79545. { /* zName: */ "foreign_key_check",
  79546. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  79547. /* ePragFlag: */ PragFlag_NeedSchema,
  79548. /* iArg: */ 0 },
  79549. #endif
  79550. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  79551. { /* zName: */ "foreign_key_list",
  79552. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  79553. /* ePragFlag: */ PragFlag_NeedSchema,
  79554. /* iArg: */ 0 },
  79555. #endif
  79556. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79557. { /* zName: */ "foreign_keys",
  79558. /* ePragTyp: */ PragTyp_FLAG,
  79559. /* ePragFlag: */ 0,
  79560. /* iArg: */ SQLITE_ForeignKeys },
  79561. #endif
  79562. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79563. { /* zName: */ "freelist_count",
  79564. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79565. /* ePragFlag: */ 0,
  79566. /* iArg: */ 0 },
  79567. #endif
  79568. { /* zName: */ "full_column_names",
  79569. /* ePragTyp: */ PragTyp_FLAG,
  79570. /* ePragFlag: */ 0,
  79571. /* iArg: */ SQLITE_FullColNames },
  79572. { /* zName: */ "fullfsync",
  79573. /* ePragTyp: */ PragTyp_FLAG,
  79574. /* ePragFlag: */ 0,
  79575. /* iArg: */ SQLITE_FullFSync },
  79576. #if defined(SQLITE_HAS_CODEC)
  79577. { /* zName: */ "hexkey",
  79578. /* ePragTyp: */ PragTyp_HEXKEY,
  79579. /* ePragFlag: */ 0,
  79580. /* iArg: */ 0 },
  79581. { /* zName: */ "hexrekey",
  79582. /* ePragTyp: */ PragTyp_HEXKEY,
  79583. /* ePragFlag: */ 0,
  79584. /* iArg: */ 0 },
  79585. #endif
  79586. #if !defined(SQLITE_OMIT_CHECK)
  79587. { /* zName: */ "ignore_check_constraints",
  79588. /* ePragTyp: */ PragTyp_FLAG,
  79589. /* ePragFlag: */ 0,
  79590. /* iArg: */ SQLITE_IgnoreChecks },
  79591. #endif
  79592. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79593. { /* zName: */ "incremental_vacuum",
  79594. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  79595. /* ePragFlag: */ PragFlag_NeedSchema,
  79596. /* iArg: */ 0 },
  79597. #endif
  79598. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79599. { /* zName: */ "index_info",
  79600. /* ePragTyp: */ PragTyp_INDEX_INFO,
  79601. /* ePragFlag: */ PragFlag_NeedSchema,
  79602. /* iArg: */ 0 },
  79603. { /* zName: */ "index_list",
  79604. /* ePragTyp: */ PragTyp_INDEX_LIST,
  79605. /* ePragFlag: */ PragFlag_NeedSchema,
  79606. /* iArg: */ 0 },
  79607. #endif
  79608. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  79609. { /* zName: */ "integrity_check",
  79610. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  79611. /* ePragFlag: */ PragFlag_NeedSchema,
  79612. /* iArg: */ 0 },
  79613. #endif
  79614. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79615. { /* zName: */ "journal_mode",
  79616. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  79617. /* ePragFlag: */ PragFlag_NeedSchema,
  79618. /* iArg: */ 0 },
  79619. { /* zName: */ "journal_size_limit",
  79620. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  79621. /* ePragFlag: */ 0,
  79622. /* iArg: */ 0 },
  79623. #endif
  79624. #if defined(SQLITE_HAS_CODEC)
  79625. { /* zName: */ "key",
  79626. /* ePragTyp: */ PragTyp_KEY,
  79627. /* ePragFlag: */ 0,
  79628. /* iArg: */ 0 },
  79629. #endif
  79630. { /* zName: */ "legacy_file_format",
  79631. /* ePragTyp: */ PragTyp_FLAG,
  79632. /* ePragFlag: */ 0,
  79633. /* iArg: */ SQLITE_LegacyFileFmt },
  79634. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  79635. { /* zName: */ "lock_proxy_file",
  79636. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  79637. /* ePragFlag: */ 0,
  79638. /* iArg: */ 0 },
  79639. #endif
  79640. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  79641. { /* zName: */ "lock_status",
  79642. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  79643. /* ePragFlag: */ 0,
  79644. /* iArg: */ 0 },
  79645. #endif
  79646. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79647. { /* zName: */ "locking_mode",
  79648. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  79649. /* ePragFlag: */ 0,
  79650. /* iArg: */ 0 },
  79651. { /* zName: */ "max_page_count",
  79652. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  79653. /* ePragFlag: */ PragFlag_NeedSchema,
  79654. /* iArg: */ 0 },
  79655. { /* zName: */ "mmap_size",
  79656. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  79657. /* ePragFlag: */ 0,
  79658. /* iArg: */ 0 },
  79659. { /* zName: */ "page_count",
  79660. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  79661. /* ePragFlag: */ PragFlag_NeedSchema,
  79662. /* iArg: */ 0 },
  79663. { /* zName: */ "page_size",
  79664. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  79665. /* ePragFlag: */ 0,
  79666. /* iArg: */ 0 },
  79667. #endif
  79668. #if defined(SQLITE_DEBUG)
  79669. { /* zName: */ "parser_trace",
  79670. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  79671. /* ePragFlag: */ 0,
  79672. /* iArg: */ 0 },
  79673. #endif
  79674. { /* zName: */ "query_only",
  79675. /* ePragTyp: */ PragTyp_FLAG,
  79676. /* ePragFlag: */ 0,
  79677. /* iArg: */ SQLITE_QueryOnly },
  79678. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  79679. { /* zName: */ "quick_check",
  79680. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  79681. /* ePragFlag: */ PragFlag_NeedSchema,
  79682. /* iArg: */ 0 },
  79683. #endif
  79684. { /* zName: */ "read_uncommitted",
  79685. /* ePragTyp: */ PragTyp_FLAG,
  79686. /* ePragFlag: */ 0,
  79687. /* iArg: */ SQLITE_ReadUncommitted },
  79688. { /* zName: */ "recursive_triggers",
  79689. /* ePragTyp: */ PragTyp_FLAG,
  79690. /* ePragFlag: */ 0,
  79691. /* iArg: */ SQLITE_RecTriggers },
  79692. #if defined(SQLITE_HAS_CODEC)
  79693. { /* zName: */ "rekey",
  79694. /* ePragTyp: */ PragTyp_REKEY,
  79695. /* ePragFlag: */ 0,
  79696. /* iArg: */ 0 },
  79697. #endif
  79698. { /* zName: */ "reverse_unordered_selects",
  79699. /* ePragTyp: */ PragTyp_FLAG,
  79700. /* ePragFlag: */ 0,
  79701. /* iArg: */ SQLITE_ReverseOrder },
  79702. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79703. { /* zName: */ "schema_version",
  79704. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79705. /* ePragFlag: */ 0,
  79706. /* iArg: */ 0 },
  79707. #endif
  79708. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79709. { /* zName: */ "secure_delete",
  79710. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  79711. /* ePragFlag: */ 0,
  79712. /* iArg: */ 0 },
  79713. #endif
  79714. { /* zName: */ "short_column_names",
  79715. /* ePragTyp: */ PragTyp_FLAG,
  79716. /* ePragFlag: */ 0,
  79717. /* iArg: */ SQLITE_ShortColNames },
  79718. { /* zName: */ "shrink_memory",
  79719. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  79720. /* ePragFlag: */ 0,
  79721. /* iArg: */ 0 },
  79722. { /* zName: */ "soft_heap_limit",
  79723. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  79724. /* ePragFlag: */ 0,
  79725. /* iArg: */ 0 },
  79726. #if defined(SQLITE_DEBUG)
  79727. { /* zName: */ "sql_trace",
  79728. /* ePragTyp: */ PragTyp_FLAG,
  79729. /* ePragFlag: */ 0,
  79730. /* iArg: */ SQLITE_SqlTrace },
  79731. #endif
  79732. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79733. { /* zName: */ "stats",
  79734. /* ePragTyp: */ PragTyp_STATS,
  79735. /* ePragFlag: */ PragFlag_NeedSchema,
  79736. /* iArg: */ 0 },
  79737. #endif
  79738. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79739. { /* zName: */ "synchronous",
  79740. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  79741. /* ePragFlag: */ PragFlag_NeedSchema,
  79742. /* iArg: */ 0 },
  79743. #endif
  79744. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79745. { /* zName: */ "table_info",
  79746. /* ePragTyp: */ PragTyp_TABLE_INFO,
  79747. /* ePragFlag: */ PragFlag_NeedSchema,
  79748. /* iArg: */ 0 },
  79749. #endif
  79750. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79751. { /* zName: */ "temp_store",
  79752. /* ePragTyp: */ PragTyp_TEMP_STORE,
  79753. /* ePragFlag: */ 0,
  79754. /* iArg: */ 0 },
  79755. { /* zName: */ "temp_store_directory",
  79756. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  79757. /* ePragFlag: */ 0,
  79758. /* iArg: */ 0 },
  79759. #endif
  79760. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79761. { /* zName: */ "user_version",
  79762. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79763. /* ePragFlag: */ 0,
  79764. /* iArg: */ 0 },
  79765. #endif
  79766. #if defined(SQLITE_DEBUG)
  79767. { /* zName: */ "vdbe_addoptrace",
  79768. /* ePragTyp: */ PragTyp_FLAG,
  79769. /* ePragFlag: */ 0,
  79770. /* iArg: */ SQLITE_VdbeAddopTrace },
  79771. { /* zName: */ "vdbe_debug",
  79772. /* ePragTyp: */ PragTyp_FLAG,
  79773. /* ePragFlag: */ 0,
  79774. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  79775. { /* zName: */ "vdbe_listing",
  79776. /* ePragTyp: */ PragTyp_FLAG,
  79777. /* ePragFlag: */ 0,
  79778. /* iArg: */ SQLITE_VdbeListing },
  79779. { /* zName: */ "vdbe_trace",
  79780. /* ePragTyp: */ PragTyp_FLAG,
  79781. /* ePragFlag: */ 0,
  79782. /* iArg: */ SQLITE_VdbeTrace },
  79783. #endif
  79784. #if !defined(SQLITE_OMIT_WAL)
  79785. { /* zName: */ "wal_autocheckpoint",
  79786. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  79787. /* ePragFlag: */ 0,
  79788. /* iArg: */ 0 },
  79789. { /* zName: */ "wal_checkpoint",
  79790. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  79791. /* ePragFlag: */ PragFlag_NeedSchema,
  79792. /* iArg: */ 0 },
  79793. #endif
  79794. { /* zName: */ "writable_schema",
  79795. /* ePragTyp: */ PragTyp_FLAG,
  79796. /* ePragFlag: */ 0,
  79797. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  79798. };
  79799. /* Number of pragmas: 56 on by default, 68 total. */
  79800. /* End of the automatically generated pragma table.
  79801. ***************************************************************************/
  79802. /*
  79803. ** Interpret the given string as a safety level. Return 0 for OFF,
  79804. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  79805. ** unrecognized string argument. The FULL option is disallowed
  79806. ** if the omitFull parameter it 1.
  79807. **
  79808. ** Note that the values returned are one less that the values that
  79809. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  79810. ** to support legacy SQL code. The safety level used to be boolean
  79811. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  79812. */
  79813. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  79814. /* 123456789 123456789 */
  79815. static const char zText[] = "onoffalseyestruefull";
  79816. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  79817. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  79818. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  79819. int i, n;
  79820. if( sqlite3Isdigit(*z) ){
  79821. return (u8)sqlite3Atoi(z);
  79822. }
  79823. n = sqlite3Strlen30(z);
  79824. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  79825. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  79826. return iValue[i];
  79827. }
  79828. }
  79829. return dflt;
  79830. }
  79831. /*
  79832. ** Interpret the given string as a boolean value.
  79833. */
  79834. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  79835. return getSafetyLevel(z,1,dflt)!=0;
  79836. }
  79837. /* The sqlite3GetBoolean() function is used by other modules but the
  79838. ** remainder of this file is specific to PRAGMA processing. So omit
  79839. ** the rest of the file if PRAGMAs are omitted from the build.
  79840. */
  79841. #if !defined(SQLITE_OMIT_PRAGMA)
  79842. /*
  79843. ** Interpret the given string as a locking mode value.
  79844. */
  79845. static int getLockingMode(const char *z){
  79846. if( z ){
  79847. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  79848. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  79849. }
  79850. return PAGER_LOCKINGMODE_QUERY;
  79851. }
  79852. #ifndef SQLITE_OMIT_AUTOVACUUM
  79853. /*
  79854. ** Interpret the given string as an auto-vacuum mode value.
  79855. **
  79856. ** The following strings, "none", "full" and "incremental" are
  79857. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  79858. */
  79859. static int getAutoVacuum(const char *z){
  79860. int i;
  79861. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  79862. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  79863. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  79864. i = sqlite3Atoi(z);
  79865. return (u8)((i>=0&&i<=2)?i:0);
  79866. }
  79867. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  79868. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79869. /*
  79870. ** Interpret the given string as a temp db location. Return 1 for file
  79871. ** backed temporary databases, 2 for the Red-Black tree in memory database
  79872. ** and 0 to use the compile-time default.
  79873. */
  79874. static int getTempStore(const char *z){
  79875. if( z[0]>='0' && z[0]<='2' ){
  79876. return z[0] - '0';
  79877. }else if( sqlite3StrICmp(z, "file")==0 ){
  79878. return 1;
  79879. }else if( sqlite3StrICmp(z, "memory")==0 ){
  79880. return 2;
  79881. }else{
  79882. return 0;
  79883. }
  79884. }
  79885. #endif /* SQLITE_PAGER_PRAGMAS */
  79886. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79887. /*
  79888. ** Invalidate temp storage, either when the temp storage is changed
  79889. ** from default, or when 'file' and the temp_store_directory has changed
  79890. */
  79891. static int invalidateTempStorage(Parse *pParse){
  79892. sqlite3 *db = pParse->db;
  79893. if( db->aDb[1].pBt!=0 ){
  79894. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  79895. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  79896. "from within a transaction");
  79897. return SQLITE_ERROR;
  79898. }
  79899. sqlite3BtreeClose(db->aDb[1].pBt);
  79900. db->aDb[1].pBt = 0;
  79901. sqlite3ResetAllSchemasOfConnection(db);
  79902. }
  79903. return SQLITE_OK;
  79904. }
  79905. #endif /* SQLITE_PAGER_PRAGMAS */
  79906. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79907. /*
  79908. ** If the TEMP database is open, close it and mark the database schema
  79909. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  79910. ** or DEFAULT_TEMP_STORE pragmas.
  79911. */
  79912. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  79913. int ts = getTempStore(zStorageType);
  79914. sqlite3 *db = pParse->db;
  79915. if( db->temp_store==ts ) return SQLITE_OK;
  79916. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  79917. return SQLITE_ERROR;
  79918. }
  79919. db->temp_store = (u8)ts;
  79920. return SQLITE_OK;
  79921. }
  79922. #endif /* SQLITE_PAGER_PRAGMAS */
  79923. /*
  79924. ** Generate code to return a single integer value.
  79925. */
  79926. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  79927. Vdbe *v = sqlite3GetVdbe(pParse);
  79928. int mem = ++pParse->nMem;
  79929. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  79930. if( pI64 ){
  79931. memcpy(pI64, &value, sizeof(value));
  79932. }
  79933. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  79934. sqlite3VdbeSetNumCols(v, 1);
  79935. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  79936. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  79937. }
  79938. /*
  79939. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  79940. ** set these values for all pagers.
  79941. */
  79942. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79943. static void setAllPagerFlags(sqlite3 *db){
  79944. if( db->autoCommit ){
  79945. Db *pDb = db->aDb;
  79946. int n = db->nDb;
  79947. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  79948. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  79949. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  79950. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  79951. == PAGER_FLAGS_MASK );
  79952. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  79953. while( (n--) > 0 ){
  79954. if( pDb->pBt ){
  79955. sqlite3BtreeSetPagerFlags(pDb->pBt,
  79956. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  79957. }
  79958. pDb++;
  79959. }
  79960. }
  79961. }
  79962. #else
  79963. # define setAllPagerFlags(X) /* no-op */
  79964. #endif
  79965. /*
  79966. ** Return a human-readable name for a constraint resolution action.
  79967. */
  79968. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79969. static const char *actionName(u8 action){
  79970. const char *zName;
  79971. switch( action ){
  79972. case OE_SetNull: zName = "SET NULL"; break;
  79973. case OE_SetDflt: zName = "SET DEFAULT"; break;
  79974. case OE_Cascade: zName = "CASCADE"; break;
  79975. case OE_Restrict: zName = "RESTRICT"; break;
  79976. default: zName = "NO ACTION";
  79977. assert( action==OE_None ); break;
  79978. }
  79979. return zName;
  79980. }
  79981. #endif
  79982. /*
  79983. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  79984. ** defined in pager.h. This function returns the associated lowercase
  79985. ** journal-mode name.
  79986. */
  79987. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  79988. static char * const azModeName[] = {
  79989. "delete", "persist", "off", "truncate", "memory"
  79990. #ifndef SQLITE_OMIT_WAL
  79991. , "wal"
  79992. #endif
  79993. };
  79994. assert( PAGER_JOURNALMODE_DELETE==0 );
  79995. assert( PAGER_JOURNALMODE_PERSIST==1 );
  79996. assert( PAGER_JOURNALMODE_OFF==2 );
  79997. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  79998. assert( PAGER_JOURNALMODE_MEMORY==4 );
  79999. assert( PAGER_JOURNALMODE_WAL==5 );
  80000. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  80001. if( eMode==ArraySize(azModeName) ) return 0;
  80002. return azModeName[eMode];
  80003. }
  80004. /*
  80005. ** Process a pragma statement.
  80006. **
  80007. ** Pragmas are of this form:
  80008. **
  80009. ** PRAGMA [database.]id [= value]
  80010. **
  80011. ** The identifier might also be a string. The value is a string, and
  80012. ** identifier, or a number. If minusFlag is true, then the value is
  80013. ** a number that was preceded by a minus sign.
  80014. **
  80015. ** If the left side is "database.id" then pId1 is the database name
  80016. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  80017. ** id and pId2 is any empty string.
  80018. */
  80019. SQLITE_PRIVATE void sqlite3Pragma(
  80020. Parse *pParse,
  80021. Token *pId1, /* First part of [database.]id field */
  80022. Token *pId2, /* Second part of [database.]id field, or NULL */
  80023. Token *pValue, /* Token for <value>, or NULL */
  80024. int minusFlag /* True if a '-' sign preceded <value> */
  80025. ){
  80026. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  80027. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  80028. const char *zDb = 0; /* The database name */
  80029. Token *pId; /* Pointer to <id> token */
  80030. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  80031. int iDb; /* Database index for <database> */
  80032. int lwr, upr, mid; /* Binary search bounds */
  80033. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  80034. sqlite3 *db = pParse->db; /* The database connection */
  80035. Db *pDb; /* The specific database being pragmaed */
  80036. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  80037. if( v==0 ) return;
  80038. sqlite3VdbeRunOnlyOnce(v);
  80039. pParse->nMem = 2;
  80040. /* Interpret the [database.] part of the pragma statement. iDb is the
  80041. ** index of the database this pragma is being applied to in db.aDb[]. */
  80042. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  80043. if( iDb<0 ) return;
  80044. pDb = &db->aDb[iDb];
  80045. /* If the temp database has been explicitly named as part of the
  80046. ** pragma, make sure it is open.
  80047. */
  80048. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  80049. return;
  80050. }
  80051. zLeft = sqlite3NameFromToken(db, pId);
  80052. if( !zLeft ) return;
  80053. if( minusFlag ){
  80054. zRight = sqlite3MPrintf(db, "-%T", pValue);
  80055. }else{
  80056. zRight = sqlite3NameFromToken(db, pValue);
  80057. }
  80058. assert( pId2 );
  80059. zDb = pId2->n>0 ? pDb->zName : 0;
  80060. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  80061. goto pragma_out;
  80062. }
  80063. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  80064. ** connection. If it returns SQLITE_OK, then assume that the VFS
  80065. ** handled the pragma and generate a no-op prepared statement.
  80066. */
  80067. aFcntl[0] = 0;
  80068. aFcntl[1] = zLeft;
  80069. aFcntl[2] = zRight;
  80070. aFcntl[3] = 0;
  80071. db->busyHandler.nBusy = 0;
  80072. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  80073. if( rc==SQLITE_OK ){
  80074. if( aFcntl[0] ){
  80075. int mem = ++pParse->nMem;
  80076. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  80077. sqlite3VdbeSetNumCols(v, 1);
  80078. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  80079. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  80080. sqlite3_free(aFcntl[0]);
  80081. }
  80082. goto pragma_out;
  80083. }
  80084. if( rc!=SQLITE_NOTFOUND ){
  80085. if( aFcntl[0] ){
  80086. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  80087. sqlite3_free(aFcntl[0]);
  80088. }
  80089. pParse->nErr++;
  80090. pParse->rc = rc;
  80091. goto pragma_out;
  80092. }
  80093. /* Locate the pragma in the lookup table */
  80094. lwr = 0;
  80095. upr = ArraySize(aPragmaNames)-1;
  80096. while( lwr<=upr ){
  80097. mid = (lwr+upr)/2;
  80098. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  80099. if( rc==0 ) break;
  80100. if( rc<0 ){
  80101. upr = mid - 1;
  80102. }else{
  80103. lwr = mid + 1;
  80104. }
  80105. }
  80106. if( lwr>upr ) goto pragma_out;
  80107. /* Make sure the database schema is loaded if the pragma requires that */
  80108. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  80109. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  80110. }
  80111. /* Jump to the appropriate pragma handler */
  80112. switch( aPragmaNames[mid].ePragTyp ){
  80113. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  80114. /*
  80115. ** PRAGMA [database.]default_cache_size
  80116. ** PRAGMA [database.]default_cache_size=N
  80117. **
  80118. ** The first form reports the current persistent setting for the
  80119. ** page cache size. The value returned is the maximum number of
  80120. ** pages in the page cache. The second form sets both the current
  80121. ** page cache size value and the persistent page cache size value
  80122. ** stored in the database file.
  80123. **
  80124. ** Older versions of SQLite would set the default cache size to a
  80125. ** negative number to indicate synchronous=OFF. These days, synchronous
  80126. ** is always on by default regardless of the sign of the default cache
  80127. ** size. But continue to take the absolute value of the default cache
  80128. ** size of historical compatibility.
  80129. */
  80130. case PragTyp_DEFAULT_CACHE_SIZE: {
  80131. static const VdbeOpList getCacheSize[] = {
  80132. { OP_Transaction, 0, 0, 0}, /* 0 */
  80133. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  80134. { OP_IfPos, 1, 8, 0},
  80135. { OP_Integer, 0, 2, 0},
  80136. { OP_Subtract, 1, 2, 1},
  80137. { OP_IfPos, 1, 8, 0},
  80138. { OP_Integer, 0, 1, 0}, /* 6 */
  80139. { OP_Noop, 0, 0, 0},
  80140. { OP_ResultRow, 1, 1, 0},
  80141. };
  80142. int addr;
  80143. sqlite3VdbeUsesBtree(v, iDb);
  80144. if( !zRight ){
  80145. sqlite3VdbeSetNumCols(v, 1);
  80146. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  80147. pParse->nMem += 2;
  80148. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  80149. sqlite3VdbeChangeP1(v, addr, iDb);
  80150. sqlite3VdbeChangeP1(v, addr+1, iDb);
  80151. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  80152. }else{
  80153. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  80154. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80155. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  80156. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  80157. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80158. pDb->pSchema->cache_size = size;
  80159. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  80160. }
  80161. break;
  80162. }
  80163. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  80164. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  80165. /*
  80166. ** PRAGMA [database.]page_size
  80167. ** PRAGMA [database.]page_size=N
  80168. **
  80169. ** The first form reports the current setting for the
  80170. ** database page size in bytes. The second form sets the
  80171. ** database page size value. The value can only be set if
  80172. ** the database has not yet been created.
  80173. */
  80174. case PragTyp_PAGE_SIZE: {
  80175. Btree *pBt = pDb->pBt;
  80176. assert( pBt!=0 );
  80177. if( !zRight ){
  80178. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  80179. returnSingleInt(pParse, "page_size", size);
  80180. }else{
  80181. /* Malloc may fail when setting the page-size, as there is an internal
  80182. ** buffer that the pager module resizes using sqlite3_realloc().
  80183. */
  80184. db->nextPagesize = sqlite3Atoi(zRight);
  80185. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  80186. db->mallocFailed = 1;
  80187. }
  80188. }
  80189. break;
  80190. }
  80191. /*
  80192. ** PRAGMA [database.]secure_delete
  80193. ** PRAGMA [database.]secure_delete=ON/OFF
  80194. **
  80195. ** The first form reports the current setting for the
  80196. ** secure_delete flag. The second form changes the secure_delete
  80197. ** flag setting and reports thenew value.
  80198. */
  80199. case PragTyp_SECURE_DELETE: {
  80200. Btree *pBt = pDb->pBt;
  80201. int b = -1;
  80202. assert( pBt!=0 );
  80203. if( zRight ){
  80204. b = sqlite3GetBoolean(zRight, 0);
  80205. }
  80206. if( pId2->n==0 && b>=0 ){
  80207. int ii;
  80208. for(ii=0; ii<db->nDb; ii++){
  80209. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  80210. }
  80211. }
  80212. b = sqlite3BtreeSecureDelete(pBt, b);
  80213. returnSingleInt(pParse, "secure_delete", b);
  80214. break;
  80215. }
  80216. /*
  80217. ** PRAGMA [database.]max_page_count
  80218. ** PRAGMA [database.]max_page_count=N
  80219. **
  80220. ** The first form reports the current setting for the
  80221. ** maximum number of pages in the database file. The
  80222. ** second form attempts to change this setting. Both
  80223. ** forms return the current setting.
  80224. **
  80225. ** The absolute value of N is used. This is undocumented and might
  80226. ** change. The only purpose is to provide an easy way to test
  80227. ** the sqlite3AbsInt32() function.
  80228. **
  80229. ** PRAGMA [database.]page_count
  80230. **
  80231. ** Return the number of pages in the specified database.
  80232. */
  80233. case PragTyp_PAGE_COUNT: {
  80234. int iReg;
  80235. sqlite3CodeVerifySchema(pParse, iDb);
  80236. iReg = ++pParse->nMem;
  80237. if( sqlite3Tolower(zLeft[0])=='p' ){
  80238. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  80239. }else{
  80240. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  80241. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  80242. }
  80243. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  80244. sqlite3VdbeSetNumCols(v, 1);
  80245. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  80246. break;
  80247. }
  80248. /*
  80249. ** PRAGMA [database.]locking_mode
  80250. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  80251. */
  80252. case PragTyp_LOCKING_MODE: {
  80253. const char *zRet = "normal";
  80254. int eMode = getLockingMode(zRight);
  80255. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  80256. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  80257. ** the current default locking mode (which may be different to
  80258. ** the locking-mode of the main database).
  80259. */
  80260. eMode = db->dfltLockMode;
  80261. }else{
  80262. Pager *pPager;
  80263. if( pId2->n==0 ){
  80264. /* This indicates that no database name was specified as part
  80265. ** of the PRAGMA command. In this case the locking-mode must be
  80266. ** set on all attached databases, as well as the main db file.
  80267. **
  80268. ** Also, the sqlite3.dfltLockMode variable is set so that
  80269. ** any subsequently attached databases also use the specified
  80270. ** locking mode.
  80271. */
  80272. int ii;
  80273. assert(pDb==&db->aDb[0]);
  80274. for(ii=2; ii<db->nDb; ii++){
  80275. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  80276. sqlite3PagerLockingMode(pPager, eMode);
  80277. }
  80278. db->dfltLockMode = (u8)eMode;
  80279. }
  80280. pPager = sqlite3BtreePager(pDb->pBt);
  80281. eMode = sqlite3PagerLockingMode(pPager, eMode);
  80282. }
  80283. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  80284. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  80285. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  80286. zRet = "exclusive";
  80287. }
  80288. sqlite3VdbeSetNumCols(v, 1);
  80289. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  80290. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  80291. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80292. break;
  80293. }
  80294. /*
  80295. ** PRAGMA [database.]journal_mode
  80296. ** PRAGMA [database.]journal_mode =
  80297. ** (delete|persist|off|truncate|memory|wal|off)
  80298. */
  80299. case PragTyp_JOURNAL_MODE: {
  80300. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  80301. int ii; /* Loop counter */
  80302. sqlite3VdbeSetNumCols(v, 1);
  80303. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  80304. if( zRight==0 ){
  80305. /* If there is no "=MODE" part of the pragma, do a query for the
  80306. ** current mode */
  80307. eMode = PAGER_JOURNALMODE_QUERY;
  80308. }else{
  80309. const char *zMode;
  80310. int n = sqlite3Strlen30(zRight);
  80311. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  80312. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  80313. }
  80314. if( !zMode ){
  80315. /* If the "=MODE" part does not match any known journal mode,
  80316. ** then do a query */
  80317. eMode = PAGER_JOURNALMODE_QUERY;
  80318. }
  80319. }
  80320. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  80321. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  80322. iDb = 0;
  80323. pId2->n = 1;
  80324. }
  80325. for(ii=db->nDb-1; ii>=0; ii--){
  80326. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  80327. sqlite3VdbeUsesBtree(v, ii);
  80328. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  80329. }
  80330. }
  80331. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80332. break;
  80333. }
  80334. /*
  80335. ** PRAGMA [database.]journal_size_limit
  80336. ** PRAGMA [database.]journal_size_limit=N
  80337. **
  80338. ** Get or set the size limit on rollback journal files.
  80339. */
  80340. case PragTyp_JOURNAL_SIZE_LIMIT: {
  80341. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80342. i64 iLimit = -2;
  80343. if( zRight ){
  80344. sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
  80345. if( iLimit<-1 ) iLimit = -1;
  80346. }
  80347. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  80348. returnSingleInt(pParse, "journal_size_limit", iLimit);
  80349. break;
  80350. }
  80351. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  80352. /*
  80353. ** PRAGMA [database.]auto_vacuum
  80354. ** PRAGMA [database.]auto_vacuum=N
  80355. **
  80356. ** Get or set the value of the database 'auto-vacuum' parameter.
  80357. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  80358. */
  80359. #ifndef SQLITE_OMIT_AUTOVACUUM
  80360. case PragTyp_AUTO_VACUUM: {
  80361. Btree *pBt = pDb->pBt;
  80362. assert( pBt!=0 );
  80363. if( !zRight ){
  80364. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  80365. }else{
  80366. int eAuto = getAutoVacuum(zRight);
  80367. assert( eAuto>=0 && eAuto<=2 );
  80368. db->nextAutovac = (u8)eAuto;
  80369. /* Call SetAutoVacuum() to set initialize the internal auto and
  80370. ** incr-vacuum flags. This is required in case this connection
  80371. ** creates the database file. It is important that it is created
  80372. ** as an auto-vacuum capable db.
  80373. */
  80374. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  80375. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  80376. /* When setting the auto_vacuum mode to either "full" or
  80377. ** "incremental", write the value of meta[6] in the database
  80378. ** file. Before writing to meta[6], check that meta[3] indicates
  80379. ** that this really is an auto-vacuum capable database.
  80380. */
  80381. static const VdbeOpList setMeta6[] = {
  80382. { OP_Transaction, 0, 1, 0}, /* 0 */
  80383. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  80384. { OP_If, 1, 0, 0}, /* 2 */
  80385. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  80386. { OP_Integer, 0, 1, 0}, /* 4 */
  80387. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  80388. };
  80389. int iAddr;
  80390. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  80391. sqlite3VdbeChangeP1(v, iAddr, iDb);
  80392. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  80393. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  80394. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  80395. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  80396. sqlite3VdbeUsesBtree(v, iDb);
  80397. }
  80398. }
  80399. break;
  80400. }
  80401. #endif
  80402. /*
  80403. ** PRAGMA [database.]incremental_vacuum(N)
  80404. **
  80405. ** Do N steps of incremental vacuuming on a database.
  80406. */
  80407. #ifndef SQLITE_OMIT_AUTOVACUUM
  80408. case PragTyp_INCREMENTAL_VACUUM: {
  80409. int iLimit, addr;
  80410. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  80411. iLimit = 0x7fffffff;
  80412. }
  80413. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80414. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  80415. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  80416. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  80417. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  80418. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  80419. sqlite3VdbeJumpHere(v, addr);
  80420. break;
  80421. }
  80422. #endif
  80423. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80424. /*
  80425. ** PRAGMA [database.]cache_size
  80426. ** PRAGMA [database.]cache_size=N
  80427. **
  80428. ** The first form reports the current local setting for the
  80429. ** page cache size. The second form sets the local
  80430. ** page cache size value. If N is positive then that is the
  80431. ** number of pages in the cache. If N is negative, then the
  80432. ** number of pages is adjusted so that the cache uses -N kibibytes
  80433. ** of memory.
  80434. */
  80435. case PragTyp_CACHE_SIZE: {
  80436. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80437. if( !zRight ){
  80438. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  80439. }else{
  80440. int size = sqlite3Atoi(zRight);
  80441. pDb->pSchema->cache_size = size;
  80442. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  80443. }
  80444. break;
  80445. }
  80446. /*
  80447. ** PRAGMA [database.]mmap_size(N)
  80448. **
  80449. ** Used to set mapping size limit. The mapping size limit is
  80450. ** used to limit the aggregate size of all memory mapped regions of the
  80451. ** database file. If this parameter is set to zero, then memory mapping
  80452. ** is not used at all. If N is negative, then the default memory map
  80453. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  80454. ** The parameter N is measured in bytes.
  80455. **
  80456. ** This value is advisory. The underlying VFS is free to memory map
  80457. ** as little or as much as it wants. Except, if N is set to 0 then the
  80458. ** upper layers will never invoke the xFetch interfaces to the VFS.
  80459. */
  80460. case PragTyp_MMAP_SIZE: {
  80461. sqlite3_int64 sz;
  80462. #if SQLITE_MAX_MMAP_SIZE>0
  80463. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80464. if( zRight ){
  80465. int ii;
  80466. sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
  80467. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  80468. if( pId2->n==0 ) db->szMmap = sz;
  80469. for(ii=db->nDb-1; ii>=0; ii--){
  80470. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  80471. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  80472. }
  80473. }
  80474. }
  80475. sz = -1;
  80476. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  80477. #else
  80478. sz = 0;
  80479. rc = SQLITE_OK;
  80480. #endif
  80481. if( rc==SQLITE_OK ){
  80482. returnSingleInt(pParse, "mmap_size", sz);
  80483. }else if( rc!=SQLITE_NOTFOUND ){
  80484. pParse->nErr++;
  80485. pParse->rc = rc;
  80486. }
  80487. break;
  80488. }
  80489. /*
  80490. ** PRAGMA temp_store
  80491. ** PRAGMA temp_store = "default"|"memory"|"file"
  80492. **
  80493. ** Return or set the local value of the temp_store flag. Changing
  80494. ** the local value does not make changes to the disk file and the default
  80495. ** value will be restored the next time the database is opened.
  80496. **
  80497. ** Note that it is possible for the library compile-time options to
  80498. ** override this setting
  80499. */
  80500. case PragTyp_TEMP_STORE: {
  80501. if( !zRight ){
  80502. returnSingleInt(pParse, "temp_store", db->temp_store);
  80503. }else{
  80504. changeTempStorage(pParse, zRight);
  80505. }
  80506. break;
  80507. }
  80508. /*
  80509. ** PRAGMA temp_store_directory
  80510. ** PRAGMA temp_store_directory = ""|"directory_name"
  80511. **
  80512. ** Return or set the local value of the temp_store_directory flag. Changing
  80513. ** the value sets a specific directory to be used for temporary files.
  80514. ** Setting to a null string reverts to the default temporary directory search.
  80515. ** If temporary directory is changed, then invalidateTempStorage.
  80516. **
  80517. */
  80518. case PragTyp_TEMP_STORE_DIRECTORY: {
  80519. if( !zRight ){
  80520. if( sqlite3_temp_directory ){
  80521. sqlite3VdbeSetNumCols(v, 1);
  80522. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80523. "temp_store_directory", SQLITE_STATIC);
  80524. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  80525. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80526. }
  80527. }else{
  80528. #ifndef SQLITE_OMIT_WSD
  80529. if( zRight[0] ){
  80530. int res;
  80531. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  80532. if( rc!=SQLITE_OK || res==0 ){
  80533. sqlite3ErrorMsg(pParse, "not a writable directory");
  80534. goto pragma_out;
  80535. }
  80536. }
  80537. if( SQLITE_TEMP_STORE==0
  80538. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  80539. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  80540. ){
  80541. invalidateTempStorage(pParse);
  80542. }
  80543. sqlite3_free(sqlite3_temp_directory);
  80544. if( zRight[0] ){
  80545. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  80546. }else{
  80547. sqlite3_temp_directory = 0;
  80548. }
  80549. #endif /* SQLITE_OMIT_WSD */
  80550. }
  80551. break;
  80552. }
  80553. #if SQLITE_OS_WIN
  80554. /*
  80555. ** PRAGMA data_store_directory
  80556. ** PRAGMA data_store_directory = ""|"directory_name"
  80557. **
  80558. ** Return or set the local value of the data_store_directory flag. Changing
  80559. ** the value sets a specific directory to be used for database files that
  80560. ** were specified with a relative pathname. Setting to a null string reverts
  80561. ** to the default database directory, which for database files specified with
  80562. ** a relative path will probably be based on the current directory for the
  80563. ** process. Database file specified with an absolute path are not impacted
  80564. ** by this setting, regardless of its value.
  80565. **
  80566. */
  80567. case PragTyp_DATA_STORE_DIRECTORY: {
  80568. if( !zRight ){
  80569. if( sqlite3_data_directory ){
  80570. sqlite3VdbeSetNumCols(v, 1);
  80571. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80572. "data_store_directory", SQLITE_STATIC);
  80573. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  80574. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80575. }
  80576. }else{
  80577. #ifndef SQLITE_OMIT_WSD
  80578. if( zRight[0] ){
  80579. int res;
  80580. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  80581. if( rc!=SQLITE_OK || res==0 ){
  80582. sqlite3ErrorMsg(pParse, "not a writable directory");
  80583. goto pragma_out;
  80584. }
  80585. }
  80586. sqlite3_free(sqlite3_data_directory);
  80587. if( zRight[0] ){
  80588. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  80589. }else{
  80590. sqlite3_data_directory = 0;
  80591. }
  80592. #endif /* SQLITE_OMIT_WSD */
  80593. }
  80594. break;
  80595. }
  80596. #endif
  80597. #if SQLITE_ENABLE_LOCKING_STYLE
  80598. /*
  80599. ** PRAGMA [database.]lock_proxy_file
  80600. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  80601. **
  80602. ** Return or set the value of the lock_proxy_file flag. Changing
  80603. ** the value sets a specific file to be used for database access locks.
  80604. **
  80605. */
  80606. case PragTyp_LOCK_PROXY_FILE: {
  80607. if( !zRight ){
  80608. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80609. char *proxy_file_path = NULL;
  80610. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  80611. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  80612. &proxy_file_path);
  80613. if( proxy_file_path ){
  80614. sqlite3VdbeSetNumCols(v, 1);
  80615. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80616. "lock_proxy_file", SQLITE_STATIC);
  80617. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  80618. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80619. }
  80620. }else{
  80621. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80622. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  80623. int res;
  80624. if( zRight[0] ){
  80625. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  80626. zRight);
  80627. } else {
  80628. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  80629. NULL);
  80630. }
  80631. if( res!=SQLITE_OK ){
  80632. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  80633. goto pragma_out;
  80634. }
  80635. }
  80636. break;
  80637. }
  80638. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  80639. /*
  80640. ** PRAGMA [database.]synchronous
  80641. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  80642. **
  80643. ** Return or set the local value of the synchronous flag. Changing
  80644. ** the local value does not make changes to the disk file and the
  80645. ** default value will be restored the next time the database is
  80646. ** opened.
  80647. */
  80648. case PragTyp_SYNCHRONOUS: {
  80649. if( !zRight ){
  80650. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  80651. }else{
  80652. if( !db->autoCommit ){
  80653. sqlite3ErrorMsg(pParse,
  80654. "Safety level may not be changed inside a transaction");
  80655. }else{
  80656. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  80657. setAllPagerFlags(db);
  80658. }
  80659. }
  80660. break;
  80661. }
  80662. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  80663. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  80664. case PragTyp_FLAG: {
  80665. if( zRight==0 ){
  80666. returnSingleInt(pParse, aPragmaNames[mid].zName,
  80667. (db->flags & aPragmaNames[mid].iArg)!=0 );
  80668. }else{
  80669. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  80670. if( db->autoCommit==0 ){
  80671. /* Foreign key support may not be enabled or disabled while not
  80672. ** in auto-commit mode. */
  80673. mask &= ~(SQLITE_ForeignKeys);
  80674. }
  80675. if( sqlite3GetBoolean(zRight, 0) ){
  80676. db->flags |= mask;
  80677. }else{
  80678. db->flags &= ~mask;
  80679. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  80680. }
  80681. /* Many of the flag-pragmas modify the code generated by the SQL
  80682. ** compiler (eg. count_changes). So add an opcode to expire all
  80683. ** compiled SQL statements after modifying a pragma value.
  80684. */
  80685. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  80686. setAllPagerFlags(db);
  80687. }
  80688. break;
  80689. }
  80690. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  80691. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  80692. /*
  80693. ** PRAGMA table_info(<table>)
  80694. **
  80695. ** Return a single row for each column of the named table. The columns of
  80696. ** the returned data set are:
  80697. **
  80698. ** cid: Column id (numbered from left to right, starting at 0)
  80699. ** name: Column name
  80700. ** type: Column declaration type.
  80701. ** notnull: True if 'NOT NULL' is part of column declaration
  80702. ** dflt_value: The default value for the column, if any.
  80703. */
  80704. case PragTyp_TABLE_INFO: if( zRight ){
  80705. Table *pTab;
  80706. pTab = sqlite3FindTable(db, zRight, zDb);
  80707. if( pTab ){
  80708. int i, k;
  80709. int nHidden = 0;
  80710. Column *pCol;
  80711. Index *pPk;
  80712. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  80713. sqlite3VdbeSetNumCols(v, 6);
  80714. pParse->nMem = 6;
  80715. sqlite3CodeVerifySchema(pParse, iDb);
  80716. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  80717. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80718. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  80719. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  80720. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  80721. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  80722. sqlite3ViewGetColumnNames(pParse, pTab);
  80723. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  80724. if( IsHiddenColumn(pCol) ){
  80725. nHidden++;
  80726. continue;
  80727. }
  80728. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  80729. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  80730. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  80731. pCol->zType ? pCol->zType : "", 0);
  80732. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  80733. if( pCol->zDflt ){
  80734. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  80735. }else{
  80736. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  80737. }
  80738. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  80739. k = 0;
  80740. }else if( pPk==0 ){
  80741. k = 1;
  80742. }else{
  80743. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  80744. }
  80745. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  80746. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  80747. }
  80748. }
  80749. }
  80750. break;
  80751. case PragTyp_STATS: {
  80752. Index *pIdx;
  80753. HashElem *i;
  80754. v = sqlite3GetVdbe(pParse);
  80755. sqlite3VdbeSetNumCols(v, 4);
  80756. pParse->nMem = 4;
  80757. sqlite3CodeVerifySchema(pParse, iDb);
  80758. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  80759. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  80760. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  80761. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  80762. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  80763. Table *pTab = sqliteHashData(i);
  80764. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  80765. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  80766. sqlite3VdbeAddOp2(v, OP_Integer,
  80767. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  80768. sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
  80769. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  80770. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80771. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  80772. sqlite3VdbeAddOp2(v, OP_Integer,
  80773. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  80774. sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
  80775. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  80776. }
  80777. }
  80778. }
  80779. break;
  80780. case PragTyp_INDEX_INFO: if( zRight ){
  80781. Index *pIdx;
  80782. Table *pTab;
  80783. pIdx = sqlite3FindIndex(db, zRight, zDb);
  80784. if( pIdx ){
  80785. int i;
  80786. pTab = pIdx->pTable;
  80787. sqlite3VdbeSetNumCols(v, 3);
  80788. pParse->nMem = 3;
  80789. sqlite3CodeVerifySchema(pParse, iDb);
  80790. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  80791. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  80792. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  80793. for(i=0; i<pIdx->nColumn; i++){
  80794. int cnum = pIdx->aiColumn[i];
  80795. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80796. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  80797. assert( pTab->nCol>cnum );
  80798. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  80799. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80800. }
  80801. }
  80802. }
  80803. break;
  80804. case PragTyp_INDEX_LIST: if( zRight ){
  80805. Index *pIdx;
  80806. Table *pTab;
  80807. int i;
  80808. pTab = sqlite3FindTable(db, zRight, zDb);
  80809. if( pTab ){
  80810. v = sqlite3GetVdbe(pParse);
  80811. sqlite3VdbeSetNumCols(v, 3);
  80812. pParse->nMem = 3;
  80813. sqlite3CodeVerifySchema(pParse, iDb);
  80814. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80815. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80816. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  80817. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  80818. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80819. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  80820. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  80821. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80822. }
  80823. }
  80824. }
  80825. break;
  80826. case PragTyp_DATABASE_LIST: {
  80827. int i;
  80828. sqlite3VdbeSetNumCols(v, 3);
  80829. pParse->nMem = 3;
  80830. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80831. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80832. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  80833. for(i=0; i<db->nDb; i++){
  80834. if( db->aDb[i].pBt==0 ) continue;
  80835. assert( db->aDb[i].zName!=0 );
  80836. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80837. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  80838. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  80839. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  80840. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80841. }
  80842. }
  80843. break;
  80844. case PragTyp_COLLATION_LIST: {
  80845. int i = 0;
  80846. HashElem *p;
  80847. sqlite3VdbeSetNumCols(v, 2);
  80848. pParse->nMem = 2;
  80849. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80850. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80851. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  80852. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  80853. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  80854. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  80855. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  80856. }
  80857. }
  80858. break;
  80859. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  80860. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80861. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  80862. FKey *pFK;
  80863. Table *pTab;
  80864. pTab = sqlite3FindTable(db, zRight, zDb);
  80865. if( pTab ){
  80866. v = sqlite3GetVdbe(pParse);
  80867. pFK = pTab->pFKey;
  80868. if( pFK ){
  80869. int i = 0;
  80870. sqlite3VdbeSetNumCols(v, 8);
  80871. pParse->nMem = 8;
  80872. sqlite3CodeVerifySchema(pParse, iDb);
  80873. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  80874. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  80875. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  80876. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  80877. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  80878. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  80879. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  80880. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  80881. while(pFK){
  80882. int j;
  80883. for(j=0; j<pFK->nCol; j++){
  80884. char *zCol = pFK->aCol[j].zCol;
  80885. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  80886. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  80887. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80888. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  80889. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  80890. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  80891. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  80892. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  80893. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  80894. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  80895. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  80896. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  80897. }
  80898. ++i;
  80899. pFK = pFK->pNextFrom;
  80900. }
  80901. }
  80902. }
  80903. }
  80904. break;
  80905. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  80906. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80907. #ifndef SQLITE_OMIT_TRIGGER
  80908. case PragTyp_FOREIGN_KEY_CHECK: {
  80909. FKey *pFK; /* A foreign key constraint */
  80910. Table *pTab; /* Child table contain "REFERENCES" keyword */
  80911. Table *pParent; /* Parent table that child points to */
  80912. Index *pIdx; /* Index in the parent table */
  80913. int i; /* Loop counter: Foreign key number for pTab */
  80914. int j; /* Loop counter: Field of the foreign key */
  80915. HashElem *k; /* Loop counter: Next table in schema */
  80916. int x; /* result variable */
  80917. int regResult; /* 3 registers to hold a result row */
  80918. int regKey; /* Register to hold key for checking the FK */
  80919. int regRow; /* Registers to hold a row from pTab */
  80920. int addrTop; /* Top of a loop checking foreign keys */
  80921. int addrOk; /* Jump here if the key is OK */
  80922. int *aiCols; /* child to parent column mapping */
  80923. regResult = pParse->nMem+1;
  80924. pParse->nMem += 4;
  80925. regKey = ++pParse->nMem;
  80926. regRow = ++pParse->nMem;
  80927. v = sqlite3GetVdbe(pParse);
  80928. sqlite3VdbeSetNumCols(v, 4);
  80929. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  80930. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  80931. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  80932. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  80933. sqlite3CodeVerifySchema(pParse, iDb);
  80934. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  80935. while( k ){
  80936. if( zRight ){
  80937. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  80938. k = 0;
  80939. }else{
  80940. pTab = (Table*)sqliteHashData(k);
  80941. k = sqliteHashNext(k);
  80942. }
  80943. if( pTab==0 || pTab->pFKey==0 ) continue;
  80944. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  80945. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  80946. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  80947. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  80948. P4_TRANSIENT);
  80949. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  80950. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  80951. if( pParent==0 ) continue;
  80952. pIdx = 0;
  80953. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  80954. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  80955. if( x==0 ){
  80956. if( pIdx==0 ){
  80957. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  80958. }else{
  80959. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  80960. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  80961. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  80962. }
  80963. }else{
  80964. k = 0;
  80965. break;
  80966. }
  80967. }
  80968. assert( pParse->nErr>0 || pFK==0 );
  80969. if( pFK ) break;
  80970. if( pParse->nTab<i ) pParse->nTab = i;
  80971. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  80972. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  80973. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  80974. pIdx = 0;
  80975. aiCols = 0;
  80976. if( pParent ){
  80977. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  80978. assert( x==0 );
  80979. }
  80980. addrOk = sqlite3VdbeMakeLabel(v);
  80981. if( pParent && pIdx==0 ){
  80982. int iKey = pFK->aCol[0].iFrom;
  80983. assert( iKey>=0 && iKey<pTab->nCol );
  80984. if( iKey!=pTab->iPKey ){
  80985. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  80986. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  80987. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  80988. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  80989. sqlite3VdbeCurrentAddr(v)+3);
  80990. }else{
  80991. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  80992. }
  80993. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  80994. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  80995. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  80996. }else{
  80997. for(j=0; j<pFK->nCol; j++){
  80998. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  80999. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  81000. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  81001. }
  81002. if( pParent ){
  81003. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  81004. sqlite3VdbeChangeP4(v, -1,
  81005. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  81006. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  81007. }
  81008. }
  81009. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  81010. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  81011. pFK->zTo, P4_TRANSIENT);
  81012. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  81013. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  81014. sqlite3VdbeResolveLabel(v, addrOk);
  81015. sqlite3DbFree(db, aiCols);
  81016. }
  81017. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  81018. sqlite3VdbeJumpHere(v, addrTop);
  81019. }
  81020. }
  81021. break;
  81022. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  81023. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  81024. #ifndef NDEBUG
  81025. case PragTyp_PARSER_TRACE: {
  81026. if( zRight ){
  81027. if( sqlite3GetBoolean(zRight, 0) ){
  81028. sqlite3ParserTrace(stderr, "parser: ");
  81029. }else{
  81030. sqlite3ParserTrace(0, 0);
  81031. }
  81032. }
  81033. }
  81034. break;
  81035. #endif
  81036. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  81037. ** used will be case sensitive or not depending on the RHS.
  81038. */
  81039. case PragTyp_CASE_SENSITIVE_LIKE: {
  81040. if( zRight ){
  81041. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  81042. }
  81043. }
  81044. break;
  81045. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  81046. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  81047. #endif
  81048. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  81049. /* Pragma "quick_check" is reduced version of
  81050. ** integrity_check designed to detect most database corruption
  81051. ** without most of the overhead of a full integrity-check.
  81052. */
  81053. case PragTyp_INTEGRITY_CHECK: {
  81054. int i, j, addr, mxErr;
  81055. /* Code that appears at the end of the integrity check. If no error
  81056. ** messages have been generated, output OK. Otherwise output the
  81057. ** error message
  81058. */
  81059. static const VdbeOpList endCode[] = {
  81060. { OP_AddImm, 1, 0, 0}, /* 0 */
  81061. { OP_IfNeg, 1, 0, 0}, /* 1 */
  81062. { OP_String8, 0, 3, 0}, /* 2 */
  81063. { OP_ResultRow, 3, 1, 0},
  81064. };
  81065. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  81066. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  81067. ** then iDb is set to the index of the database identified by <db>.
  81068. ** In this case, the integrity of database iDb only is verified by
  81069. ** the VDBE created below.
  81070. **
  81071. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  81072. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  81073. ** to -1 here, to indicate that the VDBE should verify the integrity
  81074. ** of all attached databases. */
  81075. assert( iDb>=0 );
  81076. assert( iDb==0 || pId2->z );
  81077. if( pId2->z==0 ) iDb = -1;
  81078. /* Initialize the VDBE program */
  81079. pParse->nMem = 6;
  81080. sqlite3VdbeSetNumCols(v, 1);
  81081. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  81082. /* Set the maximum error count */
  81083. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  81084. if( zRight ){
  81085. sqlite3GetInt32(zRight, &mxErr);
  81086. if( mxErr<=0 ){
  81087. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  81088. }
  81089. }
  81090. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  81091. /* Do an integrity check on each database file */
  81092. for(i=0; i<db->nDb; i++){
  81093. HashElem *x;
  81094. Hash *pTbls;
  81095. int cnt = 0;
  81096. if( OMIT_TEMPDB && i==1 ) continue;
  81097. if( iDb>=0 && i!=iDb ) continue;
  81098. sqlite3CodeVerifySchema(pParse, i);
  81099. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  81100. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81101. sqlite3VdbeJumpHere(v, addr);
  81102. /* Do an integrity check of the B-Tree
  81103. **
  81104. ** Begin by filling registers 2, 3, ... with the root pages numbers
  81105. ** for all tables and indices in the database.
  81106. */
  81107. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  81108. pTbls = &db->aDb[i].pSchema->tblHash;
  81109. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  81110. Table *pTab = sqliteHashData(x);
  81111. Index *pIdx;
  81112. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  81113. cnt++;
  81114. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81115. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  81116. cnt++;
  81117. }
  81118. }
  81119. /* Make sure sufficient number of registers have been allocated */
  81120. pParse->nMem = MAX( pParse->nMem, cnt+7 );
  81121. /* Do the b-tree integrity checks */
  81122. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  81123. sqlite3VdbeChangeP5(v, (u8)i);
  81124. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  81125. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  81126. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  81127. P4_DYNAMIC);
  81128. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  81129. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  81130. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  81131. sqlite3VdbeJumpHere(v, addr);
  81132. /* Make sure all the indices are constructed correctly.
  81133. */
  81134. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  81135. Table *pTab = sqliteHashData(x);
  81136. Index *pIdx;
  81137. int loopTop;
  81138. if( pTab->pIndex==0 ) continue;
  81139. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  81140. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81141. sqlite3VdbeJumpHere(v, addr);
  81142. sqlite3ExprCacheClear(pParse);
  81143. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  81144. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81145. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
  81146. }
  81147. pParse->nMem = MAX(pParse->nMem, 7+j);
  81148. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  81149. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81150. int jmp2, jmp3;
  81151. int r1;
  81152. static const VdbeOpList idxErr[] = {
  81153. { OP_AddImm, 1, -1, 0},
  81154. { OP_String8, 0, 3, 0}, /* 1 */
  81155. { OP_Rowid, 1, 4, 0},
  81156. { OP_String8, 0, 5, 0}, /* 3 */
  81157. { OP_String8, 0, 6, 0}, /* 4 */
  81158. { OP_Concat, 4, 3, 3},
  81159. { OP_Concat, 5, 3, 3},
  81160. { OP_Concat, 6, 3, 3},
  81161. { OP_ResultRow, 3, 1, 0},
  81162. { OP_IfPos, 1, 0, 0}, /* 9 */
  81163. { OP_Halt, 0, 0, 0},
  81164. };
  81165. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
  81166. sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
  81167. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  81168. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  81169. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  81170. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  81171. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  81172. sqlite3VdbeJumpHere(v, addr+9);
  81173. sqlite3VdbeJumpHere(v, jmp2);
  81174. sqlite3VdbeResolveLabel(v, jmp3);
  81175. }
  81176. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
  81177. sqlite3VdbeJumpHere(v, loopTop-1);
  81178. #ifndef SQLITE_OMIT_BTREECOUNT
  81179. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  81180. "wrong # of entries in index ", P4_STATIC);
  81181. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81182. addr = sqlite3VdbeCurrentAddr(v);
  81183. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  81184. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81185. sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
  81186. sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
  81187. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  81188. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  81189. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  81190. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  81191. }
  81192. #endif /* SQLITE_OMIT_BTREECOUNT */
  81193. }
  81194. }
  81195. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  81196. sqlite3VdbeChangeP2(v, addr, -mxErr);
  81197. sqlite3VdbeJumpHere(v, addr+1);
  81198. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  81199. }
  81200. break;
  81201. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  81202. #ifndef SQLITE_OMIT_UTF16
  81203. /*
  81204. ** PRAGMA encoding
  81205. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  81206. **
  81207. ** In its first form, this pragma returns the encoding of the main
  81208. ** database. If the database is not initialized, it is initialized now.
  81209. **
  81210. ** The second form of this pragma is a no-op if the main database file
  81211. ** has not already been initialized. In this case it sets the default
  81212. ** encoding that will be used for the main database file if a new file
  81213. ** is created. If an existing main database file is opened, then the
  81214. ** default text encoding for the existing database is used.
  81215. **
  81216. ** In all cases new databases created using the ATTACH command are
  81217. ** created to use the same default text encoding as the main database. If
  81218. ** the main database has not been initialized and/or created when ATTACH
  81219. ** is executed, this is done before the ATTACH operation.
  81220. **
  81221. ** In the second form this pragma sets the text encoding to be used in
  81222. ** new database files created using this database handle. It is only
  81223. ** useful if invoked immediately after the main database i
  81224. */
  81225. case PragTyp_ENCODING: {
  81226. static const struct EncName {
  81227. char *zName;
  81228. u8 enc;
  81229. } encnames[] = {
  81230. { "UTF8", SQLITE_UTF8 },
  81231. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  81232. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  81233. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  81234. { "UTF16le", SQLITE_UTF16LE },
  81235. { "UTF16be", SQLITE_UTF16BE },
  81236. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  81237. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  81238. { 0, 0 }
  81239. };
  81240. const struct EncName *pEnc;
  81241. if( !zRight ){ /* "PRAGMA encoding" */
  81242. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  81243. sqlite3VdbeSetNumCols(v, 1);
  81244. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  81245. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  81246. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  81247. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  81248. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  81249. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  81250. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  81251. }else{ /* "PRAGMA encoding = XXX" */
  81252. /* Only change the value of sqlite.enc if the database handle is not
  81253. ** initialized. If the main database exists, the new sqlite.enc value
  81254. ** will be overwritten when the schema is next loaded. If it does not
  81255. ** already exists, it will be created to use the new encoding value.
  81256. */
  81257. if(
  81258. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  81259. DbHasProperty(db, 0, DB_Empty)
  81260. ){
  81261. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  81262. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  81263. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  81264. break;
  81265. }
  81266. }
  81267. if( !pEnc->zName ){
  81268. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  81269. }
  81270. }
  81271. }
  81272. }
  81273. break;
  81274. #endif /* SQLITE_OMIT_UTF16 */
  81275. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  81276. /*
  81277. ** PRAGMA [database.]schema_version
  81278. ** PRAGMA [database.]schema_version = <integer>
  81279. **
  81280. ** PRAGMA [database.]user_version
  81281. ** PRAGMA [database.]user_version = <integer>
  81282. **
  81283. ** PRAGMA [database.]freelist_count = <integer>
  81284. **
  81285. ** PRAGMA [database.]application_id
  81286. ** PRAGMA [database.]application_id = <integer>
  81287. **
  81288. ** The pragma's schema_version and user_version are used to set or get
  81289. ** the value of the schema-version and user-version, respectively. Both
  81290. ** the schema-version and the user-version are 32-bit signed integers
  81291. ** stored in the database header.
  81292. **
  81293. ** The schema-cookie is usually only manipulated internally by SQLite. It
  81294. ** is incremented by SQLite whenever the database schema is modified (by
  81295. ** creating or dropping a table or index). The schema version is used by
  81296. ** SQLite each time a query is executed to ensure that the internal cache
  81297. ** of the schema used when compiling the SQL query matches the schema of
  81298. ** the database against which the compiled query is actually executed.
  81299. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  81300. ** the schema-version is potentially dangerous and may lead to program
  81301. ** crashes or database corruption. Use with caution!
  81302. **
  81303. ** The user-version is not used internally by SQLite. It may be used by
  81304. ** applications for any purpose.
  81305. */
  81306. case PragTyp_HEADER_VALUE: {
  81307. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  81308. sqlite3VdbeUsesBtree(v, iDb);
  81309. switch( zLeft[0] ){
  81310. case 'a': case 'A':
  81311. iCookie = BTREE_APPLICATION_ID;
  81312. break;
  81313. case 'f': case 'F':
  81314. iCookie = BTREE_FREE_PAGE_COUNT;
  81315. break;
  81316. case 's': case 'S':
  81317. iCookie = BTREE_SCHEMA_VERSION;
  81318. break;
  81319. default:
  81320. iCookie = BTREE_USER_VERSION;
  81321. break;
  81322. }
  81323. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  81324. /* Write the specified cookie value */
  81325. static const VdbeOpList setCookie[] = {
  81326. { OP_Transaction, 0, 1, 0}, /* 0 */
  81327. { OP_Integer, 0, 1, 0}, /* 1 */
  81328. { OP_SetCookie, 0, 0, 1}, /* 2 */
  81329. };
  81330. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  81331. sqlite3VdbeChangeP1(v, addr, iDb);
  81332. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  81333. sqlite3VdbeChangeP1(v, addr+2, iDb);
  81334. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  81335. }else{
  81336. /* Read the specified cookie value */
  81337. static const VdbeOpList readCookie[] = {
  81338. { OP_Transaction, 0, 0, 0}, /* 0 */
  81339. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  81340. { OP_ResultRow, 1, 1, 0}
  81341. };
  81342. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  81343. sqlite3VdbeChangeP1(v, addr, iDb);
  81344. sqlite3VdbeChangeP1(v, addr+1, iDb);
  81345. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  81346. sqlite3VdbeSetNumCols(v, 1);
  81347. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  81348. }
  81349. }
  81350. break;
  81351. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  81352. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  81353. /*
  81354. ** PRAGMA compile_options
  81355. **
  81356. ** Return the names of all compile-time options used in this build,
  81357. ** one option per row.
  81358. */
  81359. case PragTyp_COMPILE_OPTIONS: {
  81360. int i = 0;
  81361. const char *zOpt;
  81362. sqlite3VdbeSetNumCols(v, 1);
  81363. pParse->nMem = 1;
  81364. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  81365. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  81366. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  81367. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  81368. }
  81369. }
  81370. break;
  81371. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  81372. #ifndef SQLITE_OMIT_WAL
  81373. /*
  81374. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  81375. **
  81376. ** Checkpoint the database.
  81377. */
  81378. case PragTyp_WAL_CHECKPOINT: {
  81379. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  81380. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  81381. if( zRight ){
  81382. if( sqlite3StrICmp(zRight, "full")==0 ){
  81383. eMode = SQLITE_CHECKPOINT_FULL;
  81384. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  81385. eMode = SQLITE_CHECKPOINT_RESTART;
  81386. }
  81387. }
  81388. sqlite3VdbeSetNumCols(v, 3);
  81389. pParse->nMem = 3;
  81390. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  81391. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  81392. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  81393. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  81394. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  81395. }
  81396. break;
  81397. /*
  81398. ** PRAGMA wal_autocheckpoint
  81399. ** PRAGMA wal_autocheckpoint = N
  81400. **
  81401. ** Configure a database connection to automatically checkpoint a database
  81402. ** after accumulating N frames in the log. Or query for the current value
  81403. ** of N.
  81404. */
  81405. case PragTyp_WAL_AUTOCHECKPOINT: {
  81406. if( zRight ){
  81407. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  81408. }
  81409. returnSingleInt(pParse, "wal_autocheckpoint",
  81410. db->xWalCallback==sqlite3WalDefaultHook ?
  81411. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  81412. }
  81413. break;
  81414. #endif
  81415. /*
  81416. ** PRAGMA shrink_memory
  81417. **
  81418. ** This pragma attempts to free as much memory as possible from the
  81419. ** current database connection.
  81420. */
  81421. case PragTyp_SHRINK_MEMORY: {
  81422. sqlite3_db_release_memory(db);
  81423. break;
  81424. }
  81425. /*
  81426. ** PRAGMA busy_timeout
  81427. ** PRAGMA busy_timeout = N
  81428. **
  81429. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  81430. ** if one is set. If no busy handler or a different busy handler is set
  81431. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  81432. ** disables the timeout.
  81433. */
  81434. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  81435. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  81436. if( zRight ){
  81437. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  81438. }
  81439. returnSingleInt(pParse, "timeout", db->busyTimeout);
  81440. break;
  81441. }
  81442. /*
  81443. ** PRAGMA soft_heap_limit
  81444. ** PRAGMA soft_heap_limit = N
  81445. **
  81446. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  81447. ** use -1.
  81448. */
  81449. case PragTyp_SOFT_HEAP_LIMIT: {
  81450. sqlite3_int64 N;
  81451. if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
  81452. sqlite3_soft_heap_limit64(N);
  81453. }
  81454. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  81455. break;
  81456. }
  81457. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  81458. /*
  81459. ** Report the current state of file logs for all databases
  81460. */
  81461. case PragTyp_LOCK_STATUS: {
  81462. static const char *const azLockName[] = {
  81463. "unlocked", "shared", "reserved", "pending", "exclusive"
  81464. };
  81465. int i;
  81466. sqlite3VdbeSetNumCols(v, 2);
  81467. pParse->nMem = 2;
  81468. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  81469. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  81470. for(i=0; i<db->nDb; i++){
  81471. Btree *pBt;
  81472. const char *zState = "unknown";
  81473. int j;
  81474. if( db->aDb[i].zName==0 ) continue;
  81475. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  81476. pBt = db->aDb[i].pBt;
  81477. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  81478. zState = "closed";
  81479. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  81480. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  81481. zState = azLockName[j];
  81482. }
  81483. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  81484. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  81485. }
  81486. break;
  81487. }
  81488. #endif
  81489. #ifdef SQLITE_HAS_CODEC
  81490. case PragTyp_KEY: {
  81491. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  81492. break;
  81493. }
  81494. case PragTyp_REKEY: {
  81495. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  81496. break;
  81497. }
  81498. case PragTyp_HEXKEY: {
  81499. if( zRight ){
  81500. u8 iByte;
  81501. int i;
  81502. char zKey[40];
  81503. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  81504. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  81505. if( (i&1)!=0 ) zKey[i/2] = iByte;
  81506. }
  81507. if( (zLeft[3] & 0xf)==0xb ){
  81508. sqlite3_key_v2(db, zDb, zKey, i/2);
  81509. }else{
  81510. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  81511. }
  81512. }
  81513. break;
  81514. }
  81515. #endif
  81516. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  81517. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  81518. #ifdef SQLITE_HAS_CODEC
  81519. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  81520. sqlite3_activate_see(&zRight[4]);
  81521. }
  81522. #endif
  81523. #ifdef SQLITE_ENABLE_CEROD
  81524. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  81525. sqlite3_activate_cerod(&zRight[6]);
  81526. }
  81527. #endif
  81528. }
  81529. break;
  81530. #endif
  81531. } /* End of the PRAGMA switch */
  81532. pragma_out:
  81533. sqlite3DbFree(db, zLeft);
  81534. sqlite3DbFree(db, zRight);
  81535. }
  81536. #endif /* SQLITE_OMIT_PRAGMA */
  81537. /************** End of pragma.c **********************************************/
  81538. /************** Begin file prepare.c *****************************************/
  81539. /*
  81540. ** 2005 May 25
  81541. **
  81542. ** The author disclaims copyright to this source code. In place of
  81543. ** a legal notice, here is a blessing:
  81544. **
  81545. ** May you do good and not evil.
  81546. ** May you find forgiveness for yourself and forgive others.
  81547. ** May you share freely, never taking more than you give.
  81548. **
  81549. *************************************************************************
  81550. ** This file contains the implementation of the sqlite3_prepare()
  81551. ** interface, and routines that contribute to loading the database schema
  81552. ** from disk.
  81553. */
  81554. /*
  81555. ** Fill the InitData structure with an error message that indicates
  81556. ** that the database is corrupt.
  81557. */
  81558. static void corruptSchema(
  81559. InitData *pData, /* Initialization context */
  81560. const char *zObj, /* Object being parsed at the point of error */
  81561. const char *zExtra /* Error information */
  81562. ){
  81563. sqlite3 *db = pData->db;
  81564. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  81565. if( zObj==0 ) zObj = "?";
  81566. sqlite3SetString(pData->pzErrMsg, db,
  81567. "malformed database schema (%s)", zObj);
  81568. if( zExtra ){
  81569. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  81570. "%s - %s", *pData->pzErrMsg, zExtra);
  81571. }
  81572. }
  81573. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  81574. }
  81575. /*
  81576. ** This is the callback routine for the code that initializes the
  81577. ** database. See sqlite3Init() below for additional information.
  81578. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  81579. **
  81580. ** Each callback contains the following information:
  81581. **
  81582. ** argv[0] = name of thing being created
  81583. ** argv[1] = root page number for table or index. 0 for trigger or view.
  81584. ** argv[2] = SQL text for the CREATE statement.
  81585. **
  81586. */
  81587. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  81588. InitData *pData = (InitData*)pInit;
  81589. sqlite3 *db = pData->db;
  81590. int iDb = pData->iDb;
  81591. assert( argc==3 );
  81592. UNUSED_PARAMETER2(NotUsed, argc);
  81593. assert( sqlite3_mutex_held(db->mutex) );
  81594. DbClearProperty(db, iDb, DB_Empty);
  81595. if( db->mallocFailed ){
  81596. corruptSchema(pData, argv[0], 0);
  81597. return 1;
  81598. }
  81599. assert( iDb>=0 && iDb<db->nDb );
  81600. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  81601. if( argv[1]==0 ){
  81602. corruptSchema(pData, argv[0], 0);
  81603. }else if( argv[2] && argv[2][0] ){
  81604. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  81605. ** But because db->init.busy is set to 1, no VDBE code is generated
  81606. ** or executed. All the parser does is build the internal data
  81607. ** structures that describe the table, index, or view.
  81608. */
  81609. int rc;
  81610. sqlite3_stmt *pStmt;
  81611. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  81612. assert( db->init.busy );
  81613. db->init.iDb = iDb;
  81614. db->init.newTnum = sqlite3Atoi(argv[1]);
  81615. db->init.orphanTrigger = 0;
  81616. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  81617. rc = db->errCode;
  81618. assert( (rc&0xFF)==(rcp&0xFF) );
  81619. db->init.iDb = 0;
  81620. if( SQLITE_OK!=rc ){
  81621. if( db->init.orphanTrigger ){
  81622. assert( iDb==1 );
  81623. }else{
  81624. pData->rc = rc;
  81625. if( rc==SQLITE_NOMEM ){
  81626. db->mallocFailed = 1;
  81627. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  81628. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  81629. }
  81630. }
  81631. }
  81632. sqlite3_finalize(pStmt);
  81633. }else if( argv[0]==0 ){
  81634. corruptSchema(pData, 0, 0);
  81635. }else{
  81636. /* If the SQL column is blank it means this is an index that
  81637. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  81638. ** constraint for a CREATE TABLE. The index should have already
  81639. ** been created when we processed the CREATE TABLE. All we have
  81640. ** to do here is record the root page number for that index.
  81641. */
  81642. Index *pIndex;
  81643. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  81644. if( pIndex==0 ){
  81645. /* This can occur if there exists an index on a TEMP table which
  81646. ** has the same name as another index on a permanent index. Since
  81647. ** the permanent table is hidden by the TEMP table, we can also
  81648. ** safely ignore the index on the permanent table.
  81649. */
  81650. /* Do Nothing */;
  81651. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  81652. corruptSchema(pData, argv[0], "invalid rootpage");
  81653. }
  81654. }
  81655. return 0;
  81656. }
  81657. /*
  81658. ** Attempt to read the database schema and initialize internal
  81659. ** data structures for a single database file. The index of the
  81660. ** database file is given by iDb. iDb==0 is used for the main
  81661. ** database. iDb==1 should never be used. iDb>=2 is used for
  81662. ** auxiliary databases. Return one of the SQLITE_ error codes to
  81663. ** indicate success or failure.
  81664. */
  81665. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  81666. int rc;
  81667. int i;
  81668. #ifndef SQLITE_OMIT_DEPRECATED
  81669. int size;
  81670. #endif
  81671. Table *pTab;
  81672. Db *pDb;
  81673. char const *azArg[4];
  81674. int meta[5];
  81675. InitData initData;
  81676. char const *zMasterSchema;
  81677. char const *zMasterName;
  81678. int openedTransaction = 0;
  81679. /*
  81680. ** The master database table has a structure like this
  81681. */
  81682. static const char master_schema[] =
  81683. "CREATE TABLE sqlite_master(\n"
  81684. " type text,\n"
  81685. " name text,\n"
  81686. " tbl_name text,\n"
  81687. " rootpage integer,\n"
  81688. " sql text\n"
  81689. ")"
  81690. ;
  81691. #ifndef SQLITE_OMIT_TEMPDB
  81692. static const char temp_master_schema[] =
  81693. "CREATE TEMP TABLE sqlite_temp_master(\n"
  81694. " type text,\n"
  81695. " name text,\n"
  81696. " tbl_name text,\n"
  81697. " rootpage integer,\n"
  81698. " sql text\n"
  81699. ")"
  81700. ;
  81701. #else
  81702. #define temp_master_schema 0
  81703. #endif
  81704. assert( iDb>=0 && iDb<db->nDb );
  81705. assert( db->aDb[iDb].pSchema );
  81706. assert( sqlite3_mutex_held(db->mutex) );
  81707. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  81708. /* zMasterSchema and zInitScript are set to point at the master schema
  81709. ** and initialisation script appropriate for the database being
  81710. ** initialized. zMasterName is the name of the master table.
  81711. */
  81712. if( !OMIT_TEMPDB && iDb==1 ){
  81713. zMasterSchema = temp_master_schema;
  81714. }else{
  81715. zMasterSchema = master_schema;
  81716. }
  81717. zMasterName = SCHEMA_TABLE(iDb);
  81718. /* Construct the schema tables. */
  81719. azArg[0] = zMasterName;
  81720. azArg[1] = "1";
  81721. azArg[2] = zMasterSchema;
  81722. azArg[3] = 0;
  81723. initData.db = db;
  81724. initData.iDb = iDb;
  81725. initData.rc = SQLITE_OK;
  81726. initData.pzErrMsg = pzErrMsg;
  81727. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  81728. if( initData.rc ){
  81729. rc = initData.rc;
  81730. goto error_out;
  81731. }
  81732. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  81733. if( ALWAYS(pTab) ){
  81734. pTab->tabFlags |= TF_Readonly;
  81735. }
  81736. /* Create a cursor to hold the database open
  81737. */
  81738. pDb = &db->aDb[iDb];
  81739. if( pDb->pBt==0 ){
  81740. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  81741. DbSetProperty(db, 1, DB_SchemaLoaded);
  81742. }
  81743. return SQLITE_OK;
  81744. }
  81745. /* If there is not already a read-only (or read-write) transaction opened
  81746. ** on the b-tree database, open one now. If a transaction is opened, it
  81747. ** will be closed before this function returns. */
  81748. sqlite3BtreeEnter(pDb->pBt);
  81749. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  81750. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  81751. if( rc!=SQLITE_OK ){
  81752. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  81753. goto initone_error_out;
  81754. }
  81755. openedTransaction = 1;
  81756. }
  81757. /* Get the database meta information.
  81758. **
  81759. ** Meta values are as follows:
  81760. ** meta[0] Schema cookie. Changes with each schema change.
  81761. ** meta[1] File format of schema layer.
  81762. ** meta[2] Size of the page cache.
  81763. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  81764. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  81765. ** meta[5] User version
  81766. ** meta[6] Incremental vacuum mode
  81767. ** meta[7] unused
  81768. ** meta[8] unused
  81769. ** meta[9] unused
  81770. **
  81771. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  81772. ** the possible values of meta[4].
  81773. */
  81774. for(i=0; i<ArraySize(meta); i++){
  81775. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  81776. }
  81777. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  81778. /* If opening a non-empty database, check the text encoding. For the
  81779. ** main database, set sqlite3.enc to the encoding of the main database.
  81780. ** For an attached db, it is an error if the encoding is not the same
  81781. ** as sqlite3.enc.
  81782. */
  81783. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  81784. if( iDb==0 ){
  81785. #ifndef SQLITE_OMIT_UTF16
  81786. u8 encoding;
  81787. /* If opening the main database, set ENC(db). */
  81788. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  81789. if( encoding==0 ) encoding = SQLITE_UTF8;
  81790. ENC(db) = encoding;
  81791. #else
  81792. ENC(db) = SQLITE_UTF8;
  81793. #endif
  81794. }else{
  81795. /* If opening an attached database, the encoding much match ENC(db) */
  81796. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  81797. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  81798. " text encoding as main database");
  81799. rc = SQLITE_ERROR;
  81800. goto initone_error_out;
  81801. }
  81802. }
  81803. }else{
  81804. DbSetProperty(db, iDb, DB_Empty);
  81805. }
  81806. pDb->pSchema->enc = ENC(db);
  81807. if( pDb->pSchema->cache_size==0 ){
  81808. #ifndef SQLITE_OMIT_DEPRECATED
  81809. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  81810. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  81811. pDb->pSchema->cache_size = size;
  81812. #else
  81813. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  81814. #endif
  81815. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  81816. }
  81817. /*
  81818. ** file_format==1 Version 3.0.0.
  81819. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  81820. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  81821. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  81822. */
  81823. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  81824. if( pDb->pSchema->file_format==0 ){
  81825. pDb->pSchema->file_format = 1;
  81826. }
  81827. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  81828. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  81829. rc = SQLITE_ERROR;
  81830. goto initone_error_out;
  81831. }
  81832. /* Ticket #2804: When we open a database in the newer file format,
  81833. ** clear the legacy_file_format pragma flag so that a VACUUM will
  81834. ** not downgrade the database and thus invalidate any descending
  81835. ** indices that the user might have created.
  81836. */
  81837. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  81838. db->flags &= ~SQLITE_LegacyFileFmt;
  81839. }
  81840. /* Read the schema information out of the schema tables
  81841. */
  81842. assert( db->init.busy );
  81843. {
  81844. char *zSql;
  81845. zSql = sqlite3MPrintf(db,
  81846. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  81847. db->aDb[iDb].zName, zMasterName);
  81848. #ifndef SQLITE_OMIT_AUTHORIZATION
  81849. {
  81850. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  81851. xAuth = db->xAuth;
  81852. db->xAuth = 0;
  81853. #endif
  81854. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  81855. #ifndef SQLITE_OMIT_AUTHORIZATION
  81856. db->xAuth = xAuth;
  81857. }
  81858. #endif
  81859. if( rc==SQLITE_OK ) rc = initData.rc;
  81860. sqlite3DbFree(db, zSql);
  81861. #ifndef SQLITE_OMIT_ANALYZE
  81862. if( rc==SQLITE_OK ){
  81863. sqlite3AnalysisLoad(db, iDb);
  81864. }
  81865. #endif
  81866. }
  81867. if( db->mallocFailed ){
  81868. rc = SQLITE_NOMEM;
  81869. sqlite3ResetAllSchemasOfConnection(db);
  81870. }
  81871. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  81872. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  81873. ** the schema loaded, even if errors occurred. In this situation the
  81874. ** current sqlite3_prepare() operation will fail, but the following one
  81875. ** will attempt to compile the supplied statement against whatever subset
  81876. ** of the schema was loaded before the error occurred. The primary
  81877. ** purpose of this is to allow access to the sqlite_master table
  81878. ** even when its contents have been corrupted.
  81879. */
  81880. DbSetProperty(db, iDb, DB_SchemaLoaded);
  81881. rc = SQLITE_OK;
  81882. }
  81883. /* Jump here for an error that occurs after successfully allocating
  81884. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  81885. ** before that point, jump to error_out.
  81886. */
  81887. initone_error_out:
  81888. if( openedTransaction ){
  81889. sqlite3BtreeCommit(pDb->pBt);
  81890. }
  81891. sqlite3BtreeLeave(pDb->pBt);
  81892. error_out:
  81893. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  81894. db->mallocFailed = 1;
  81895. }
  81896. return rc;
  81897. }
  81898. /*
  81899. ** Initialize all database files - the main database file, the file
  81900. ** used to store temporary tables, and any additional database files
  81901. ** created using ATTACH statements. Return a success code. If an
  81902. ** error occurs, write an error message into *pzErrMsg.
  81903. **
  81904. ** After a database is initialized, the DB_SchemaLoaded bit is set
  81905. ** bit is set in the flags field of the Db structure. If the database
  81906. ** file was of zero-length, then the DB_Empty flag is also set.
  81907. */
  81908. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  81909. int i, rc;
  81910. int commit_internal = !(db->flags&SQLITE_InternChanges);
  81911. assert( sqlite3_mutex_held(db->mutex) );
  81912. rc = SQLITE_OK;
  81913. db->init.busy = 1;
  81914. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  81915. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  81916. rc = sqlite3InitOne(db, i, pzErrMsg);
  81917. if( rc ){
  81918. sqlite3ResetOneSchema(db, i);
  81919. }
  81920. }
  81921. /* Once all the other databases have been initialized, load the schema
  81922. ** for the TEMP database. This is loaded last, as the TEMP database
  81923. ** schema may contain references to objects in other databases.
  81924. */
  81925. #ifndef SQLITE_OMIT_TEMPDB
  81926. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  81927. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  81928. rc = sqlite3InitOne(db, 1, pzErrMsg);
  81929. if( rc ){
  81930. sqlite3ResetOneSchema(db, 1);
  81931. }
  81932. }
  81933. #endif
  81934. db->init.busy = 0;
  81935. if( rc==SQLITE_OK && commit_internal ){
  81936. sqlite3CommitInternalChanges(db);
  81937. }
  81938. return rc;
  81939. }
  81940. /*
  81941. ** This routine is a no-op if the database schema is already initialized.
  81942. ** Otherwise, the schema is loaded. An error code is returned.
  81943. */
  81944. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  81945. int rc = SQLITE_OK;
  81946. sqlite3 *db = pParse->db;
  81947. assert( sqlite3_mutex_held(db->mutex) );
  81948. if( !db->init.busy ){
  81949. rc = sqlite3Init(db, &pParse->zErrMsg);
  81950. }
  81951. if( rc!=SQLITE_OK ){
  81952. pParse->rc = rc;
  81953. pParse->nErr++;
  81954. }
  81955. return rc;
  81956. }
  81957. /*
  81958. ** Check schema cookies in all databases. If any cookie is out
  81959. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  81960. ** make no changes to pParse->rc.
  81961. */
  81962. static void schemaIsValid(Parse *pParse){
  81963. sqlite3 *db = pParse->db;
  81964. int iDb;
  81965. int rc;
  81966. int cookie;
  81967. assert( pParse->checkSchema );
  81968. assert( sqlite3_mutex_held(db->mutex) );
  81969. for(iDb=0; iDb<db->nDb; iDb++){
  81970. int openedTransaction = 0; /* True if a transaction is opened */
  81971. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  81972. if( pBt==0 ) continue;
  81973. /* If there is not already a read-only (or read-write) transaction opened
  81974. ** on the b-tree database, open one now. If a transaction is opened, it
  81975. ** will be closed immediately after reading the meta-value. */
  81976. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  81977. rc = sqlite3BtreeBeginTrans(pBt, 0);
  81978. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  81979. db->mallocFailed = 1;
  81980. }
  81981. if( rc!=SQLITE_OK ) return;
  81982. openedTransaction = 1;
  81983. }
  81984. /* Read the schema cookie from the database. If it does not match the
  81985. ** value stored as part of the in-memory schema representation,
  81986. ** set Parse.rc to SQLITE_SCHEMA. */
  81987. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  81988. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81989. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  81990. sqlite3ResetOneSchema(db, iDb);
  81991. pParse->rc = SQLITE_SCHEMA;
  81992. }
  81993. /* Close the transaction, if one was opened. */
  81994. if( openedTransaction ){
  81995. sqlite3BtreeCommit(pBt);
  81996. }
  81997. }
  81998. }
  81999. /*
  82000. ** Convert a schema pointer into the iDb index that indicates
  82001. ** which database file in db->aDb[] the schema refers to.
  82002. **
  82003. ** If the same database is attached more than once, the first
  82004. ** attached database is returned.
  82005. */
  82006. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  82007. int i = -1000000;
  82008. /* If pSchema is NULL, then return -1000000. This happens when code in
  82009. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  82010. ** created by a sub-select). In this case the return value of this
  82011. ** function should never be used.
  82012. **
  82013. ** We return -1000000 instead of the more usual -1 simply because using
  82014. ** -1000000 as the incorrect index into db->aDb[] is much
  82015. ** more likely to cause a segfault than -1 (of course there are assert()
  82016. ** statements too, but it never hurts to play the odds).
  82017. */
  82018. assert( sqlite3_mutex_held(db->mutex) );
  82019. if( pSchema ){
  82020. for(i=0; ALWAYS(i<db->nDb); i++){
  82021. if( db->aDb[i].pSchema==pSchema ){
  82022. break;
  82023. }
  82024. }
  82025. assert( i>=0 && i<db->nDb );
  82026. }
  82027. return i;
  82028. }
  82029. /*
  82030. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  82031. */
  82032. static int sqlite3Prepare(
  82033. sqlite3 *db, /* Database handle. */
  82034. const char *zSql, /* UTF-8 encoded SQL statement. */
  82035. int nBytes, /* Length of zSql in bytes. */
  82036. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  82037. Vdbe *pReprepare, /* VM being reprepared */
  82038. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82039. const char **pzTail /* OUT: End of parsed string */
  82040. ){
  82041. Parse *pParse; /* Parsing context */
  82042. char *zErrMsg = 0; /* Error message */
  82043. int rc = SQLITE_OK; /* Result code */
  82044. int i; /* Loop counter */
  82045. /* Allocate the parsing context */
  82046. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  82047. if( pParse==0 ){
  82048. rc = SQLITE_NOMEM;
  82049. goto end_prepare;
  82050. }
  82051. pParse->pReprepare = pReprepare;
  82052. assert( ppStmt && *ppStmt==0 );
  82053. assert( !db->mallocFailed );
  82054. assert( sqlite3_mutex_held(db->mutex) );
  82055. /* Check to verify that it is possible to get a read lock on all
  82056. ** database schemas. The inability to get a read lock indicates that
  82057. ** some other database connection is holding a write-lock, which in
  82058. ** turn means that the other connection has made uncommitted changes
  82059. ** to the schema.
  82060. **
  82061. ** Were we to proceed and prepare the statement against the uncommitted
  82062. ** schema changes and if those schema changes are subsequently rolled
  82063. ** back and different changes are made in their place, then when this
  82064. ** prepared statement goes to run the schema cookie would fail to detect
  82065. ** the schema change. Disaster would follow.
  82066. **
  82067. ** This thread is currently holding mutexes on all Btrees (because
  82068. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  82069. ** is not possible for another thread to start a new schema change
  82070. ** while this routine is running. Hence, we do not need to hold
  82071. ** locks on the schema, we just need to make sure nobody else is
  82072. ** holding them.
  82073. **
  82074. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  82075. ** but it does *not* override schema lock detection, so this all still
  82076. ** works even if READ_UNCOMMITTED is set.
  82077. */
  82078. for(i=0; i<db->nDb; i++) {
  82079. Btree *pBt = db->aDb[i].pBt;
  82080. if( pBt ){
  82081. assert( sqlite3BtreeHoldsMutex(pBt) );
  82082. rc = sqlite3BtreeSchemaLocked(pBt);
  82083. if( rc ){
  82084. const char *zDb = db->aDb[i].zName;
  82085. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  82086. testcase( db->flags & SQLITE_ReadUncommitted );
  82087. goto end_prepare;
  82088. }
  82089. }
  82090. }
  82091. sqlite3VtabUnlockList(db);
  82092. pParse->db = db;
  82093. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  82094. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  82095. char *zSqlCopy;
  82096. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  82097. testcase( nBytes==mxLen );
  82098. testcase( nBytes==mxLen+1 );
  82099. if( nBytes>mxLen ){
  82100. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  82101. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  82102. goto end_prepare;
  82103. }
  82104. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  82105. if( zSqlCopy ){
  82106. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  82107. sqlite3DbFree(db, zSqlCopy);
  82108. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  82109. }else{
  82110. pParse->zTail = &zSql[nBytes];
  82111. }
  82112. }else{
  82113. sqlite3RunParser(pParse, zSql, &zErrMsg);
  82114. }
  82115. assert( 0==pParse->nQueryLoop );
  82116. if( db->mallocFailed ){
  82117. pParse->rc = SQLITE_NOMEM;
  82118. }
  82119. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  82120. if( pParse->checkSchema ){
  82121. schemaIsValid(pParse);
  82122. }
  82123. if( db->mallocFailed ){
  82124. pParse->rc = SQLITE_NOMEM;
  82125. }
  82126. if( pzTail ){
  82127. *pzTail = pParse->zTail;
  82128. }
  82129. rc = pParse->rc;
  82130. #ifndef SQLITE_OMIT_EXPLAIN
  82131. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  82132. static const char * const azColName[] = {
  82133. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  82134. "selectid", "order", "from", "detail"
  82135. };
  82136. int iFirst, mx;
  82137. if( pParse->explain==2 ){
  82138. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  82139. iFirst = 8;
  82140. mx = 12;
  82141. }else{
  82142. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  82143. iFirst = 0;
  82144. mx = 8;
  82145. }
  82146. for(i=iFirst; i<mx; i++){
  82147. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  82148. azColName[i], SQLITE_STATIC);
  82149. }
  82150. }
  82151. #endif
  82152. if( db->init.busy==0 ){
  82153. Vdbe *pVdbe = pParse->pVdbe;
  82154. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  82155. }
  82156. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  82157. sqlite3VdbeFinalize(pParse->pVdbe);
  82158. assert(!(*ppStmt));
  82159. }else{
  82160. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  82161. }
  82162. if( zErrMsg ){
  82163. sqlite3Error(db, rc, "%s", zErrMsg);
  82164. sqlite3DbFree(db, zErrMsg);
  82165. }else{
  82166. sqlite3Error(db, rc, 0);
  82167. }
  82168. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  82169. while( pParse->pTriggerPrg ){
  82170. TriggerPrg *pT = pParse->pTriggerPrg;
  82171. pParse->pTriggerPrg = pT->pNext;
  82172. sqlite3DbFree(db, pT);
  82173. }
  82174. end_prepare:
  82175. sqlite3StackFree(db, pParse);
  82176. rc = sqlite3ApiExit(db, rc);
  82177. assert( (rc&db->errMask)==rc );
  82178. return rc;
  82179. }
  82180. static int sqlite3LockAndPrepare(
  82181. sqlite3 *db, /* Database handle. */
  82182. const char *zSql, /* UTF-8 encoded SQL statement. */
  82183. int nBytes, /* Length of zSql in bytes. */
  82184. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  82185. Vdbe *pOld, /* VM being reprepared */
  82186. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82187. const char **pzTail /* OUT: End of parsed string */
  82188. ){
  82189. int rc;
  82190. assert( ppStmt!=0 );
  82191. *ppStmt = 0;
  82192. if( !sqlite3SafetyCheckOk(db) ){
  82193. return SQLITE_MISUSE_BKPT;
  82194. }
  82195. sqlite3_mutex_enter(db->mutex);
  82196. sqlite3BtreeEnterAll(db);
  82197. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  82198. if( rc==SQLITE_SCHEMA ){
  82199. sqlite3_finalize(*ppStmt);
  82200. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  82201. }
  82202. sqlite3BtreeLeaveAll(db);
  82203. sqlite3_mutex_leave(db->mutex);
  82204. assert( rc==SQLITE_OK || *ppStmt==0 );
  82205. return rc;
  82206. }
  82207. /*
  82208. ** Rerun the compilation of a statement after a schema change.
  82209. **
  82210. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  82211. ** if the statement cannot be recompiled because another connection has
  82212. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  82213. ** occurs, return SQLITE_SCHEMA.
  82214. */
  82215. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  82216. int rc;
  82217. sqlite3_stmt *pNew;
  82218. const char *zSql;
  82219. sqlite3 *db;
  82220. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  82221. zSql = sqlite3_sql((sqlite3_stmt *)p);
  82222. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  82223. db = sqlite3VdbeDb(p);
  82224. assert( sqlite3_mutex_held(db->mutex) );
  82225. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  82226. if( rc ){
  82227. if( rc==SQLITE_NOMEM ){
  82228. db->mallocFailed = 1;
  82229. }
  82230. assert( pNew==0 );
  82231. return rc;
  82232. }else{
  82233. assert( pNew!=0 );
  82234. }
  82235. sqlite3VdbeSwap((Vdbe*)pNew, p);
  82236. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  82237. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  82238. sqlite3VdbeFinalize((Vdbe*)pNew);
  82239. return SQLITE_OK;
  82240. }
  82241. /*
  82242. ** Two versions of the official API. Legacy and new use. In the legacy
  82243. ** version, the original SQL text is not saved in the prepared statement
  82244. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  82245. ** sqlite3_step(). In the new version, the original SQL text is retained
  82246. ** and the statement is automatically recompiled if an schema change
  82247. ** occurs.
  82248. */
  82249. SQLITE_API int sqlite3_prepare(
  82250. sqlite3 *db, /* Database handle. */
  82251. const char *zSql, /* UTF-8 encoded SQL statement. */
  82252. int nBytes, /* Length of zSql in bytes. */
  82253. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82254. const char **pzTail /* OUT: End of parsed string */
  82255. ){
  82256. int rc;
  82257. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  82258. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82259. return rc;
  82260. }
  82261. SQLITE_API int sqlite3_prepare_v2(
  82262. sqlite3 *db, /* Database handle. */
  82263. const char *zSql, /* UTF-8 encoded SQL statement. */
  82264. int nBytes, /* Length of zSql in bytes. */
  82265. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82266. const char **pzTail /* OUT: End of parsed string */
  82267. ){
  82268. int rc;
  82269. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  82270. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82271. return rc;
  82272. }
  82273. #ifndef SQLITE_OMIT_UTF16
  82274. /*
  82275. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  82276. */
  82277. static int sqlite3Prepare16(
  82278. sqlite3 *db, /* Database handle. */
  82279. const void *zSql, /* UTF-16 encoded SQL statement. */
  82280. int nBytes, /* Length of zSql in bytes. */
  82281. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  82282. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82283. const void **pzTail /* OUT: End of parsed string */
  82284. ){
  82285. /* This function currently works by first transforming the UTF-16
  82286. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  82287. ** tricky bit is figuring out the pointer to return in *pzTail.
  82288. */
  82289. char *zSql8;
  82290. const char *zTail8 = 0;
  82291. int rc = SQLITE_OK;
  82292. assert( ppStmt );
  82293. *ppStmt = 0;
  82294. if( !sqlite3SafetyCheckOk(db) ){
  82295. return SQLITE_MISUSE_BKPT;
  82296. }
  82297. if( nBytes>=0 ){
  82298. int sz;
  82299. const char *z = (const char*)zSql;
  82300. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  82301. nBytes = sz;
  82302. }
  82303. sqlite3_mutex_enter(db->mutex);
  82304. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  82305. if( zSql8 ){
  82306. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  82307. }
  82308. if( zTail8 && pzTail ){
  82309. /* If sqlite3_prepare returns a tail pointer, we calculate the
  82310. ** equivalent pointer into the UTF-16 string by counting the unicode
  82311. ** characters between zSql8 and zTail8, and then returning a pointer
  82312. ** the same number of characters into the UTF-16 string.
  82313. */
  82314. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  82315. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  82316. }
  82317. sqlite3DbFree(db, zSql8);
  82318. rc = sqlite3ApiExit(db, rc);
  82319. sqlite3_mutex_leave(db->mutex);
  82320. return rc;
  82321. }
  82322. /*
  82323. ** Two versions of the official API. Legacy and new use. In the legacy
  82324. ** version, the original SQL text is not saved in the prepared statement
  82325. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  82326. ** sqlite3_step(). In the new version, the original SQL text is retained
  82327. ** and the statement is automatically recompiled if an schema change
  82328. ** occurs.
  82329. */
  82330. SQLITE_API int sqlite3_prepare16(
  82331. sqlite3 *db, /* Database handle. */
  82332. const void *zSql, /* UTF-16 encoded SQL statement. */
  82333. int nBytes, /* Length of zSql in bytes. */
  82334. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82335. const void **pzTail /* OUT: End of parsed string */
  82336. ){
  82337. int rc;
  82338. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  82339. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82340. return rc;
  82341. }
  82342. SQLITE_API int sqlite3_prepare16_v2(
  82343. sqlite3 *db, /* Database handle. */
  82344. const void *zSql, /* UTF-16 encoded SQL statement. */
  82345. int nBytes, /* Length of zSql in bytes. */
  82346. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82347. const void **pzTail /* OUT: End of parsed string */
  82348. ){
  82349. int rc;
  82350. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  82351. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82352. return rc;
  82353. }
  82354. #endif /* SQLITE_OMIT_UTF16 */
  82355. /************** End of prepare.c *********************************************/
  82356. /************** Begin file select.c ******************************************/
  82357. /*
  82358. ** 2001 September 15
  82359. **
  82360. ** The author disclaims copyright to this source code. In place of
  82361. ** a legal notice, here is a blessing:
  82362. **
  82363. ** May you do good and not evil.
  82364. ** May you find forgiveness for yourself and forgive others.
  82365. ** May you share freely, never taking more than you give.
  82366. **
  82367. *************************************************************************
  82368. ** This file contains C code routines that are called by the parser
  82369. ** to handle SELECT statements in SQLite.
  82370. */
  82371. /*
  82372. ** Delete all the content of a Select structure but do not deallocate
  82373. ** the select structure itself.
  82374. */
  82375. static void clearSelect(sqlite3 *db, Select *p){
  82376. sqlite3ExprListDelete(db, p->pEList);
  82377. sqlite3SrcListDelete(db, p->pSrc);
  82378. sqlite3ExprDelete(db, p->pWhere);
  82379. sqlite3ExprListDelete(db, p->pGroupBy);
  82380. sqlite3ExprDelete(db, p->pHaving);
  82381. sqlite3ExprListDelete(db, p->pOrderBy);
  82382. sqlite3SelectDelete(db, p->pPrior);
  82383. sqlite3ExprDelete(db, p->pLimit);
  82384. sqlite3ExprDelete(db, p->pOffset);
  82385. }
  82386. /*
  82387. ** Initialize a SelectDest structure.
  82388. */
  82389. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  82390. pDest->eDest = (u8)eDest;
  82391. pDest->iSDParm = iParm;
  82392. pDest->affSdst = 0;
  82393. pDest->iSdst = 0;
  82394. pDest->nSdst = 0;
  82395. }
  82396. /*
  82397. ** Allocate a new Select structure and return a pointer to that
  82398. ** structure.
  82399. */
  82400. SQLITE_PRIVATE Select *sqlite3SelectNew(
  82401. Parse *pParse, /* Parsing context */
  82402. ExprList *pEList, /* which columns to include in the result */
  82403. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  82404. Expr *pWhere, /* the WHERE clause */
  82405. ExprList *pGroupBy, /* the GROUP BY clause */
  82406. Expr *pHaving, /* the HAVING clause */
  82407. ExprList *pOrderBy, /* the ORDER BY clause */
  82408. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  82409. Expr *pLimit, /* LIMIT value. NULL means not used */
  82410. Expr *pOffset /* OFFSET value. NULL means no offset */
  82411. ){
  82412. Select *pNew;
  82413. Select standin;
  82414. sqlite3 *db = pParse->db;
  82415. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  82416. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  82417. if( pNew==0 ){
  82418. assert( db->mallocFailed );
  82419. pNew = &standin;
  82420. memset(pNew, 0, sizeof(*pNew));
  82421. }
  82422. if( pEList==0 ){
  82423. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  82424. }
  82425. pNew->pEList = pEList;
  82426. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  82427. pNew->pSrc = pSrc;
  82428. pNew->pWhere = pWhere;
  82429. pNew->pGroupBy = pGroupBy;
  82430. pNew->pHaving = pHaving;
  82431. pNew->pOrderBy = pOrderBy;
  82432. pNew->selFlags = selFlags;
  82433. pNew->op = TK_SELECT;
  82434. pNew->pLimit = pLimit;
  82435. pNew->pOffset = pOffset;
  82436. assert( pOffset==0 || pLimit!=0 );
  82437. pNew->addrOpenEphm[0] = -1;
  82438. pNew->addrOpenEphm[1] = -1;
  82439. pNew->addrOpenEphm[2] = -1;
  82440. if( db->mallocFailed ) {
  82441. clearSelect(db, pNew);
  82442. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  82443. pNew = 0;
  82444. }else{
  82445. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  82446. }
  82447. assert( pNew!=&standin );
  82448. return pNew;
  82449. }
  82450. /*
  82451. ** Delete the given Select structure and all of its substructures.
  82452. */
  82453. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  82454. if( p ){
  82455. clearSelect(db, p);
  82456. sqlite3DbFree(db, p);
  82457. }
  82458. }
  82459. /*
  82460. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  82461. ** type of join. Return an integer constant that expresses that type
  82462. ** in terms of the following bit values:
  82463. **
  82464. ** JT_INNER
  82465. ** JT_CROSS
  82466. ** JT_OUTER
  82467. ** JT_NATURAL
  82468. ** JT_LEFT
  82469. ** JT_RIGHT
  82470. **
  82471. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  82472. **
  82473. ** If an illegal or unsupported join type is seen, then still return
  82474. ** a join type, but put an error in the pParse structure.
  82475. */
  82476. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  82477. int jointype = 0;
  82478. Token *apAll[3];
  82479. Token *p;
  82480. /* 0123456789 123456789 123456789 123 */
  82481. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  82482. static const struct {
  82483. u8 i; /* Beginning of keyword text in zKeyText[] */
  82484. u8 nChar; /* Length of the keyword in characters */
  82485. u8 code; /* Join type mask */
  82486. } aKeyword[] = {
  82487. /* natural */ { 0, 7, JT_NATURAL },
  82488. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  82489. /* outer */ { 10, 5, JT_OUTER },
  82490. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  82491. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  82492. /* inner */ { 23, 5, JT_INNER },
  82493. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  82494. };
  82495. int i, j;
  82496. apAll[0] = pA;
  82497. apAll[1] = pB;
  82498. apAll[2] = pC;
  82499. for(i=0; i<3 && apAll[i]; i++){
  82500. p = apAll[i];
  82501. for(j=0; j<ArraySize(aKeyword); j++){
  82502. if( p->n==aKeyword[j].nChar
  82503. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  82504. jointype |= aKeyword[j].code;
  82505. break;
  82506. }
  82507. }
  82508. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  82509. if( j>=ArraySize(aKeyword) ){
  82510. jointype |= JT_ERROR;
  82511. break;
  82512. }
  82513. }
  82514. if(
  82515. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  82516. (jointype & JT_ERROR)!=0
  82517. ){
  82518. const char *zSp = " ";
  82519. assert( pB!=0 );
  82520. if( pC==0 ){ zSp++; }
  82521. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  82522. "%T %T%s%T", pA, pB, zSp, pC);
  82523. jointype = JT_INNER;
  82524. }else if( (jointype & JT_OUTER)!=0
  82525. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  82526. sqlite3ErrorMsg(pParse,
  82527. "RIGHT and FULL OUTER JOINs are not currently supported");
  82528. jointype = JT_INNER;
  82529. }
  82530. return jointype;
  82531. }
  82532. /*
  82533. ** Return the index of a column in a table. Return -1 if the column
  82534. ** is not contained in the table.
  82535. */
  82536. static int columnIndex(Table *pTab, const char *zCol){
  82537. int i;
  82538. for(i=0; i<pTab->nCol; i++){
  82539. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  82540. }
  82541. return -1;
  82542. }
  82543. /*
  82544. ** Search the first N tables in pSrc, from left to right, looking for a
  82545. ** table that has a column named zCol.
  82546. **
  82547. ** When found, set *piTab and *piCol to the table index and column index
  82548. ** of the matching column and return TRUE.
  82549. **
  82550. ** If not found, return FALSE.
  82551. */
  82552. static int tableAndColumnIndex(
  82553. SrcList *pSrc, /* Array of tables to search */
  82554. int N, /* Number of tables in pSrc->a[] to search */
  82555. const char *zCol, /* Name of the column we are looking for */
  82556. int *piTab, /* Write index of pSrc->a[] here */
  82557. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  82558. ){
  82559. int i; /* For looping over tables in pSrc */
  82560. int iCol; /* Index of column matching zCol */
  82561. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  82562. for(i=0; i<N; i++){
  82563. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  82564. if( iCol>=0 ){
  82565. if( piTab ){
  82566. *piTab = i;
  82567. *piCol = iCol;
  82568. }
  82569. return 1;
  82570. }
  82571. }
  82572. return 0;
  82573. }
  82574. /*
  82575. ** This function is used to add terms implied by JOIN syntax to the
  82576. ** WHERE clause expression of a SELECT statement. The new term, which
  82577. ** is ANDed with the existing WHERE clause, is of the form:
  82578. **
  82579. ** (tab1.col1 = tab2.col2)
  82580. **
  82581. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  82582. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  82583. ** column iColRight of tab2.
  82584. */
  82585. static void addWhereTerm(
  82586. Parse *pParse, /* Parsing context */
  82587. SrcList *pSrc, /* List of tables in FROM clause */
  82588. int iLeft, /* Index of first table to join in pSrc */
  82589. int iColLeft, /* Index of column in first table */
  82590. int iRight, /* Index of second table in pSrc */
  82591. int iColRight, /* Index of column in second table */
  82592. int isOuterJoin, /* True if this is an OUTER join */
  82593. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  82594. ){
  82595. sqlite3 *db = pParse->db;
  82596. Expr *pE1;
  82597. Expr *pE2;
  82598. Expr *pEq;
  82599. assert( iLeft<iRight );
  82600. assert( pSrc->nSrc>iRight );
  82601. assert( pSrc->a[iLeft].pTab );
  82602. assert( pSrc->a[iRight].pTab );
  82603. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  82604. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  82605. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  82606. if( pEq && isOuterJoin ){
  82607. ExprSetProperty(pEq, EP_FromJoin);
  82608. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  82609. ExprSetVVAProperty(pEq, EP_NoReduce);
  82610. pEq->iRightJoinTable = (i16)pE2->iTable;
  82611. }
  82612. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  82613. }
  82614. /*
  82615. ** Set the EP_FromJoin property on all terms of the given expression.
  82616. ** And set the Expr.iRightJoinTable to iTable for every term in the
  82617. ** expression.
  82618. **
  82619. ** The EP_FromJoin property is used on terms of an expression to tell
  82620. ** the LEFT OUTER JOIN processing logic that this term is part of the
  82621. ** join restriction specified in the ON or USING clause and not a part
  82622. ** of the more general WHERE clause. These terms are moved over to the
  82623. ** WHERE clause during join processing but we need to remember that they
  82624. ** originated in the ON or USING clause.
  82625. **
  82626. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  82627. ** expression depends on table iRightJoinTable even if that table is not
  82628. ** explicitly mentioned in the expression. That information is needed
  82629. ** for cases like this:
  82630. **
  82631. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  82632. **
  82633. ** The where clause needs to defer the handling of the t1.x=5
  82634. ** term until after the t2 loop of the join. In that way, a
  82635. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  82636. ** defer the handling of t1.x=5, it will be processed immediately
  82637. ** after the t1 loop and rows with t1.x!=5 will never appear in
  82638. ** the output, which is incorrect.
  82639. */
  82640. static void setJoinExpr(Expr *p, int iTable){
  82641. while( p ){
  82642. ExprSetProperty(p, EP_FromJoin);
  82643. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  82644. ExprSetVVAProperty(p, EP_NoReduce);
  82645. p->iRightJoinTable = (i16)iTable;
  82646. setJoinExpr(p->pLeft, iTable);
  82647. p = p->pRight;
  82648. }
  82649. }
  82650. /*
  82651. ** This routine processes the join information for a SELECT statement.
  82652. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  82653. ** NATURAL joins also create extra WHERE clause terms.
  82654. **
  82655. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  82656. ** The left most table is the first entry in Select.pSrc. The right-most
  82657. ** table is the last entry. The join operator is held in the entry to
  82658. ** the left. Thus entry 0 contains the join operator for the join between
  82659. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  82660. ** also attached to the left entry.
  82661. **
  82662. ** This routine returns the number of errors encountered.
  82663. */
  82664. static int sqliteProcessJoin(Parse *pParse, Select *p){
  82665. SrcList *pSrc; /* All tables in the FROM clause */
  82666. int i, j; /* Loop counters */
  82667. struct SrcList_item *pLeft; /* Left table being joined */
  82668. struct SrcList_item *pRight; /* Right table being joined */
  82669. pSrc = p->pSrc;
  82670. pLeft = &pSrc->a[0];
  82671. pRight = &pLeft[1];
  82672. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  82673. Table *pLeftTab = pLeft->pTab;
  82674. Table *pRightTab = pRight->pTab;
  82675. int isOuter;
  82676. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  82677. isOuter = (pRight->jointype & JT_OUTER)!=0;
  82678. /* When the NATURAL keyword is present, add WHERE clause terms for
  82679. ** every column that the two tables have in common.
  82680. */
  82681. if( pRight->jointype & JT_NATURAL ){
  82682. if( pRight->pOn || pRight->pUsing ){
  82683. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  82684. "an ON or USING clause", 0);
  82685. return 1;
  82686. }
  82687. for(j=0; j<pRightTab->nCol; j++){
  82688. char *zName; /* Name of column in the right table */
  82689. int iLeft; /* Matching left table */
  82690. int iLeftCol; /* Matching column in the left table */
  82691. zName = pRightTab->aCol[j].zName;
  82692. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  82693. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  82694. isOuter, &p->pWhere);
  82695. }
  82696. }
  82697. }
  82698. /* Disallow both ON and USING clauses in the same join
  82699. */
  82700. if( pRight->pOn && pRight->pUsing ){
  82701. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  82702. "clauses in the same join");
  82703. return 1;
  82704. }
  82705. /* Add the ON clause to the end of the WHERE clause, connected by
  82706. ** an AND operator.
  82707. */
  82708. if( pRight->pOn ){
  82709. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  82710. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  82711. pRight->pOn = 0;
  82712. }
  82713. /* Create extra terms on the WHERE clause for each column named
  82714. ** in the USING clause. Example: If the two tables to be joined are
  82715. ** A and B and the USING clause names X, Y, and Z, then add this
  82716. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  82717. ** Report an error if any column mentioned in the USING clause is
  82718. ** not contained in both tables to be joined.
  82719. */
  82720. if( pRight->pUsing ){
  82721. IdList *pList = pRight->pUsing;
  82722. for(j=0; j<pList->nId; j++){
  82723. char *zName; /* Name of the term in the USING clause */
  82724. int iLeft; /* Table on the left with matching column name */
  82725. int iLeftCol; /* Column number of matching column on the left */
  82726. int iRightCol; /* Column number of matching column on the right */
  82727. zName = pList->a[j].zName;
  82728. iRightCol = columnIndex(pRightTab, zName);
  82729. if( iRightCol<0
  82730. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  82731. ){
  82732. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  82733. "not present in both tables", zName);
  82734. return 1;
  82735. }
  82736. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  82737. isOuter, &p->pWhere);
  82738. }
  82739. }
  82740. }
  82741. return 0;
  82742. }
  82743. /*
  82744. ** Insert code into "v" that will push the record on the top of the
  82745. ** stack into the sorter.
  82746. */
  82747. static void pushOntoSorter(
  82748. Parse *pParse, /* Parser context */
  82749. ExprList *pOrderBy, /* The ORDER BY clause */
  82750. Select *pSelect, /* The whole SELECT statement */
  82751. int regData /* Register holding data to be sorted */
  82752. ){
  82753. Vdbe *v = pParse->pVdbe;
  82754. int nExpr = pOrderBy->nExpr;
  82755. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  82756. int regRecord = sqlite3GetTempReg(pParse);
  82757. int op;
  82758. sqlite3ExprCacheClear(pParse);
  82759. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  82760. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  82761. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  82762. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  82763. if( pSelect->selFlags & SF_UseSorter ){
  82764. op = OP_SorterInsert;
  82765. }else{
  82766. op = OP_IdxInsert;
  82767. }
  82768. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  82769. sqlite3ReleaseTempReg(pParse, regRecord);
  82770. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  82771. if( pSelect->iLimit ){
  82772. int addr1, addr2;
  82773. int iLimit;
  82774. if( pSelect->iOffset ){
  82775. iLimit = pSelect->iOffset+1;
  82776. }else{
  82777. iLimit = pSelect->iLimit;
  82778. }
  82779. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  82780. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  82781. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  82782. sqlite3VdbeJumpHere(v, addr1);
  82783. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  82784. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  82785. sqlite3VdbeJumpHere(v, addr2);
  82786. }
  82787. }
  82788. /*
  82789. ** Add code to implement the OFFSET
  82790. */
  82791. static void codeOffset(
  82792. Vdbe *v, /* Generate code into this VM */
  82793. Select *p, /* The SELECT statement being coded */
  82794. int iContinue /* Jump here to skip the current record */
  82795. ){
  82796. if( p->iOffset && iContinue!=0 ){
  82797. int addr;
  82798. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  82799. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  82800. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  82801. VdbeComment((v, "skip OFFSET records"));
  82802. sqlite3VdbeJumpHere(v, addr);
  82803. }
  82804. }
  82805. /*
  82806. ** Add code that will check to make sure the N registers starting at iMem
  82807. ** form a distinct entry. iTab is a sorting index that holds previously
  82808. ** seen combinations of the N values. A new entry is made in iTab
  82809. ** if the current N values are new.
  82810. **
  82811. ** A jump to addrRepeat is made and the N+1 values are popped from the
  82812. ** stack if the top N elements are not distinct.
  82813. */
  82814. static void codeDistinct(
  82815. Parse *pParse, /* Parsing and code generating context */
  82816. int iTab, /* A sorting index used to test for distinctness */
  82817. int addrRepeat, /* Jump to here if not distinct */
  82818. int N, /* Number of elements */
  82819. int iMem /* First element */
  82820. ){
  82821. Vdbe *v;
  82822. int r1;
  82823. v = pParse->pVdbe;
  82824. r1 = sqlite3GetTempReg(pParse);
  82825. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  82826. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  82827. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  82828. sqlite3ReleaseTempReg(pParse, r1);
  82829. }
  82830. #ifndef SQLITE_OMIT_SUBQUERY
  82831. /*
  82832. ** Generate an error message when a SELECT is used within a subexpression
  82833. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  82834. ** column. We do this in a subroutine because the error used to occur
  82835. ** in multiple places. (The error only occurs in one place now, but we
  82836. ** retain the subroutine to minimize code disruption.)
  82837. */
  82838. static int checkForMultiColumnSelectError(
  82839. Parse *pParse, /* Parse context. */
  82840. SelectDest *pDest, /* Destination of SELECT results */
  82841. int nExpr /* Number of result columns returned by SELECT */
  82842. ){
  82843. int eDest = pDest->eDest;
  82844. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  82845. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  82846. "a SELECT that is part of an expression");
  82847. return 1;
  82848. }else{
  82849. return 0;
  82850. }
  82851. }
  82852. #endif
  82853. /*
  82854. ** An instance of the following object is used to record information about
  82855. ** how to process the DISTINCT keyword, to simplify passing that information
  82856. ** into the selectInnerLoop() routine.
  82857. */
  82858. typedef struct DistinctCtx DistinctCtx;
  82859. struct DistinctCtx {
  82860. u8 isTnct; /* True if the DISTINCT keyword is present */
  82861. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  82862. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  82863. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  82864. };
  82865. /*
  82866. ** This routine generates the code for the inside of the inner loop
  82867. ** of a SELECT.
  82868. **
  82869. ** If srcTab and nColumn are both zero, then the pEList expressions
  82870. ** are evaluated in order to get the data for this row. If nColumn>0
  82871. ** then data is pulled from srcTab and pEList is used only to get the
  82872. ** datatypes for each column.
  82873. */
  82874. static void selectInnerLoop(
  82875. Parse *pParse, /* The parser context */
  82876. Select *p, /* The complete select statement being coded */
  82877. ExprList *pEList, /* List of values being extracted */
  82878. int srcTab, /* Pull data from this table */
  82879. int nColumn, /* Number of columns in the source table */
  82880. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  82881. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  82882. SelectDest *pDest, /* How to dispose of the results */
  82883. int iContinue, /* Jump here to continue with next row */
  82884. int iBreak /* Jump here to break out of the inner loop */
  82885. ){
  82886. Vdbe *v = pParse->pVdbe;
  82887. int i;
  82888. int hasDistinct; /* True if the DISTINCT keyword is present */
  82889. int regResult; /* Start of memory holding result set */
  82890. int eDest = pDest->eDest; /* How to dispose of results */
  82891. int iParm = pDest->iSDParm; /* First argument to disposal method */
  82892. int nResultCol; /* Number of result columns */
  82893. assert( v );
  82894. if( NEVER(v==0) ) return;
  82895. assert( pEList!=0 );
  82896. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  82897. if( pOrderBy==0 && !hasDistinct ){
  82898. codeOffset(v, p, iContinue);
  82899. }
  82900. /* Pull the requested columns.
  82901. */
  82902. if( nColumn>0 ){
  82903. nResultCol = nColumn;
  82904. }else{
  82905. nResultCol = pEList->nExpr;
  82906. }
  82907. if( pDest->iSdst==0 ){
  82908. pDest->iSdst = pParse->nMem+1;
  82909. pDest->nSdst = nResultCol;
  82910. pParse->nMem += nResultCol;
  82911. }else{
  82912. assert( pDest->nSdst==nResultCol );
  82913. }
  82914. regResult = pDest->iSdst;
  82915. if( nColumn>0 ){
  82916. for(i=0; i<nColumn; i++){
  82917. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  82918. }
  82919. }else if( eDest!=SRT_Exists ){
  82920. /* If the destination is an EXISTS(...) expression, the actual
  82921. ** values returned by the SELECT are not required.
  82922. */
  82923. sqlite3ExprCacheClear(pParse);
  82924. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  82925. }
  82926. nColumn = nResultCol;
  82927. /* If the DISTINCT keyword was present on the SELECT statement
  82928. ** and this row has been seen before, then do not make this row
  82929. ** part of the result.
  82930. */
  82931. if( hasDistinct ){
  82932. assert( pEList!=0 );
  82933. assert( pEList->nExpr==nColumn );
  82934. switch( pDistinct->eTnctType ){
  82935. case WHERE_DISTINCT_ORDERED: {
  82936. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  82937. int iJump; /* Jump destination */
  82938. int regPrev; /* Previous row content */
  82939. /* Allocate space for the previous row */
  82940. regPrev = pParse->nMem+1;
  82941. pParse->nMem += nColumn;
  82942. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  82943. ** sets the MEM_Cleared bit on the first register of the
  82944. ** previous value. This will cause the OP_Ne below to always
  82945. ** fail on the first iteration of the loop even if the first
  82946. ** row is all NULLs.
  82947. */
  82948. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  82949. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  82950. pOp->opcode = OP_Null;
  82951. pOp->p1 = 1;
  82952. pOp->p2 = regPrev;
  82953. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  82954. for(i=0; i<nColumn; i++){
  82955. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  82956. if( i<nColumn-1 ){
  82957. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  82958. }else{
  82959. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  82960. }
  82961. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  82962. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  82963. }
  82964. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  82965. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  82966. break;
  82967. }
  82968. case WHERE_DISTINCT_UNIQUE: {
  82969. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  82970. break;
  82971. }
  82972. default: {
  82973. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  82974. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  82975. break;
  82976. }
  82977. }
  82978. if( pOrderBy==0 ){
  82979. codeOffset(v, p, iContinue);
  82980. }
  82981. }
  82982. switch( eDest ){
  82983. /* In this mode, write each query result to the key of the temporary
  82984. ** table iParm.
  82985. */
  82986. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  82987. case SRT_Union: {
  82988. int r1;
  82989. r1 = sqlite3GetTempReg(pParse);
  82990. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  82991. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  82992. sqlite3ReleaseTempReg(pParse, r1);
  82993. break;
  82994. }
  82995. /* Construct a record from the query result, but instead of
  82996. ** saving that record, use it as a key to delete elements from
  82997. ** the temporary table iParm.
  82998. */
  82999. case SRT_Except: {
  83000. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  83001. break;
  83002. }
  83003. #endif
  83004. /* Store the result as data using a unique key.
  83005. */
  83006. case SRT_Table:
  83007. case SRT_EphemTab: {
  83008. int r1 = sqlite3GetTempReg(pParse);
  83009. testcase( eDest==SRT_Table );
  83010. testcase( eDest==SRT_EphemTab );
  83011. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  83012. if( pOrderBy ){
  83013. pushOntoSorter(pParse, pOrderBy, p, r1);
  83014. }else{
  83015. int r2 = sqlite3GetTempReg(pParse);
  83016. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  83017. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  83018. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83019. sqlite3ReleaseTempReg(pParse, r2);
  83020. }
  83021. sqlite3ReleaseTempReg(pParse, r1);
  83022. break;
  83023. }
  83024. #ifndef SQLITE_OMIT_SUBQUERY
  83025. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  83026. ** then there should be a single item on the stack. Write this
  83027. ** item into the set table with bogus data.
  83028. */
  83029. case SRT_Set: {
  83030. assert( nColumn==1 );
  83031. pDest->affSdst =
  83032. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  83033. if( pOrderBy ){
  83034. /* At first glance you would think we could optimize out the
  83035. ** ORDER BY in this case since the order of entries in the set
  83036. ** does not matter. But there might be a LIMIT clause, in which
  83037. ** case the order does matter */
  83038. pushOntoSorter(pParse, pOrderBy, p, regResult);
  83039. }else{
  83040. int r1 = sqlite3GetTempReg(pParse);
  83041. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  83042. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  83043. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  83044. sqlite3ReleaseTempReg(pParse, r1);
  83045. }
  83046. break;
  83047. }
  83048. /* If any row exist in the result set, record that fact and abort.
  83049. */
  83050. case SRT_Exists: {
  83051. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  83052. /* The LIMIT clause will terminate the loop for us */
  83053. break;
  83054. }
  83055. /* If this is a scalar select that is part of an expression, then
  83056. ** store the results in the appropriate memory cell and break out
  83057. ** of the scan loop.
  83058. */
  83059. case SRT_Mem: {
  83060. assert( nColumn==1 );
  83061. if( pOrderBy ){
  83062. pushOntoSorter(pParse, pOrderBy, p, regResult);
  83063. }else{
  83064. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  83065. /* The LIMIT clause will jump out of the loop for us */
  83066. }
  83067. break;
  83068. }
  83069. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  83070. /* Send the data to the callback function or to a subroutine. In the
  83071. ** case of a subroutine, the subroutine itself is responsible for
  83072. ** popping the data from the stack.
  83073. */
  83074. case SRT_Coroutine:
  83075. case SRT_Output: {
  83076. testcase( eDest==SRT_Coroutine );
  83077. testcase( eDest==SRT_Output );
  83078. if( pOrderBy ){
  83079. int r1 = sqlite3GetTempReg(pParse);
  83080. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  83081. pushOntoSorter(pParse, pOrderBy, p, r1);
  83082. sqlite3ReleaseTempReg(pParse, r1);
  83083. }else if( eDest==SRT_Coroutine ){
  83084. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  83085. }else{
  83086. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  83087. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  83088. }
  83089. break;
  83090. }
  83091. #if !defined(SQLITE_OMIT_TRIGGER)
  83092. /* Discard the results. This is used for SELECT statements inside
  83093. ** the body of a TRIGGER. The purpose of such selects is to call
  83094. ** user-defined functions that have side effects. We do not care
  83095. ** about the actual results of the select.
  83096. */
  83097. default: {
  83098. assert( eDest==SRT_Discard );
  83099. break;
  83100. }
  83101. #endif
  83102. }
  83103. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  83104. ** there is a sorter, in which case the sorter has already limited
  83105. ** the output for us.
  83106. */
  83107. if( pOrderBy==0 && p->iLimit ){
  83108. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  83109. }
  83110. }
  83111. /*
  83112. ** Allocate a KeyInfo object sufficient for an index of N columns.
  83113. **
  83114. ** Actually, always allocate one extra column for the rowid at the end
  83115. ** of the index. So the KeyInfo returned will have space sufficient for
  83116. ** N+1 columns.
  83117. */
  83118. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
  83119. KeyInfo *p = sqlite3DbMallocZero(db,
  83120. sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
  83121. if( p ){
  83122. p->aSortOrder = (u8*)&p->aColl[N+1];
  83123. p->nField = (u16)N;
  83124. p->enc = ENC(db);
  83125. p->db = db;
  83126. }
  83127. return p;
  83128. }
  83129. /*
  83130. ** Given an expression list, generate a KeyInfo structure that records
  83131. ** the collating sequence for each expression in that expression list.
  83132. **
  83133. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  83134. ** KeyInfo structure is appropriate for initializing a virtual index to
  83135. ** implement that clause. If the ExprList is the result set of a SELECT
  83136. ** then the KeyInfo structure is appropriate for initializing a virtual
  83137. ** index to implement a DISTINCT test.
  83138. **
  83139. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  83140. ** function is responsible for seeing that this structure is eventually
  83141. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  83142. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  83143. */
  83144. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  83145. int nExpr;
  83146. KeyInfo *pInfo;
  83147. struct ExprList_item *pItem;
  83148. sqlite3 *db = pParse->db;
  83149. int i;
  83150. nExpr = pList->nExpr;
  83151. pInfo = sqlite3KeyInfoAlloc(db, nExpr);
  83152. if( pInfo ){
  83153. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  83154. CollSeq *pColl;
  83155. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  83156. if( !pColl ) pColl = db->pDfltColl;
  83157. pInfo->aColl[i] = pColl;
  83158. pInfo->aSortOrder[i] = pItem->sortOrder;
  83159. }
  83160. }
  83161. return pInfo;
  83162. }
  83163. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83164. /*
  83165. ** Name of the connection operator, used for error messages.
  83166. */
  83167. static const char *selectOpName(int id){
  83168. char *z;
  83169. switch( id ){
  83170. case TK_ALL: z = "UNION ALL"; break;
  83171. case TK_INTERSECT: z = "INTERSECT"; break;
  83172. case TK_EXCEPT: z = "EXCEPT"; break;
  83173. default: z = "UNION"; break;
  83174. }
  83175. return z;
  83176. }
  83177. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  83178. #ifndef SQLITE_OMIT_EXPLAIN
  83179. /*
  83180. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  83181. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  83182. ** where the caption is of the form:
  83183. **
  83184. ** "USE TEMP B-TREE FOR xxx"
  83185. **
  83186. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  83187. ** is determined by the zUsage argument.
  83188. */
  83189. static void explainTempTable(Parse *pParse, const char *zUsage){
  83190. if( pParse->explain==2 ){
  83191. Vdbe *v = pParse->pVdbe;
  83192. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  83193. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  83194. }
  83195. }
  83196. /*
  83197. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  83198. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  83199. ** in sqlite3Select() to assign values to structure member variables that
  83200. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  83201. ** code with #ifndef directives.
  83202. */
  83203. # define explainSetInteger(a, b) a = b
  83204. #else
  83205. /* No-op versions of the explainXXX() functions and macros. */
  83206. # define explainTempTable(y,z)
  83207. # define explainSetInteger(y,z)
  83208. #endif
  83209. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  83210. /*
  83211. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  83212. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  83213. ** where the caption is of one of the two forms:
  83214. **
  83215. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  83216. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  83217. **
  83218. ** where iSub1 and iSub2 are the integers passed as the corresponding
  83219. ** function parameters, and op is the text representation of the parameter
  83220. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  83221. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  83222. ** false, or the second form if it is true.
  83223. */
  83224. static void explainComposite(
  83225. Parse *pParse, /* Parse context */
  83226. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  83227. int iSub1, /* Subquery id 1 */
  83228. int iSub2, /* Subquery id 2 */
  83229. int bUseTmp /* True if a temp table was used */
  83230. ){
  83231. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  83232. if( pParse->explain==2 ){
  83233. Vdbe *v = pParse->pVdbe;
  83234. char *zMsg = sqlite3MPrintf(
  83235. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  83236. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  83237. );
  83238. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  83239. }
  83240. }
  83241. #else
  83242. /* No-op versions of the explainXXX() functions and macros. */
  83243. # define explainComposite(v,w,x,y,z)
  83244. #endif
  83245. /*
  83246. ** If the inner loop was generated using a non-null pOrderBy argument,
  83247. ** then the results were placed in a sorter. After the loop is terminated
  83248. ** we need to run the sorter and output the results. The following
  83249. ** routine generates the code needed to do that.
  83250. */
  83251. static void generateSortTail(
  83252. Parse *pParse, /* Parsing context */
  83253. Select *p, /* The SELECT statement */
  83254. Vdbe *v, /* Generate code into this VDBE */
  83255. int nColumn, /* Number of columns of data */
  83256. SelectDest *pDest /* Write the sorted results here */
  83257. ){
  83258. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  83259. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  83260. int addr;
  83261. int iTab;
  83262. int pseudoTab = 0;
  83263. ExprList *pOrderBy = p->pOrderBy;
  83264. int eDest = pDest->eDest;
  83265. int iParm = pDest->iSDParm;
  83266. int regRow;
  83267. int regRowid;
  83268. iTab = pOrderBy->iECursor;
  83269. regRow = sqlite3GetTempReg(pParse);
  83270. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  83271. pseudoTab = pParse->nTab++;
  83272. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  83273. regRowid = 0;
  83274. }else{
  83275. regRowid = sqlite3GetTempReg(pParse);
  83276. }
  83277. if( p->selFlags & SF_UseSorter ){
  83278. int regSortOut = ++pParse->nMem;
  83279. int ptab2 = pParse->nTab++;
  83280. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  83281. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  83282. codeOffset(v, p, addrContinue);
  83283. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  83284. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  83285. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  83286. }else{
  83287. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  83288. codeOffset(v, p, addrContinue);
  83289. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  83290. }
  83291. switch( eDest ){
  83292. case SRT_Table:
  83293. case SRT_EphemTab: {
  83294. testcase( eDest==SRT_Table );
  83295. testcase( eDest==SRT_EphemTab );
  83296. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  83297. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  83298. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83299. break;
  83300. }
  83301. #ifndef SQLITE_OMIT_SUBQUERY
  83302. case SRT_Set: {
  83303. assert( nColumn==1 );
  83304. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  83305. &pDest->affSdst, 1);
  83306. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  83307. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  83308. break;
  83309. }
  83310. case SRT_Mem: {
  83311. assert( nColumn==1 );
  83312. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  83313. /* The LIMIT clause will terminate the loop for us */
  83314. break;
  83315. }
  83316. #endif
  83317. default: {
  83318. int i;
  83319. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  83320. testcase( eDest==SRT_Output );
  83321. testcase( eDest==SRT_Coroutine );
  83322. for(i=0; i<nColumn; i++){
  83323. assert( regRow!=pDest->iSdst+i );
  83324. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  83325. if( i==0 ){
  83326. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  83327. }
  83328. }
  83329. if( eDest==SRT_Output ){
  83330. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  83331. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  83332. }else{
  83333. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  83334. }
  83335. break;
  83336. }
  83337. }
  83338. sqlite3ReleaseTempReg(pParse, regRow);
  83339. sqlite3ReleaseTempReg(pParse, regRowid);
  83340. /* The bottom of the loop
  83341. */
  83342. sqlite3VdbeResolveLabel(v, addrContinue);
  83343. if( p->selFlags & SF_UseSorter ){
  83344. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  83345. }else{
  83346. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  83347. }
  83348. sqlite3VdbeResolveLabel(v, addrBreak);
  83349. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  83350. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  83351. }
  83352. }
  83353. /*
  83354. ** Return a pointer to a string containing the 'declaration type' of the
  83355. ** expression pExpr. The string may be treated as static by the caller.
  83356. **
  83357. ** Also try to estimate the size of the returned value and return that
  83358. ** result in *pEstWidth.
  83359. **
  83360. ** The declaration type is the exact datatype definition extracted from the
  83361. ** original CREATE TABLE statement if the expression is a column. The
  83362. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  83363. ** is considered a column can be complex in the presence of subqueries. The
  83364. ** result-set expression in all of the following SELECT statements is
  83365. ** considered a column by this function.
  83366. **
  83367. ** SELECT col FROM tbl;
  83368. ** SELECT (SELECT col FROM tbl;
  83369. ** SELECT (SELECT col FROM tbl);
  83370. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  83371. **
  83372. ** The declaration type for any expression other than a column is NULL.
  83373. **
  83374. ** This routine has either 3 or 6 parameters depending on whether or not
  83375. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  83376. */
  83377. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83378. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  83379. static const char *columnTypeImpl(
  83380. NameContext *pNC,
  83381. Expr *pExpr,
  83382. const char **pzOrigDb,
  83383. const char **pzOrigTab,
  83384. const char **pzOrigCol,
  83385. u8 *pEstWidth
  83386. ){
  83387. char const *zOrigDb = 0;
  83388. char const *zOrigTab = 0;
  83389. char const *zOrigCol = 0;
  83390. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  83391. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  83392. static const char *columnTypeImpl(
  83393. NameContext *pNC,
  83394. Expr *pExpr,
  83395. u8 *pEstWidth
  83396. ){
  83397. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  83398. char const *zType = 0;
  83399. int j;
  83400. u8 estWidth = 1;
  83401. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  83402. switch( pExpr->op ){
  83403. case TK_AGG_COLUMN:
  83404. case TK_COLUMN: {
  83405. /* The expression is a column. Locate the table the column is being
  83406. ** extracted from in NameContext.pSrcList. This table may be real
  83407. ** database table or a subquery.
  83408. */
  83409. Table *pTab = 0; /* Table structure column is extracted from */
  83410. Select *pS = 0; /* Select the column is extracted from */
  83411. int iCol = pExpr->iColumn; /* Index of column in pTab */
  83412. testcase( pExpr->op==TK_AGG_COLUMN );
  83413. testcase( pExpr->op==TK_COLUMN );
  83414. while( pNC && !pTab ){
  83415. SrcList *pTabList = pNC->pSrcList;
  83416. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  83417. if( j<pTabList->nSrc ){
  83418. pTab = pTabList->a[j].pTab;
  83419. pS = pTabList->a[j].pSelect;
  83420. }else{
  83421. pNC = pNC->pNext;
  83422. }
  83423. }
  83424. if( pTab==0 ){
  83425. /* At one time, code such as "SELECT new.x" within a trigger would
  83426. ** cause this condition to run. Since then, we have restructured how
  83427. ** trigger code is generated and so this condition is no longer
  83428. ** possible. However, it can still be true for statements like
  83429. ** the following:
  83430. **
  83431. ** CREATE TABLE t1(col INTEGER);
  83432. ** SELECT (SELECT t1.col) FROM FROM t1;
  83433. **
  83434. ** when columnType() is called on the expression "t1.col" in the
  83435. ** sub-select. In this case, set the column type to NULL, even
  83436. ** though it should really be "INTEGER".
  83437. **
  83438. ** This is not a problem, as the column type of "t1.col" is never
  83439. ** used. When columnType() is called on the expression
  83440. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  83441. ** branch below. */
  83442. break;
  83443. }
  83444. assert( pTab && pExpr->pTab==pTab );
  83445. if( pS ){
  83446. /* The "table" is actually a sub-select or a view in the FROM clause
  83447. ** of the SELECT statement. Return the declaration type and origin
  83448. ** data for the result-set column of the sub-select.
  83449. */
  83450. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  83451. /* If iCol is less than zero, then the expression requests the
  83452. ** rowid of the sub-select or view. This expression is legal (see
  83453. ** test case misc2.2.2) - it always evaluates to NULL.
  83454. */
  83455. NameContext sNC;
  83456. Expr *p = pS->pEList->a[iCol].pExpr;
  83457. sNC.pSrcList = pS->pSrc;
  83458. sNC.pNext = pNC;
  83459. sNC.pParse = pNC->pParse;
  83460. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  83461. }
  83462. }else if( ALWAYS(pTab->pSchema) ){
  83463. /* A real table */
  83464. assert( !pS );
  83465. if( iCol<0 ) iCol = pTab->iPKey;
  83466. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  83467. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83468. if( iCol<0 ){
  83469. zType = "INTEGER";
  83470. zOrigCol = "rowid";
  83471. }else{
  83472. zType = pTab->aCol[iCol].zType;
  83473. zOrigCol = pTab->aCol[iCol].zName;
  83474. estWidth = pTab->aCol[iCol].szEst;
  83475. }
  83476. zOrigTab = pTab->zName;
  83477. if( pNC->pParse ){
  83478. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  83479. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  83480. }
  83481. #else
  83482. if( iCol<0 ){
  83483. zType = "INTEGER";
  83484. }else{
  83485. zType = pTab->aCol[iCol].zType;
  83486. estWidth = pTab->aCol[iCol].szEst;
  83487. }
  83488. #endif
  83489. }
  83490. break;
  83491. }
  83492. #ifndef SQLITE_OMIT_SUBQUERY
  83493. case TK_SELECT: {
  83494. /* The expression is a sub-select. Return the declaration type and
  83495. ** origin info for the single column in the result set of the SELECT
  83496. ** statement.
  83497. */
  83498. NameContext sNC;
  83499. Select *pS = pExpr->x.pSelect;
  83500. Expr *p = pS->pEList->a[0].pExpr;
  83501. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  83502. sNC.pSrcList = pS->pSrc;
  83503. sNC.pNext = pNC;
  83504. sNC.pParse = pNC->pParse;
  83505. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  83506. break;
  83507. }
  83508. #endif
  83509. }
  83510. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83511. if( pzOrigDb ){
  83512. assert( pzOrigTab && pzOrigCol );
  83513. *pzOrigDb = zOrigDb;
  83514. *pzOrigTab = zOrigTab;
  83515. *pzOrigCol = zOrigCol;
  83516. }
  83517. #endif
  83518. if( pEstWidth ) *pEstWidth = estWidth;
  83519. return zType;
  83520. }
  83521. /*
  83522. ** Generate code that will tell the VDBE the declaration types of columns
  83523. ** in the result set.
  83524. */
  83525. static void generateColumnTypes(
  83526. Parse *pParse, /* Parser context */
  83527. SrcList *pTabList, /* List of tables */
  83528. ExprList *pEList /* Expressions defining the result set */
  83529. ){
  83530. #ifndef SQLITE_OMIT_DECLTYPE
  83531. Vdbe *v = pParse->pVdbe;
  83532. int i;
  83533. NameContext sNC;
  83534. sNC.pSrcList = pTabList;
  83535. sNC.pParse = pParse;
  83536. for(i=0; i<pEList->nExpr; i++){
  83537. Expr *p = pEList->a[i].pExpr;
  83538. const char *zType;
  83539. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83540. const char *zOrigDb = 0;
  83541. const char *zOrigTab = 0;
  83542. const char *zOrigCol = 0;
  83543. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  83544. /* The vdbe must make its own copy of the column-type and other
  83545. ** column specific strings, in case the schema is reset before this
  83546. ** virtual machine is deleted.
  83547. */
  83548. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  83549. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  83550. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  83551. #else
  83552. zType = columnType(&sNC, p, 0, 0, 0, 0);
  83553. #endif
  83554. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  83555. }
  83556. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  83557. }
  83558. /*
  83559. ** Generate code that will tell the VDBE the names of columns
  83560. ** in the result set. This information is used to provide the
  83561. ** azCol[] values in the callback.
  83562. */
  83563. static void generateColumnNames(
  83564. Parse *pParse, /* Parser context */
  83565. SrcList *pTabList, /* List of tables */
  83566. ExprList *pEList /* Expressions defining the result set */
  83567. ){
  83568. Vdbe *v = pParse->pVdbe;
  83569. int i, j;
  83570. sqlite3 *db = pParse->db;
  83571. int fullNames, shortNames;
  83572. #ifndef SQLITE_OMIT_EXPLAIN
  83573. /* If this is an EXPLAIN, skip this step */
  83574. if( pParse->explain ){
  83575. return;
  83576. }
  83577. #endif
  83578. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  83579. pParse->colNamesSet = 1;
  83580. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  83581. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  83582. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  83583. for(i=0; i<pEList->nExpr; i++){
  83584. Expr *p;
  83585. p = pEList->a[i].pExpr;
  83586. if( NEVER(p==0) ) continue;
  83587. if( pEList->a[i].zName ){
  83588. char *zName = pEList->a[i].zName;
  83589. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  83590. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  83591. Table *pTab;
  83592. char *zCol;
  83593. int iCol = p->iColumn;
  83594. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  83595. if( pTabList->a[j].iCursor==p->iTable ) break;
  83596. }
  83597. assert( j<pTabList->nSrc );
  83598. pTab = pTabList->a[j].pTab;
  83599. if( iCol<0 ) iCol = pTab->iPKey;
  83600. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  83601. if( iCol<0 ){
  83602. zCol = "rowid";
  83603. }else{
  83604. zCol = pTab->aCol[iCol].zName;
  83605. }
  83606. if( !shortNames && !fullNames ){
  83607. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  83608. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  83609. }else if( fullNames ){
  83610. char *zName = 0;
  83611. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  83612. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  83613. }else{
  83614. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  83615. }
  83616. }else{
  83617. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  83618. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  83619. }
  83620. }
  83621. generateColumnTypes(pParse, pTabList, pEList);
  83622. }
  83623. /*
  83624. ** Given a an expression list (which is really the list of expressions
  83625. ** that form the result set of a SELECT statement) compute appropriate
  83626. ** column names for a table that would hold the expression list.
  83627. **
  83628. ** All column names will be unique.
  83629. **
  83630. ** Only the column names are computed. Column.zType, Column.zColl,
  83631. ** and other fields of Column are zeroed.
  83632. **
  83633. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  83634. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  83635. */
  83636. static int selectColumnsFromExprList(
  83637. Parse *pParse, /* Parsing context */
  83638. ExprList *pEList, /* Expr list from which to derive column names */
  83639. i16 *pnCol, /* Write the number of columns here */
  83640. Column **paCol /* Write the new column list here */
  83641. ){
  83642. sqlite3 *db = pParse->db; /* Database connection */
  83643. int i, j; /* Loop counters */
  83644. int cnt; /* Index added to make the name unique */
  83645. Column *aCol, *pCol; /* For looping over result columns */
  83646. int nCol; /* Number of columns in the result set */
  83647. Expr *p; /* Expression for a single result column */
  83648. char *zName; /* Column name */
  83649. int nName; /* Size of name in zName[] */
  83650. if( pEList ){
  83651. nCol = pEList->nExpr;
  83652. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  83653. testcase( aCol==0 );
  83654. }else{
  83655. nCol = 0;
  83656. aCol = 0;
  83657. }
  83658. *pnCol = nCol;
  83659. *paCol = aCol;
  83660. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  83661. /* Get an appropriate name for the column
  83662. */
  83663. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  83664. if( (zName = pEList->a[i].zName)!=0 ){
  83665. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  83666. zName = sqlite3DbStrDup(db, zName);
  83667. }else{
  83668. Expr *pColExpr = p; /* The expression that is the result column name */
  83669. Table *pTab; /* Table associated with this expression */
  83670. while( pColExpr->op==TK_DOT ){
  83671. pColExpr = pColExpr->pRight;
  83672. assert( pColExpr!=0 );
  83673. }
  83674. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  83675. /* For columns use the column name name */
  83676. int iCol = pColExpr->iColumn;
  83677. pTab = pColExpr->pTab;
  83678. if( iCol<0 ) iCol = pTab->iPKey;
  83679. zName = sqlite3MPrintf(db, "%s",
  83680. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  83681. }else if( pColExpr->op==TK_ID ){
  83682. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  83683. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  83684. }else{
  83685. /* Use the original text of the column expression as its name */
  83686. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  83687. }
  83688. }
  83689. if( db->mallocFailed ){
  83690. sqlite3DbFree(db, zName);
  83691. break;
  83692. }
  83693. /* Make sure the column name is unique. If the name is not unique,
  83694. ** append a integer to the name so that it becomes unique.
  83695. */
  83696. nName = sqlite3Strlen30(zName);
  83697. for(j=cnt=0; j<i; j++){
  83698. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  83699. char *zNewName;
  83700. int k;
  83701. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  83702. if( zName[k]==':' ) nName = k;
  83703. zName[nName] = 0;
  83704. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  83705. sqlite3DbFree(db, zName);
  83706. zName = zNewName;
  83707. j = -1;
  83708. if( zName==0 ) break;
  83709. }
  83710. }
  83711. pCol->zName = zName;
  83712. }
  83713. if( db->mallocFailed ){
  83714. for(j=0; j<i; j++){
  83715. sqlite3DbFree(db, aCol[j].zName);
  83716. }
  83717. sqlite3DbFree(db, aCol);
  83718. *paCol = 0;
  83719. *pnCol = 0;
  83720. return SQLITE_NOMEM;
  83721. }
  83722. return SQLITE_OK;
  83723. }
  83724. /*
  83725. ** Add type and collation information to a column list based on
  83726. ** a SELECT statement.
  83727. **
  83728. ** The column list presumably came from selectColumnNamesFromExprList().
  83729. ** The column list has only names, not types or collations. This
  83730. ** routine goes through and adds the types and collations.
  83731. **
  83732. ** This routine requires that all identifiers in the SELECT
  83733. ** statement be resolved.
  83734. */
  83735. static void selectAddColumnTypeAndCollation(
  83736. Parse *pParse, /* Parsing contexts */
  83737. Table *pTab, /* Add column type information to this table */
  83738. Select *pSelect /* SELECT used to determine types and collations */
  83739. ){
  83740. sqlite3 *db = pParse->db;
  83741. NameContext sNC;
  83742. Column *pCol;
  83743. CollSeq *pColl;
  83744. int i;
  83745. Expr *p;
  83746. struct ExprList_item *a;
  83747. u64 szAll = 0;
  83748. assert( pSelect!=0 );
  83749. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  83750. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  83751. if( db->mallocFailed ) return;
  83752. memset(&sNC, 0, sizeof(sNC));
  83753. sNC.pSrcList = pSelect->pSrc;
  83754. a = pSelect->pEList->a;
  83755. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  83756. p = a[i].pExpr;
  83757. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  83758. szAll += pCol->szEst;
  83759. pCol->affinity = sqlite3ExprAffinity(p);
  83760. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  83761. pColl = sqlite3ExprCollSeq(pParse, p);
  83762. if( pColl ){
  83763. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  83764. }
  83765. }
  83766. pTab->szTabRow = sqlite3LogEst(szAll*4);
  83767. }
  83768. /*
  83769. ** Given a SELECT statement, generate a Table structure that describes
  83770. ** the result set of that SELECT.
  83771. */
  83772. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  83773. Table *pTab;
  83774. sqlite3 *db = pParse->db;
  83775. int savedFlags;
  83776. savedFlags = db->flags;
  83777. db->flags &= ~SQLITE_FullColNames;
  83778. db->flags |= SQLITE_ShortColNames;
  83779. sqlite3SelectPrep(pParse, pSelect, 0);
  83780. if( pParse->nErr ) return 0;
  83781. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  83782. db->flags = savedFlags;
  83783. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  83784. if( pTab==0 ){
  83785. return 0;
  83786. }
  83787. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  83788. ** is disabled */
  83789. assert( db->lookaside.bEnabled==0 );
  83790. pTab->nRef = 1;
  83791. pTab->zName = 0;
  83792. pTab->nRowEst = 1048576;
  83793. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  83794. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  83795. pTab->iPKey = -1;
  83796. if( db->mallocFailed ){
  83797. sqlite3DeleteTable(db, pTab);
  83798. return 0;
  83799. }
  83800. return pTab;
  83801. }
  83802. /*
  83803. ** Get a VDBE for the given parser context. Create a new one if necessary.
  83804. ** If an error occurs, return NULL and leave a message in pParse.
  83805. */
  83806. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  83807. Vdbe *v = pParse->pVdbe;
  83808. if( v==0 ){
  83809. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  83810. #ifndef SQLITE_OMIT_TRACE
  83811. if( v ){
  83812. sqlite3VdbeAddOp0(v, OP_Trace);
  83813. }
  83814. #endif
  83815. }
  83816. return v;
  83817. }
  83818. /*
  83819. ** Compute the iLimit and iOffset fields of the SELECT based on the
  83820. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  83821. ** that appear in the original SQL statement after the LIMIT and OFFSET
  83822. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  83823. ** are the integer memory register numbers for counters used to compute
  83824. ** the limit and offset. If there is no limit and/or offset, then
  83825. ** iLimit and iOffset are negative.
  83826. **
  83827. ** This routine changes the values of iLimit and iOffset only if
  83828. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  83829. ** iOffset should have been preset to appropriate default values
  83830. ** (usually but not always -1) prior to calling this routine.
  83831. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  83832. ** redefined. The UNION ALL operator uses this property to force
  83833. ** the reuse of the same limit and offset registers across multiple
  83834. ** SELECT statements.
  83835. */
  83836. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  83837. Vdbe *v = 0;
  83838. int iLimit = 0;
  83839. int iOffset;
  83840. int addr1, n;
  83841. if( p->iLimit ) return;
  83842. /*
  83843. ** "LIMIT -1" always shows all rows. There is some
  83844. ** controversy about what the correct behavior should be.
  83845. ** The current implementation interprets "LIMIT 0" to mean
  83846. ** no rows.
  83847. */
  83848. sqlite3ExprCacheClear(pParse);
  83849. assert( p->pOffset==0 || p->pLimit!=0 );
  83850. if( p->pLimit ){
  83851. p->iLimit = iLimit = ++pParse->nMem;
  83852. v = sqlite3GetVdbe(pParse);
  83853. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  83854. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  83855. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  83856. VdbeComment((v, "LIMIT counter"));
  83857. if( n==0 ){
  83858. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  83859. }else if( n>=0 && p->nSelectRow>(u64)n ){
  83860. p->nSelectRow = n;
  83861. }
  83862. }else{
  83863. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  83864. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  83865. VdbeComment((v, "LIMIT counter"));
  83866. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  83867. }
  83868. if( p->pOffset ){
  83869. p->iOffset = iOffset = ++pParse->nMem;
  83870. pParse->nMem++; /* Allocate an extra register for limit+offset */
  83871. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  83872. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  83873. VdbeComment((v, "OFFSET counter"));
  83874. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  83875. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  83876. sqlite3VdbeJumpHere(v, addr1);
  83877. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  83878. VdbeComment((v, "LIMIT+OFFSET"));
  83879. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  83880. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  83881. sqlite3VdbeJumpHere(v, addr1);
  83882. }
  83883. }
  83884. }
  83885. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83886. /*
  83887. ** Return the appropriate collating sequence for the iCol-th column of
  83888. ** the result set for the compound-select statement "p". Return NULL if
  83889. ** the column has no default collating sequence.
  83890. **
  83891. ** The collating sequence for the compound select is taken from the
  83892. ** left-most term of the select that has a collating sequence.
  83893. */
  83894. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  83895. CollSeq *pRet;
  83896. if( p->pPrior ){
  83897. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  83898. }else{
  83899. pRet = 0;
  83900. }
  83901. assert( iCol>=0 );
  83902. if( pRet==0 && iCol<p->pEList->nExpr ){
  83903. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  83904. }
  83905. return pRet;
  83906. }
  83907. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  83908. /* Forward reference */
  83909. static int multiSelectOrderBy(
  83910. Parse *pParse, /* Parsing context */
  83911. Select *p, /* The right-most of SELECTs to be coded */
  83912. SelectDest *pDest /* What to do with query results */
  83913. );
  83914. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83915. /*
  83916. ** This routine is called to process a compound query form from
  83917. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  83918. ** INTERSECT
  83919. **
  83920. ** "p" points to the right-most of the two queries. the query on the
  83921. ** left is p->pPrior. The left query could also be a compound query
  83922. ** in which case this routine will be called recursively.
  83923. **
  83924. ** The results of the total query are to be written into a destination
  83925. ** of type eDest with parameter iParm.
  83926. **
  83927. ** Example 1: Consider a three-way compound SQL statement.
  83928. **
  83929. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  83930. **
  83931. ** This statement is parsed up as follows:
  83932. **
  83933. ** SELECT c FROM t3
  83934. ** |
  83935. ** `-----> SELECT b FROM t2
  83936. ** |
  83937. ** `------> SELECT a FROM t1
  83938. **
  83939. ** The arrows in the diagram above represent the Select.pPrior pointer.
  83940. ** So if this routine is called with p equal to the t3 query, then
  83941. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  83942. **
  83943. ** Notice that because of the way SQLite parses compound SELECTs, the
  83944. ** individual selects always group from left to right.
  83945. */
  83946. static int multiSelect(
  83947. Parse *pParse, /* Parsing context */
  83948. Select *p, /* The right-most of SELECTs to be coded */
  83949. SelectDest *pDest /* What to do with query results */
  83950. ){
  83951. int rc = SQLITE_OK; /* Success code from a subroutine */
  83952. Select *pPrior; /* Another SELECT immediately to our left */
  83953. Vdbe *v; /* Generate code to this VDBE */
  83954. SelectDest dest; /* Alternative data destination */
  83955. Select *pDelete = 0; /* Chain of simple selects to delete */
  83956. sqlite3 *db; /* Database connection */
  83957. #ifndef SQLITE_OMIT_EXPLAIN
  83958. int iSub1; /* EQP id of left-hand query */
  83959. int iSub2; /* EQP id of right-hand query */
  83960. #endif
  83961. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  83962. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  83963. */
  83964. assert( p && p->pPrior ); /* Calling function guarantees this much */
  83965. db = pParse->db;
  83966. pPrior = p->pPrior;
  83967. assert( pPrior->pRightmost!=pPrior );
  83968. assert( pPrior->pRightmost==p->pRightmost );
  83969. dest = *pDest;
  83970. if( pPrior->pOrderBy ){
  83971. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  83972. selectOpName(p->op));
  83973. rc = 1;
  83974. goto multi_select_end;
  83975. }
  83976. if( pPrior->pLimit ){
  83977. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  83978. selectOpName(p->op));
  83979. rc = 1;
  83980. goto multi_select_end;
  83981. }
  83982. v = sqlite3GetVdbe(pParse);
  83983. assert( v!=0 ); /* The VDBE already created by calling function */
  83984. /* Create the destination temporary table if necessary
  83985. */
  83986. if( dest.eDest==SRT_EphemTab ){
  83987. assert( p->pEList );
  83988. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  83989. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  83990. dest.eDest = SRT_Table;
  83991. }
  83992. /* Make sure all SELECTs in the statement have the same number of elements
  83993. ** in their result sets.
  83994. */
  83995. assert( p->pEList && pPrior->pEList );
  83996. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  83997. if( p->selFlags & SF_Values ){
  83998. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  83999. }else{
  84000. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  84001. " do not have the same number of result columns", selectOpName(p->op));
  84002. }
  84003. rc = 1;
  84004. goto multi_select_end;
  84005. }
  84006. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  84007. */
  84008. if( p->pOrderBy ){
  84009. return multiSelectOrderBy(pParse, p, pDest);
  84010. }
  84011. /* Generate code for the left and right SELECT statements.
  84012. */
  84013. switch( p->op ){
  84014. case TK_ALL: {
  84015. int addr = 0;
  84016. int nLimit;
  84017. assert( !pPrior->pLimit );
  84018. pPrior->iLimit = p->iLimit;
  84019. pPrior->iOffset = p->iOffset;
  84020. pPrior->pLimit = p->pLimit;
  84021. pPrior->pOffset = p->pOffset;
  84022. explainSetInteger(iSub1, pParse->iNextSelectId);
  84023. rc = sqlite3Select(pParse, pPrior, &dest);
  84024. p->pLimit = 0;
  84025. p->pOffset = 0;
  84026. if( rc ){
  84027. goto multi_select_end;
  84028. }
  84029. p->pPrior = 0;
  84030. p->iLimit = pPrior->iLimit;
  84031. p->iOffset = pPrior->iOffset;
  84032. if( p->iLimit ){
  84033. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  84034. VdbeComment((v, "Jump ahead if LIMIT reached"));
  84035. }
  84036. explainSetInteger(iSub2, pParse->iNextSelectId);
  84037. rc = sqlite3Select(pParse, p, &dest);
  84038. testcase( rc!=SQLITE_OK );
  84039. pDelete = p->pPrior;
  84040. p->pPrior = pPrior;
  84041. p->nSelectRow += pPrior->nSelectRow;
  84042. if( pPrior->pLimit
  84043. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  84044. && nLimit>0 && p->nSelectRow > (u64)nLimit
  84045. ){
  84046. p->nSelectRow = nLimit;
  84047. }
  84048. if( addr ){
  84049. sqlite3VdbeJumpHere(v, addr);
  84050. }
  84051. break;
  84052. }
  84053. case TK_EXCEPT:
  84054. case TK_UNION: {
  84055. int unionTab; /* Cursor number of the temporary table holding result */
  84056. u8 op = 0; /* One of the SRT_ operations to apply to self */
  84057. int priorOp; /* The SRT_ operation to apply to prior selects */
  84058. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  84059. int addr;
  84060. SelectDest uniondest;
  84061. testcase( p->op==TK_EXCEPT );
  84062. testcase( p->op==TK_UNION );
  84063. priorOp = SRT_Union;
  84064. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  84065. /* We can reuse a temporary table generated by a SELECT to our
  84066. ** right.
  84067. */
  84068. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  84069. ** of a 3-way or more compound */
  84070. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  84071. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  84072. unionTab = dest.iSDParm;
  84073. }else{
  84074. /* We will need to create our own temporary table to hold the
  84075. ** intermediate results.
  84076. */
  84077. unionTab = pParse->nTab++;
  84078. assert( p->pOrderBy==0 );
  84079. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  84080. assert( p->addrOpenEphm[0] == -1 );
  84081. p->addrOpenEphm[0] = addr;
  84082. p->pRightmost->selFlags |= SF_UsesEphemeral;
  84083. assert( p->pEList );
  84084. }
  84085. /* Code the SELECT statements to our left
  84086. */
  84087. assert( !pPrior->pOrderBy );
  84088. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  84089. explainSetInteger(iSub1, pParse->iNextSelectId);
  84090. rc = sqlite3Select(pParse, pPrior, &uniondest);
  84091. if( rc ){
  84092. goto multi_select_end;
  84093. }
  84094. /* Code the current SELECT statement
  84095. */
  84096. if( p->op==TK_EXCEPT ){
  84097. op = SRT_Except;
  84098. }else{
  84099. assert( p->op==TK_UNION );
  84100. op = SRT_Union;
  84101. }
  84102. p->pPrior = 0;
  84103. pLimit = p->pLimit;
  84104. p->pLimit = 0;
  84105. pOffset = p->pOffset;
  84106. p->pOffset = 0;
  84107. uniondest.eDest = op;
  84108. explainSetInteger(iSub2, pParse->iNextSelectId);
  84109. rc = sqlite3Select(pParse, p, &uniondest);
  84110. testcase( rc!=SQLITE_OK );
  84111. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  84112. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  84113. sqlite3ExprListDelete(db, p->pOrderBy);
  84114. pDelete = p->pPrior;
  84115. p->pPrior = pPrior;
  84116. p->pOrderBy = 0;
  84117. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  84118. sqlite3ExprDelete(db, p->pLimit);
  84119. p->pLimit = pLimit;
  84120. p->pOffset = pOffset;
  84121. p->iLimit = 0;
  84122. p->iOffset = 0;
  84123. /* Convert the data in the temporary table into whatever form
  84124. ** it is that we currently need.
  84125. */
  84126. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  84127. if( dest.eDest!=priorOp ){
  84128. int iCont, iBreak, iStart;
  84129. assert( p->pEList );
  84130. if( dest.eDest==SRT_Output ){
  84131. Select *pFirst = p;
  84132. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84133. generateColumnNames(pParse, 0, pFirst->pEList);
  84134. }
  84135. iBreak = sqlite3VdbeMakeLabel(v);
  84136. iCont = sqlite3VdbeMakeLabel(v);
  84137. computeLimitRegisters(pParse, p, iBreak);
  84138. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  84139. iStart = sqlite3VdbeCurrentAddr(v);
  84140. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  84141. 0, 0, &dest, iCont, iBreak);
  84142. sqlite3VdbeResolveLabel(v, iCont);
  84143. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  84144. sqlite3VdbeResolveLabel(v, iBreak);
  84145. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  84146. }
  84147. break;
  84148. }
  84149. default: assert( p->op==TK_INTERSECT ); {
  84150. int tab1, tab2;
  84151. int iCont, iBreak, iStart;
  84152. Expr *pLimit, *pOffset;
  84153. int addr;
  84154. SelectDest intersectdest;
  84155. int r1;
  84156. /* INTERSECT is different from the others since it requires
  84157. ** two temporary tables. Hence it has its own case. Begin
  84158. ** by allocating the tables we will need.
  84159. */
  84160. tab1 = pParse->nTab++;
  84161. tab2 = pParse->nTab++;
  84162. assert( p->pOrderBy==0 );
  84163. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  84164. assert( p->addrOpenEphm[0] == -1 );
  84165. p->addrOpenEphm[0] = addr;
  84166. p->pRightmost->selFlags |= SF_UsesEphemeral;
  84167. assert( p->pEList );
  84168. /* Code the SELECTs to our left into temporary table "tab1".
  84169. */
  84170. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  84171. explainSetInteger(iSub1, pParse->iNextSelectId);
  84172. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  84173. if( rc ){
  84174. goto multi_select_end;
  84175. }
  84176. /* Code the current SELECT into temporary table "tab2"
  84177. */
  84178. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  84179. assert( p->addrOpenEphm[1] == -1 );
  84180. p->addrOpenEphm[1] = addr;
  84181. p->pPrior = 0;
  84182. pLimit = p->pLimit;
  84183. p->pLimit = 0;
  84184. pOffset = p->pOffset;
  84185. p->pOffset = 0;
  84186. intersectdest.iSDParm = tab2;
  84187. explainSetInteger(iSub2, pParse->iNextSelectId);
  84188. rc = sqlite3Select(pParse, p, &intersectdest);
  84189. testcase( rc!=SQLITE_OK );
  84190. pDelete = p->pPrior;
  84191. p->pPrior = pPrior;
  84192. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  84193. sqlite3ExprDelete(db, p->pLimit);
  84194. p->pLimit = pLimit;
  84195. p->pOffset = pOffset;
  84196. /* Generate code to take the intersection of the two temporary
  84197. ** tables.
  84198. */
  84199. assert( p->pEList );
  84200. if( dest.eDest==SRT_Output ){
  84201. Select *pFirst = p;
  84202. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84203. generateColumnNames(pParse, 0, pFirst->pEList);
  84204. }
  84205. iBreak = sqlite3VdbeMakeLabel(v);
  84206. iCont = sqlite3VdbeMakeLabel(v);
  84207. computeLimitRegisters(pParse, p, iBreak);
  84208. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  84209. r1 = sqlite3GetTempReg(pParse);
  84210. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  84211. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  84212. sqlite3ReleaseTempReg(pParse, r1);
  84213. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  84214. 0, 0, &dest, iCont, iBreak);
  84215. sqlite3VdbeResolveLabel(v, iCont);
  84216. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  84217. sqlite3VdbeResolveLabel(v, iBreak);
  84218. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  84219. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  84220. break;
  84221. }
  84222. }
  84223. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  84224. /* Compute collating sequences used by
  84225. ** temporary tables needed to implement the compound select.
  84226. ** Attach the KeyInfo structure to all temporary tables.
  84227. **
  84228. ** This section is run by the right-most SELECT statement only.
  84229. ** SELECT statements to the left always skip this part. The right-most
  84230. ** SELECT might also skip this part if it has no ORDER BY clause and
  84231. ** no temp tables are required.
  84232. */
  84233. if( p->selFlags & SF_UsesEphemeral ){
  84234. int i; /* Loop counter */
  84235. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  84236. Select *pLoop; /* For looping through SELECT statements */
  84237. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  84238. int nCol; /* Number of columns in result set */
  84239. assert( p->pRightmost==p );
  84240. nCol = p->pEList->nExpr;
  84241. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  84242. if( !pKeyInfo ){
  84243. rc = SQLITE_NOMEM;
  84244. goto multi_select_end;
  84245. }
  84246. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  84247. *apColl = multiSelectCollSeq(pParse, p, i);
  84248. if( 0==*apColl ){
  84249. *apColl = db->pDfltColl;
  84250. }
  84251. }
  84252. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  84253. for(i=0; i<2; i++){
  84254. int addr = pLoop->addrOpenEphm[i];
  84255. if( addr<0 ){
  84256. /* If [0] is unused then [1] is also unused. So we can
  84257. ** always safely abort as soon as the first unused slot is found */
  84258. assert( pLoop->addrOpenEphm[1]<0 );
  84259. break;
  84260. }
  84261. sqlite3VdbeChangeP2(v, addr, nCol);
  84262. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  84263. pLoop->addrOpenEphm[i] = -1;
  84264. }
  84265. }
  84266. sqlite3DbFree(db, pKeyInfo);
  84267. }
  84268. multi_select_end:
  84269. pDest->iSdst = dest.iSdst;
  84270. pDest->nSdst = dest.nSdst;
  84271. sqlite3SelectDelete(db, pDelete);
  84272. return rc;
  84273. }
  84274. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  84275. /*
  84276. ** Code an output subroutine for a coroutine implementation of a
  84277. ** SELECT statment.
  84278. **
  84279. ** The data to be output is contained in pIn->iSdst. There are
  84280. ** pIn->nSdst columns to be output. pDest is where the output should
  84281. ** be sent.
  84282. **
  84283. ** regReturn is the number of the register holding the subroutine
  84284. ** return address.
  84285. **
  84286. ** If regPrev>0 then it is the first register in a vector that
  84287. ** records the previous output. mem[regPrev] is a flag that is false
  84288. ** if there has been no previous output. If regPrev>0 then code is
  84289. ** generated to suppress duplicates. pKeyInfo is used for comparing
  84290. ** keys.
  84291. **
  84292. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  84293. ** iBreak.
  84294. */
  84295. static int generateOutputSubroutine(
  84296. Parse *pParse, /* Parsing context */
  84297. Select *p, /* The SELECT statement */
  84298. SelectDest *pIn, /* Coroutine supplying data */
  84299. SelectDest *pDest, /* Where to send the data */
  84300. int regReturn, /* The return address register */
  84301. int regPrev, /* Previous result register. No uniqueness if 0 */
  84302. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  84303. int p4type, /* The p4 type for pKeyInfo */
  84304. int iBreak /* Jump here if we hit the LIMIT */
  84305. ){
  84306. Vdbe *v = pParse->pVdbe;
  84307. int iContinue;
  84308. int addr;
  84309. addr = sqlite3VdbeCurrentAddr(v);
  84310. iContinue = sqlite3VdbeMakeLabel(v);
  84311. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  84312. */
  84313. if( regPrev ){
  84314. int j1, j2;
  84315. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  84316. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  84317. (char*)pKeyInfo, p4type);
  84318. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  84319. sqlite3VdbeJumpHere(v, j1);
  84320. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  84321. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  84322. }
  84323. if( pParse->db->mallocFailed ) return 0;
  84324. /* Suppress the first OFFSET entries if there is an OFFSET clause
  84325. */
  84326. codeOffset(v, p, iContinue);
  84327. switch( pDest->eDest ){
  84328. /* Store the result as data using a unique key.
  84329. */
  84330. case SRT_Table:
  84331. case SRT_EphemTab: {
  84332. int r1 = sqlite3GetTempReg(pParse);
  84333. int r2 = sqlite3GetTempReg(pParse);
  84334. testcase( pDest->eDest==SRT_Table );
  84335. testcase( pDest->eDest==SRT_EphemTab );
  84336. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  84337. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  84338. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  84339. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84340. sqlite3ReleaseTempReg(pParse, r2);
  84341. sqlite3ReleaseTempReg(pParse, r1);
  84342. break;
  84343. }
  84344. #ifndef SQLITE_OMIT_SUBQUERY
  84345. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  84346. ** then there should be a single item on the stack. Write this
  84347. ** item into the set table with bogus data.
  84348. */
  84349. case SRT_Set: {
  84350. int r1;
  84351. assert( pIn->nSdst==1 );
  84352. pDest->affSdst =
  84353. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  84354. r1 = sqlite3GetTempReg(pParse);
  84355. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  84356. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  84357. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  84358. sqlite3ReleaseTempReg(pParse, r1);
  84359. break;
  84360. }
  84361. #if 0 /* Never occurs on an ORDER BY query */
  84362. /* If any row exist in the result set, record that fact and abort.
  84363. */
  84364. case SRT_Exists: {
  84365. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  84366. /* The LIMIT clause will terminate the loop for us */
  84367. break;
  84368. }
  84369. #endif
  84370. /* If this is a scalar select that is part of an expression, then
  84371. ** store the results in the appropriate memory cell and break out
  84372. ** of the scan loop.
  84373. */
  84374. case SRT_Mem: {
  84375. assert( pIn->nSdst==1 );
  84376. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  84377. /* The LIMIT clause will jump out of the loop for us */
  84378. break;
  84379. }
  84380. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  84381. /* The results are stored in a sequence of registers
  84382. ** starting at pDest->iSdst. Then the co-routine yields.
  84383. */
  84384. case SRT_Coroutine: {
  84385. if( pDest->iSdst==0 ){
  84386. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  84387. pDest->nSdst = pIn->nSdst;
  84388. }
  84389. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  84390. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  84391. break;
  84392. }
  84393. /* If none of the above, then the result destination must be
  84394. ** SRT_Output. This routine is never called with any other
  84395. ** destination other than the ones handled above or SRT_Output.
  84396. **
  84397. ** For SRT_Output, results are stored in a sequence of registers.
  84398. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  84399. ** return the next row of result.
  84400. */
  84401. default: {
  84402. assert( pDest->eDest==SRT_Output );
  84403. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  84404. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  84405. break;
  84406. }
  84407. }
  84408. /* Jump to the end of the loop if the LIMIT is reached.
  84409. */
  84410. if( p->iLimit ){
  84411. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  84412. }
  84413. /* Generate the subroutine return
  84414. */
  84415. sqlite3VdbeResolveLabel(v, iContinue);
  84416. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  84417. return addr;
  84418. }
  84419. /*
  84420. ** Alternative compound select code generator for cases when there
  84421. ** is an ORDER BY clause.
  84422. **
  84423. ** We assume a query of the following form:
  84424. **
  84425. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  84426. **
  84427. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  84428. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  84429. ** co-routines. Then run the co-routines in parallel and merge the results
  84430. ** into the output. In addition to the two coroutines (called selectA and
  84431. ** selectB) there are 7 subroutines:
  84432. **
  84433. ** outA: Move the output of the selectA coroutine into the output
  84434. ** of the compound query.
  84435. **
  84436. ** outB: Move the output of the selectB coroutine into the output
  84437. ** of the compound query. (Only generated for UNION and
  84438. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  84439. ** appears only in B.)
  84440. **
  84441. ** AltB: Called when there is data from both coroutines and A<B.
  84442. **
  84443. ** AeqB: Called when there is data from both coroutines and A==B.
  84444. **
  84445. ** AgtB: Called when there is data from both coroutines and A>B.
  84446. **
  84447. ** EofA: Called when data is exhausted from selectA.
  84448. **
  84449. ** EofB: Called when data is exhausted from selectB.
  84450. **
  84451. ** The implementation of the latter five subroutines depend on which
  84452. ** <operator> is used:
  84453. **
  84454. **
  84455. ** UNION ALL UNION EXCEPT INTERSECT
  84456. ** ------------- ----------------- -------------- -----------------
  84457. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  84458. **
  84459. ** AeqB: outA, nextA nextA nextA outA, nextA
  84460. **
  84461. ** AgtB: outB, nextB outB, nextB nextB nextB
  84462. **
  84463. ** EofA: outB, nextB outB, nextB halt halt
  84464. **
  84465. ** EofB: outA, nextA outA, nextA outA, nextA halt
  84466. **
  84467. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  84468. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  84469. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  84470. ** following nextX causes a jump to the end of the select processing.
  84471. **
  84472. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  84473. ** within the output subroutine. The regPrev register set holds the previously
  84474. ** output value. A comparison is made against this value and the output
  84475. ** is skipped if the next results would be the same as the previous.
  84476. **
  84477. ** The implementation plan is to implement the two coroutines and seven
  84478. ** subroutines first, then put the control logic at the bottom. Like this:
  84479. **
  84480. ** goto Init
  84481. ** coA: coroutine for left query (A)
  84482. ** coB: coroutine for right query (B)
  84483. ** outA: output one row of A
  84484. ** outB: output one row of B (UNION and UNION ALL only)
  84485. ** EofA: ...
  84486. ** EofB: ...
  84487. ** AltB: ...
  84488. ** AeqB: ...
  84489. ** AgtB: ...
  84490. ** Init: initialize coroutine registers
  84491. ** yield coA
  84492. ** if eof(A) goto EofA
  84493. ** yield coB
  84494. ** if eof(B) goto EofB
  84495. ** Cmpr: Compare A, B
  84496. ** Jump AltB, AeqB, AgtB
  84497. ** End: ...
  84498. **
  84499. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  84500. ** actually called using Gosub and they do not Return. EofA and EofB loop
  84501. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  84502. ** and AgtB jump to either L2 or to one of EofA or EofB.
  84503. */
  84504. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  84505. static int multiSelectOrderBy(
  84506. Parse *pParse, /* Parsing context */
  84507. Select *p, /* The right-most of SELECTs to be coded */
  84508. SelectDest *pDest /* What to do with query results */
  84509. ){
  84510. int i, j; /* Loop counters */
  84511. Select *pPrior; /* Another SELECT immediately to our left */
  84512. Vdbe *v; /* Generate code to this VDBE */
  84513. SelectDest destA; /* Destination for coroutine A */
  84514. SelectDest destB; /* Destination for coroutine B */
  84515. int regAddrA; /* Address register for select-A coroutine */
  84516. int regEofA; /* Flag to indicate when select-A is complete */
  84517. int regAddrB; /* Address register for select-B coroutine */
  84518. int regEofB; /* Flag to indicate when select-B is complete */
  84519. int addrSelectA; /* Address of the select-A coroutine */
  84520. int addrSelectB; /* Address of the select-B coroutine */
  84521. int regOutA; /* Address register for the output-A subroutine */
  84522. int regOutB; /* Address register for the output-B subroutine */
  84523. int addrOutA; /* Address of the output-A subroutine */
  84524. int addrOutB = 0; /* Address of the output-B subroutine */
  84525. int addrEofA; /* Address of the select-A-exhausted subroutine */
  84526. int addrEofB; /* Address of the select-B-exhausted subroutine */
  84527. int addrAltB; /* Address of the A<B subroutine */
  84528. int addrAeqB; /* Address of the A==B subroutine */
  84529. int addrAgtB; /* Address of the A>B subroutine */
  84530. int regLimitA; /* Limit register for select-A */
  84531. int regLimitB; /* Limit register for select-A */
  84532. int regPrev; /* A range of registers to hold previous output */
  84533. int savedLimit; /* Saved value of p->iLimit */
  84534. int savedOffset; /* Saved value of p->iOffset */
  84535. int labelCmpr; /* Label for the start of the merge algorithm */
  84536. int labelEnd; /* Label for the end of the overall SELECT stmt */
  84537. int j1; /* Jump instructions that get retargetted */
  84538. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  84539. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  84540. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  84541. sqlite3 *db; /* Database connection */
  84542. ExprList *pOrderBy; /* The ORDER BY clause */
  84543. int nOrderBy; /* Number of terms in the ORDER BY clause */
  84544. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  84545. #ifndef SQLITE_OMIT_EXPLAIN
  84546. int iSub1; /* EQP id of left-hand query */
  84547. int iSub2; /* EQP id of right-hand query */
  84548. #endif
  84549. assert( p->pOrderBy!=0 );
  84550. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  84551. db = pParse->db;
  84552. v = pParse->pVdbe;
  84553. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  84554. labelEnd = sqlite3VdbeMakeLabel(v);
  84555. labelCmpr = sqlite3VdbeMakeLabel(v);
  84556. /* Patch up the ORDER BY clause
  84557. */
  84558. op = p->op;
  84559. pPrior = p->pPrior;
  84560. assert( pPrior->pOrderBy==0 );
  84561. pOrderBy = p->pOrderBy;
  84562. assert( pOrderBy );
  84563. nOrderBy = pOrderBy->nExpr;
  84564. /* For operators other than UNION ALL we have to make sure that
  84565. ** the ORDER BY clause covers every term of the result set. Add
  84566. ** terms to the ORDER BY clause as necessary.
  84567. */
  84568. if( op!=TK_ALL ){
  84569. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  84570. struct ExprList_item *pItem;
  84571. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  84572. assert( pItem->iOrderByCol>0 );
  84573. if( pItem->iOrderByCol==i ) break;
  84574. }
  84575. if( j==nOrderBy ){
  84576. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  84577. if( pNew==0 ) return SQLITE_NOMEM;
  84578. pNew->flags |= EP_IntValue;
  84579. pNew->u.iValue = i;
  84580. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  84581. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  84582. }
  84583. }
  84584. }
  84585. /* Compute the comparison permutation and keyinfo that is used with
  84586. ** the permutation used to determine if the next
  84587. ** row of results comes from selectA or selectB. Also add explicit
  84588. ** collations to the ORDER BY clause terms so that when the subqueries
  84589. ** to the right and the left are evaluated, they use the correct
  84590. ** collation.
  84591. */
  84592. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  84593. if( aPermute ){
  84594. struct ExprList_item *pItem;
  84595. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  84596. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  84597. aPermute[i] = pItem->iOrderByCol - 1;
  84598. }
  84599. pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  84600. if( pKeyMerge ){
  84601. for(i=0; i<nOrderBy; i++){
  84602. CollSeq *pColl;
  84603. Expr *pTerm = pOrderBy->a[i].pExpr;
  84604. if( pTerm->flags & EP_Collate ){
  84605. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  84606. }else{
  84607. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  84608. if( pColl==0 ) pColl = db->pDfltColl;
  84609. pOrderBy->a[i].pExpr =
  84610. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  84611. }
  84612. pKeyMerge->aColl[i] = pColl;
  84613. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  84614. }
  84615. }
  84616. }else{
  84617. pKeyMerge = 0;
  84618. }
  84619. /* Reattach the ORDER BY clause to the query.
  84620. */
  84621. p->pOrderBy = pOrderBy;
  84622. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  84623. /* Allocate a range of temporary registers and the KeyInfo needed
  84624. ** for the logic that removes duplicate result rows when the
  84625. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  84626. */
  84627. if( op==TK_ALL ){
  84628. regPrev = 0;
  84629. }else{
  84630. int nExpr = p->pEList->nExpr;
  84631. assert( nOrderBy>=nExpr || db->mallocFailed );
  84632. regPrev = pParse->nMem+1;
  84633. pParse->nMem += nExpr+1;
  84634. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  84635. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  84636. if( pKeyDup ){
  84637. for(i=0; i<nExpr; i++){
  84638. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  84639. pKeyDup->aSortOrder[i] = 0;
  84640. }
  84641. }
  84642. }
  84643. /* Separate the left and the right query from one another
  84644. */
  84645. p->pPrior = 0;
  84646. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  84647. if( pPrior->pPrior==0 ){
  84648. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  84649. }
  84650. /* Compute the limit registers */
  84651. computeLimitRegisters(pParse, p, labelEnd);
  84652. if( p->iLimit && op==TK_ALL ){
  84653. regLimitA = ++pParse->nMem;
  84654. regLimitB = ++pParse->nMem;
  84655. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  84656. regLimitA);
  84657. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  84658. }else{
  84659. regLimitA = regLimitB = 0;
  84660. }
  84661. sqlite3ExprDelete(db, p->pLimit);
  84662. p->pLimit = 0;
  84663. sqlite3ExprDelete(db, p->pOffset);
  84664. p->pOffset = 0;
  84665. regAddrA = ++pParse->nMem;
  84666. regEofA = ++pParse->nMem;
  84667. regAddrB = ++pParse->nMem;
  84668. regEofB = ++pParse->nMem;
  84669. regOutA = ++pParse->nMem;
  84670. regOutB = ++pParse->nMem;
  84671. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  84672. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  84673. /* Jump past the various subroutines and coroutines to the main
  84674. ** merge loop
  84675. */
  84676. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  84677. addrSelectA = sqlite3VdbeCurrentAddr(v);
  84678. /* Generate a coroutine to evaluate the SELECT statement to the
  84679. ** left of the compound operator - the "A" select.
  84680. */
  84681. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  84682. pPrior->iLimit = regLimitA;
  84683. explainSetInteger(iSub1, pParse->iNextSelectId);
  84684. sqlite3Select(pParse, pPrior, &destA);
  84685. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  84686. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84687. VdbeNoopComment((v, "End coroutine for left SELECT"));
  84688. /* Generate a coroutine to evaluate the SELECT statement on
  84689. ** the right - the "B" select
  84690. */
  84691. addrSelectB = sqlite3VdbeCurrentAddr(v);
  84692. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  84693. savedLimit = p->iLimit;
  84694. savedOffset = p->iOffset;
  84695. p->iLimit = regLimitB;
  84696. p->iOffset = 0;
  84697. explainSetInteger(iSub2, pParse->iNextSelectId);
  84698. sqlite3Select(pParse, p, &destB);
  84699. p->iLimit = savedLimit;
  84700. p->iOffset = savedOffset;
  84701. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  84702. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84703. VdbeNoopComment((v, "End coroutine for right SELECT"));
  84704. /* Generate a subroutine that outputs the current row of the A
  84705. ** select as the next output row of the compound select.
  84706. */
  84707. VdbeNoopComment((v, "Output routine for A"));
  84708. addrOutA = generateOutputSubroutine(pParse,
  84709. p, &destA, pDest, regOutA,
  84710. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  84711. /* Generate a subroutine that outputs the current row of the B
  84712. ** select as the next output row of the compound select.
  84713. */
  84714. if( op==TK_ALL || op==TK_UNION ){
  84715. VdbeNoopComment((v, "Output routine for B"));
  84716. addrOutB = generateOutputSubroutine(pParse,
  84717. p, &destB, pDest, regOutB,
  84718. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  84719. }
  84720. /* Generate a subroutine to run when the results from select A
  84721. ** are exhausted and only data in select B remains.
  84722. */
  84723. VdbeNoopComment((v, "eof-A subroutine"));
  84724. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  84725. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  84726. }else{
  84727. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  84728. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  84729. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84730. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  84731. p->nSelectRow += pPrior->nSelectRow;
  84732. }
  84733. /* Generate a subroutine to run when the results from select B
  84734. ** are exhausted and only data in select A remains.
  84735. */
  84736. if( op==TK_INTERSECT ){
  84737. addrEofB = addrEofA;
  84738. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  84739. }else{
  84740. VdbeNoopComment((v, "eof-B subroutine"));
  84741. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  84742. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  84743. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84744. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  84745. }
  84746. /* Generate code to handle the case of A<B
  84747. */
  84748. VdbeNoopComment((v, "A-lt-B subroutine"));
  84749. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  84750. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84751. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84752. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84753. /* Generate code to handle the case of A==B
  84754. */
  84755. if( op==TK_ALL ){
  84756. addrAeqB = addrAltB;
  84757. }else if( op==TK_INTERSECT ){
  84758. addrAeqB = addrAltB;
  84759. addrAltB++;
  84760. }else{
  84761. VdbeNoopComment((v, "A-eq-B subroutine"));
  84762. addrAeqB =
  84763. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84764. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84765. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84766. }
  84767. /* Generate code to handle the case of A>B
  84768. */
  84769. VdbeNoopComment((v, "A-gt-B subroutine"));
  84770. addrAgtB = sqlite3VdbeCurrentAddr(v);
  84771. if( op==TK_ALL || op==TK_UNION ){
  84772. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  84773. }
  84774. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84775. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  84776. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84777. /* This code runs once to initialize everything.
  84778. */
  84779. sqlite3VdbeJumpHere(v, j1);
  84780. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  84781. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  84782. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  84783. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  84784. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84785. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  84786. /* Implement the main merge loop
  84787. */
  84788. sqlite3VdbeResolveLabel(v, labelCmpr);
  84789. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  84790. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  84791. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  84792. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  84793. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  84794. /* Jump to the this point in order to terminate the query.
  84795. */
  84796. sqlite3VdbeResolveLabel(v, labelEnd);
  84797. /* Set the number of output columns
  84798. */
  84799. if( pDest->eDest==SRT_Output ){
  84800. Select *pFirst = pPrior;
  84801. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84802. generateColumnNames(pParse, 0, pFirst->pEList);
  84803. }
  84804. /* Reassembly the compound query so that it will be freed correctly
  84805. ** by the calling function */
  84806. if( p->pPrior ){
  84807. sqlite3SelectDelete(db, p->pPrior);
  84808. }
  84809. p->pPrior = pPrior;
  84810. /*** TBD: Insert subroutine calls to close cursors on incomplete
  84811. **** subqueries ****/
  84812. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  84813. return SQLITE_OK;
  84814. }
  84815. #endif
  84816. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  84817. /* Forward Declarations */
  84818. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  84819. static void substSelect(sqlite3*, Select *, int, ExprList *);
  84820. /*
  84821. ** Scan through the expression pExpr. Replace every reference to
  84822. ** a column in table number iTable with a copy of the iColumn-th
  84823. ** entry in pEList. (But leave references to the ROWID column
  84824. ** unchanged.)
  84825. **
  84826. ** This routine is part of the flattening procedure. A subquery
  84827. ** whose result set is defined by pEList appears as entry in the
  84828. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  84829. ** FORM clause entry is iTable. This routine make the necessary
  84830. ** changes to pExpr so that it refers directly to the source table
  84831. ** of the subquery rather the result set of the subquery.
  84832. */
  84833. static Expr *substExpr(
  84834. sqlite3 *db, /* Report malloc errors to this connection */
  84835. Expr *pExpr, /* Expr in which substitution occurs */
  84836. int iTable, /* Table to be substituted */
  84837. ExprList *pEList /* Substitute expressions */
  84838. ){
  84839. if( pExpr==0 ) return 0;
  84840. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  84841. if( pExpr->iColumn<0 ){
  84842. pExpr->op = TK_NULL;
  84843. }else{
  84844. Expr *pNew;
  84845. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  84846. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  84847. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  84848. sqlite3ExprDelete(db, pExpr);
  84849. pExpr = pNew;
  84850. }
  84851. }else{
  84852. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  84853. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  84854. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84855. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  84856. }else{
  84857. substExprList(db, pExpr->x.pList, iTable, pEList);
  84858. }
  84859. }
  84860. return pExpr;
  84861. }
  84862. static void substExprList(
  84863. sqlite3 *db, /* Report malloc errors here */
  84864. ExprList *pList, /* List to scan and in which to make substitutes */
  84865. int iTable, /* Table to be substituted */
  84866. ExprList *pEList /* Substitute values */
  84867. ){
  84868. int i;
  84869. if( pList==0 ) return;
  84870. for(i=0; i<pList->nExpr; i++){
  84871. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  84872. }
  84873. }
  84874. static void substSelect(
  84875. sqlite3 *db, /* Report malloc errors here */
  84876. Select *p, /* SELECT statement in which to make substitutions */
  84877. int iTable, /* Table to be replaced */
  84878. ExprList *pEList /* Substitute values */
  84879. ){
  84880. SrcList *pSrc;
  84881. struct SrcList_item *pItem;
  84882. int i;
  84883. if( !p ) return;
  84884. substExprList(db, p->pEList, iTable, pEList);
  84885. substExprList(db, p->pGroupBy, iTable, pEList);
  84886. substExprList(db, p->pOrderBy, iTable, pEList);
  84887. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  84888. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  84889. substSelect(db, p->pPrior, iTable, pEList);
  84890. pSrc = p->pSrc;
  84891. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  84892. if( ALWAYS(pSrc) ){
  84893. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  84894. substSelect(db, pItem->pSelect, iTable, pEList);
  84895. }
  84896. }
  84897. }
  84898. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  84899. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  84900. /*
  84901. ** This routine attempts to flatten subqueries as a performance optimization.
  84902. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  84903. **
  84904. ** To understand the concept of flattening, consider the following
  84905. ** query:
  84906. **
  84907. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  84908. **
  84909. ** The default way of implementing this query is to execute the
  84910. ** subquery first and store the results in a temporary table, then
  84911. ** run the outer query on that temporary table. This requires two
  84912. ** passes over the data. Furthermore, because the temporary table
  84913. ** has no indices, the WHERE clause on the outer query cannot be
  84914. ** optimized.
  84915. **
  84916. ** This routine attempts to rewrite queries such as the above into
  84917. ** a single flat select, like this:
  84918. **
  84919. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  84920. **
  84921. ** The code generated for this simpification gives the same result
  84922. ** but only has to scan the data once. And because indices might
  84923. ** exist on the table t1, a complete scan of the data might be
  84924. ** avoided.
  84925. **
  84926. ** Flattening is only attempted if all of the following are true:
  84927. **
  84928. ** (1) The subquery and the outer query do not both use aggregates.
  84929. **
  84930. ** (2) The subquery is not an aggregate or the outer query is not a join.
  84931. **
  84932. ** (3) The subquery is not the right operand of a left outer join
  84933. ** (Originally ticket #306. Strengthened by ticket #3300)
  84934. **
  84935. ** (4) The subquery is not DISTINCT.
  84936. **
  84937. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  84938. ** sub-queries that were excluded from this optimization. Restriction
  84939. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  84940. **
  84941. ** (6) The subquery does not use aggregates or the outer query is not
  84942. ** DISTINCT.
  84943. **
  84944. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  84945. ** A FROM clause, consider adding a FROM close with the special
  84946. ** table sqlite_once that consists of a single row containing a
  84947. ** single NULL.
  84948. **
  84949. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  84950. **
  84951. ** (9) The subquery does not use LIMIT or the outer query does not use
  84952. ** aggregates.
  84953. **
  84954. ** (10) The subquery does not use aggregates or the outer query does not
  84955. ** use LIMIT.
  84956. **
  84957. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  84958. **
  84959. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  84960. ** a separate restriction deriving from ticket #350.
  84961. **
  84962. ** (13) The subquery and outer query do not both use LIMIT.
  84963. **
  84964. ** (14) The subquery does not use OFFSET.
  84965. **
  84966. ** (15) The outer query is not part of a compound select or the
  84967. ** subquery does not have a LIMIT clause.
  84968. ** (See ticket #2339 and ticket [02a8e81d44]).
  84969. **
  84970. ** (16) The outer query is not an aggregate or the subquery does
  84971. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  84972. ** until we introduced the group_concat() function.
  84973. **
  84974. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  84975. ** compound clause made up entirely of non-aggregate queries, and
  84976. ** the parent query:
  84977. **
  84978. ** * is not itself part of a compound select,
  84979. ** * is not an aggregate or DISTINCT query, and
  84980. ** * is not a join
  84981. **
  84982. ** The parent and sub-query may contain WHERE clauses. Subject to
  84983. ** rules (11), (13) and (14), they may also contain ORDER BY,
  84984. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  84985. ** operator other than UNION ALL because all the other compound
  84986. ** operators have an implied DISTINCT which is disallowed by
  84987. ** restriction (4).
  84988. **
  84989. ** Also, each component of the sub-query must return the same number
  84990. ** of result columns. This is actually a requirement for any compound
  84991. ** SELECT statement, but all the code here does is make sure that no
  84992. ** such (illegal) sub-query is flattened. The caller will detect the
  84993. ** syntax error and return a detailed message.
  84994. **
  84995. ** (18) If the sub-query is a compound select, then all terms of the
  84996. ** ORDER by clause of the parent must be simple references to
  84997. ** columns of the sub-query.
  84998. **
  84999. ** (19) The subquery does not use LIMIT or the outer query does not
  85000. ** have a WHERE clause.
  85001. **
  85002. ** (20) If the sub-query is a compound select, then it must not use
  85003. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  85004. ** somewhat by saying that the terms of the ORDER BY clause must
  85005. ** appear as unmodified result columns in the outer query. But we
  85006. ** have other optimizations in mind to deal with that case.
  85007. **
  85008. ** (21) The subquery does not use LIMIT or the outer query is not
  85009. ** DISTINCT. (See ticket [752e1646fc]).
  85010. **
  85011. ** In this routine, the "p" parameter is a pointer to the outer query.
  85012. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  85013. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  85014. **
  85015. ** If flattening is not attempted, this routine is a no-op and returns 0.
  85016. ** If flattening is attempted this routine returns 1.
  85017. **
  85018. ** All of the expression analysis must occur on both the outer query and
  85019. ** the subquery before this routine runs.
  85020. */
  85021. static int flattenSubquery(
  85022. Parse *pParse, /* Parsing context */
  85023. Select *p, /* The parent or outer SELECT statement */
  85024. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  85025. int isAgg, /* True if outer SELECT uses aggregate functions */
  85026. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  85027. ){
  85028. const char *zSavedAuthContext = pParse->zAuthContext;
  85029. Select *pParent;
  85030. Select *pSub; /* The inner query or "subquery" */
  85031. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  85032. SrcList *pSrc; /* The FROM clause of the outer query */
  85033. SrcList *pSubSrc; /* The FROM clause of the subquery */
  85034. ExprList *pList; /* The result set of the outer query */
  85035. int iParent; /* VDBE cursor number of the pSub result set temp table */
  85036. int i; /* Loop counter */
  85037. Expr *pWhere; /* The WHERE clause */
  85038. struct SrcList_item *pSubitem; /* The subquery */
  85039. sqlite3 *db = pParse->db;
  85040. /* Check to see if flattening is permitted. Return 0 if not.
  85041. */
  85042. assert( p!=0 );
  85043. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  85044. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  85045. pSrc = p->pSrc;
  85046. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  85047. pSubitem = &pSrc->a[iFrom];
  85048. iParent = pSubitem->iCursor;
  85049. pSub = pSubitem->pSelect;
  85050. assert( pSub!=0 );
  85051. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  85052. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  85053. pSubSrc = pSub->pSrc;
  85054. assert( pSubSrc );
  85055. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  85056. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  85057. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  85058. ** became arbitrary expressions, we were forced to add restrictions (13)
  85059. ** and (14). */
  85060. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  85061. if( pSub->pOffset ) return 0; /* Restriction (14) */
  85062. if( p->pRightmost && pSub->pLimit ){
  85063. return 0; /* Restriction (15) */
  85064. }
  85065. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  85066. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  85067. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  85068. return 0; /* Restrictions (8)(9) */
  85069. }
  85070. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  85071. return 0; /* Restriction (6) */
  85072. }
  85073. if( p->pOrderBy && pSub->pOrderBy ){
  85074. return 0; /* Restriction (11) */
  85075. }
  85076. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  85077. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  85078. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  85079. return 0; /* Restriction (21) */
  85080. }
  85081. /* OBSOLETE COMMENT 1:
  85082. ** Restriction 3: If the subquery is a join, make sure the subquery is
  85083. ** not used as the right operand of an outer join. Examples of why this
  85084. ** is not allowed:
  85085. **
  85086. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  85087. **
  85088. ** If we flatten the above, we would get
  85089. **
  85090. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  85091. **
  85092. ** which is not at all the same thing.
  85093. **
  85094. ** OBSOLETE COMMENT 2:
  85095. ** Restriction 12: If the subquery is the right operand of a left outer
  85096. ** join, make sure the subquery has no WHERE clause.
  85097. ** An examples of why this is not allowed:
  85098. **
  85099. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  85100. **
  85101. ** If we flatten the above, we would get
  85102. **
  85103. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  85104. **
  85105. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  85106. ** effectively converts the OUTER JOIN into an INNER JOIN.
  85107. **
  85108. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  85109. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  85110. ** is fraught with danger. Best to avoid the whole thing. If the
  85111. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  85112. */
  85113. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  85114. return 0;
  85115. }
  85116. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  85117. ** use only the UNION ALL operator. And none of the simple select queries
  85118. ** that make up the compound SELECT are allowed to be aggregate or distinct
  85119. ** queries.
  85120. */
  85121. if( pSub->pPrior ){
  85122. if( pSub->pOrderBy ){
  85123. return 0; /* Restriction 20 */
  85124. }
  85125. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  85126. return 0;
  85127. }
  85128. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  85129. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  85130. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  85131. assert( pSub->pSrc!=0 );
  85132. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  85133. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  85134. || pSub1->pSrc->nSrc<1
  85135. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  85136. ){
  85137. return 0;
  85138. }
  85139. testcase( pSub1->pSrc->nSrc>1 );
  85140. }
  85141. /* Restriction 18. */
  85142. if( p->pOrderBy ){
  85143. int ii;
  85144. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  85145. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  85146. }
  85147. }
  85148. }
  85149. /***** If we reach this point, flattening is permitted. *****/
  85150. /* Authorize the subquery */
  85151. pParse->zAuthContext = pSubitem->zName;
  85152. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  85153. testcase( i==SQLITE_DENY );
  85154. pParse->zAuthContext = zSavedAuthContext;
  85155. /* If the sub-query is a compound SELECT statement, then (by restrictions
  85156. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  85157. ** be of the form:
  85158. **
  85159. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  85160. **
  85161. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  85162. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  85163. ** OFFSET clauses and joins them to the left-hand-side of the original
  85164. ** using UNION ALL operators. In this case N is the number of simple
  85165. ** select statements in the compound sub-query.
  85166. **
  85167. ** Example:
  85168. **
  85169. ** SELECT a+1 FROM (
  85170. ** SELECT x FROM tab
  85171. ** UNION ALL
  85172. ** SELECT y FROM tab
  85173. ** UNION ALL
  85174. ** SELECT abs(z*2) FROM tab2
  85175. ** ) WHERE a!=5 ORDER BY 1
  85176. **
  85177. ** Transformed into:
  85178. **
  85179. ** SELECT x+1 FROM tab WHERE x+1!=5
  85180. ** UNION ALL
  85181. ** SELECT y+1 FROM tab WHERE y+1!=5
  85182. ** UNION ALL
  85183. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  85184. ** ORDER BY 1
  85185. **
  85186. ** We call this the "compound-subquery flattening".
  85187. */
  85188. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  85189. Select *pNew;
  85190. ExprList *pOrderBy = p->pOrderBy;
  85191. Expr *pLimit = p->pLimit;
  85192. Expr *pOffset = p->pOffset;
  85193. Select *pPrior = p->pPrior;
  85194. p->pOrderBy = 0;
  85195. p->pSrc = 0;
  85196. p->pPrior = 0;
  85197. p->pLimit = 0;
  85198. p->pOffset = 0;
  85199. pNew = sqlite3SelectDup(db, p, 0);
  85200. p->pOffset = pOffset;
  85201. p->pLimit = pLimit;
  85202. p->pOrderBy = pOrderBy;
  85203. p->pSrc = pSrc;
  85204. p->op = TK_ALL;
  85205. p->pRightmost = 0;
  85206. if( pNew==0 ){
  85207. pNew = pPrior;
  85208. }else{
  85209. pNew->pPrior = pPrior;
  85210. pNew->pRightmost = 0;
  85211. }
  85212. p->pPrior = pNew;
  85213. if( db->mallocFailed ) return 1;
  85214. }
  85215. /* Begin flattening the iFrom-th entry of the FROM clause
  85216. ** in the outer query.
  85217. */
  85218. pSub = pSub1 = pSubitem->pSelect;
  85219. /* Delete the transient table structure associated with the
  85220. ** subquery
  85221. */
  85222. sqlite3DbFree(db, pSubitem->zDatabase);
  85223. sqlite3DbFree(db, pSubitem->zName);
  85224. sqlite3DbFree(db, pSubitem->zAlias);
  85225. pSubitem->zDatabase = 0;
  85226. pSubitem->zName = 0;
  85227. pSubitem->zAlias = 0;
  85228. pSubitem->pSelect = 0;
  85229. /* Defer deleting the Table object associated with the
  85230. ** subquery until code generation is
  85231. ** complete, since there may still exist Expr.pTab entries that
  85232. ** refer to the subquery even after flattening. Ticket #3346.
  85233. **
  85234. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  85235. */
  85236. if( ALWAYS(pSubitem->pTab!=0) ){
  85237. Table *pTabToDel = pSubitem->pTab;
  85238. if( pTabToDel->nRef==1 ){
  85239. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  85240. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  85241. pToplevel->pZombieTab = pTabToDel;
  85242. }else{
  85243. pTabToDel->nRef--;
  85244. }
  85245. pSubitem->pTab = 0;
  85246. }
  85247. /* The following loop runs once for each term in a compound-subquery
  85248. ** flattening (as described above). If we are doing a different kind
  85249. ** of flattening - a flattening other than a compound-subquery flattening -
  85250. ** then this loop only runs once.
  85251. **
  85252. ** This loop moves all of the FROM elements of the subquery into the
  85253. ** the FROM clause of the outer query. Before doing this, remember
  85254. ** the cursor number for the original outer query FROM element in
  85255. ** iParent. The iParent cursor will never be used. Subsequent code
  85256. ** will scan expressions looking for iParent references and replace
  85257. ** those references with expressions that resolve to the subquery FROM
  85258. ** elements we are now copying in.
  85259. */
  85260. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  85261. int nSubSrc;
  85262. u8 jointype = 0;
  85263. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  85264. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  85265. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  85266. if( pSrc ){
  85267. assert( pParent==p ); /* First time through the loop */
  85268. jointype = pSubitem->jointype;
  85269. }else{
  85270. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  85271. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  85272. if( pSrc==0 ){
  85273. assert( db->mallocFailed );
  85274. break;
  85275. }
  85276. }
  85277. /* The subquery uses a single slot of the FROM clause of the outer
  85278. ** query. If the subquery has more than one element in its FROM clause,
  85279. ** then expand the outer query to make space for it to hold all elements
  85280. ** of the subquery.
  85281. **
  85282. ** Example:
  85283. **
  85284. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  85285. **
  85286. ** The outer query has 3 slots in its FROM clause. One slot of the
  85287. ** outer query (the middle slot) is used by the subquery. The next
  85288. ** block of code will expand the out query to 4 slots. The middle
  85289. ** slot is expanded to two slots in order to make space for the
  85290. ** two elements in the FROM clause of the subquery.
  85291. */
  85292. if( nSubSrc>1 ){
  85293. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  85294. if( db->mallocFailed ){
  85295. break;
  85296. }
  85297. }
  85298. /* Transfer the FROM clause terms from the subquery into the
  85299. ** outer query.
  85300. */
  85301. for(i=0; i<nSubSrc; i++){
  85302. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  85303. pSrc->a[i+iFrom] = pSubSrc->a[i];
  85304. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  85305. }
  85306. pSrc->a[iFrom].jointype = jointype;
  85307. /* Now begin substituting subquery result set expressions for
  85308. ** references to the iParent in the outer query.
  85309. **
  85310. ** Example:
  85311. **
  85312. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  85313. ** \ \_____________ subquery __________/ /
  85314. ** \_____________________ outer query ______________________________/
  85315. **
  85316. ** We look at every expression in the outer query and every place we see
  85317. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  85318. */
  85319. pList = pParent->pEList;
  85320. for(i=0; i<pList->nExpr; i++){
  85321. if( pList->a[i].zName==0 ){
  85322. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  85323. sqlite3Dequote(zName);
  85324. pList->a[i].zName = zName;
  85325. }
  85326. }
  85327. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  85328. if( isAgg ){
  85329. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  85330. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  85331. }
  85332. if( pSub->pOrderBy ){
  85333. assert( pParent->pOrderBy==0 );
  85334. pParent->pOrderBy = pSub->pOrderBy;
  85335. pSub->pOrderBy = 0;
  85336. }else if( pParent->pOrderBy ){
  85337. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  85338. }
  85339. if( pSub->pWhere ){
  85340. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  85341. }else{
  85342. pWhere = 0;
  85343. }
  85344. if( subqueryIsAgg ){
  85345. assert( pParent->pHaving==0 );
  85346. pParent->pHaving = pParent->pWhere;
  85347. pParent->pWhere = pWhere;
  85348. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  85349. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  85350. sqlite3ExprDup(db, pSub->pHaving, 0));
  85351. assert( pParent->pGroupBy==0 );
  85352. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  85353. }else{
  85354. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  85355. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  85356. }
  85357. /* The flattened query is distinct if either the inner or the
  85358. ** outer query is distinct.
  85359. */
  85360. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  85361. /*
  85362. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  85363. **
  85364. ** One is tempted to try to add a and b to combine the limits. But this
  85365. ** does not work if either limit is negative.
  85366. */
  85367. if( pSub->pLimit ){
  85368. pParent->pLimit = pSub->pLimit;
  85369. pSub->pLimit = 0;
  85370. }
  85371. }
  85372. /* Finially, delete what is left of the subquery and return
  85373. ** success.
  85374. */
  85375. sqlite3SelectDelete(db, pSub1);
  85376. return 1;
  85377. }
  85378. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  85379. /*
  85380. ** Based on the contents of the AggInfo structure indicated by the first
  85381. ** argument, this function checks if the following are true:
  85382. **
  85383. ** * the query contains just a single aggregate function,
  85384. ** * the aggregate function is either min() or max(), and
  85385. ** * the argument to the aggregate function is a column value.
  85386. **
  85387. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  85388. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  85389. ** list of arguments passed to the aggregate before returning.
  85390. **
  85391. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  85392. ** WHERE_ORDERBY_NORMAL is returned.
  85393. */
  85394. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  85395. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  85396. *ppMinMax = 0;
  85397. if( pAggInfo->nFunc==1 ){
  85398. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  85399. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  85400. assert( pExpr->op==TK_AGG_FUNCTION );
  85401. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  85402. const char *zFunc = pExpr->u.zToken;
  85403. if( sqlite3StrICmp(zFunc, "min")==0 ){
  85404. eRet = WHERE_ORDERBY_MIN;
  85405. *ppMinMax = pEList;
  85406. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  85407. eRet = WHERE_ORDERBY_MAX;
  85408. *ppMinMax = pEList;
  85409. }
  85410. }
  85411. }
  85412. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  85413. return eRet;
  85414. }
  85415. /*
  85416. ** The select statement passed as the first argument is an aggregate query.
  85417. ** The second argment is the associated aggregate-info object. This
  85418. ** function tests if the SELECT is of the form:
  85419. **
  85420. ** SELECT count(*) FROM <tbl>
  85421. **
  85422. ** where table is a database table, not a sub-select or view. If the query
  85423. ** does match this pattern, then a pointer to the Table object representing
  85424. ** <tbl> is returned. Otherwise, 0 is returned.
  85425. */
  85426. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  85427. Table *pTab;
  85428. Expr *pExpr;
  85429. assert( !p->pGroupBy );
  85430. if( p->pWhere || p->pEList->nExpr!=1
  85431. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  85432. ){
  85433. return 0;
  85434. }
  85435. pTab = p->pSrc->a[0].pTab;
  85436. pExpr = p->pEList->a[0].pExpr;
  85437. assert( pTab && !pTab->pSelect && pExpr );
  85438. if( IsVirtual(pTab) ) return 0;
  85439. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  85440. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  85441. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  85442. if( pExpr->flags&EP_Distinct ) return 0;
  85443. return pTab;
  85444. }
  85445. /*
  85446. ** If the source-list item passed as an argument was augmented with an
  85447. ** INDEXED BY clause, then try to locate the specified index. If there
  85448. ** was such a clause and the named index cannot be found, return
  85449. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  85450. ** pFrom->pIndex and return SQLITE_OK.
  85451. */
  85452. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  85453. if( pFrom->pTab && pFrom->zIndex ){
  85454. Table *pTab = pFrom->pTab;
  85455. char *zIndex = pFrom->zIndex;
  85456. Index *pIdx;
  85457. for(pIdx=pTab->pIndex;
  85458. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  85459. pIdx=pIdx->pNext
  85460. );
  85461. if( !pIdx ){
  85462. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  85463. pParse->checkSchema = 1;
  85464. return SQLITE_ERROR;
  85465. }
  85466. pFrom->pIndex = pIdx;
  85467. }
  85468. return SQLITE_OK;
  85469. }
  85470. /*
  85471. ** Detect compound SELECT statements that use an ORDER BY clause with
  85472. ** an alternative collating sequence.
  85473. **
  85474. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  85475. **
  85476. ** These are rewritten as a subquery:
  85477. **
  85478. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  85479. ** ORDER BY ... COLLATE ...
  85480. **
  85481. ** This transformation is necessary because the multiSelectOrderBy() routine
  85482. ** above that generates the code for a compound SELECT with an ORDER BY clause
  85483. ** uses a merge algorithm that requires the same collating sequence on the
  85484. ** result columns as on the ORDER BY clause. See ticket
  85485. ** http://www.sqlite.org/src/info/6709574d2a
  85486. **
  85487. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  85488. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  85489. ** there are COLLATE terms in the ORDER BY.
  85490. */
  85491. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  85492. int i;
  85493. Select *pNew;
  85494. Select *pX;
  85495. sqlite3 *db;
  85496. struct ExprList_item *a;
  85497. SrcList *pNewSrc;
  85498. Parse *pParse;
  85499. Token dummy;
  85500. if( p->pPrior==0 ) return WRC_Continue;
  85501. if( p->pOrderBy==0 ) return WRC_Continue;
  85502. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  85503. if( pX==0 ) return WRC_Continue;
  85504. a = p->pOrderBy->a;
  85505. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  85506. if( a[i].pExpr->flags & EP_Collate ) break;
  85507. }
  85508. if( i<0 ) return WRC_Continue;
  85509. /* If we reach this point, that means the transformation is required. */
  85510. pParse = pWalker->pParse;
  85511. db = pParse->db;
  85512. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  85513. if( pNew==0 ) return WRC_Abort;
  85514. memset(&dummy, 0, sizeof(dummy));
  85515. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  85516. if( pNewSrc==0 ) return WRC_Abort;
  85517. *pNew = *p;
  85518. p->pSrc = pNewSrc;
  85519. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  85520. p->op = TK_SELECT;
  85521. p->pWhere = 0;
  85522. pNew->pGroupBy = 0;
  85523. pNew->pHaving = 0;
  85524. pNew->pOrderBy = 0;
  85525. p->pPrior = 0;
  85526. pNew->pLimit = 0;
  85527. pNew->pOffset = 0;
  85528. return WRC_Continue;
  85529. }
  85530. /*
  85531. ** This routine is a Walker callback for "expanding" a SELECT statement.
  85532. ** "Expanding" means to do the following:
  85533. **
  85534. ** (1) Make sure VDBE cursor numbers have been assigned to every
  85535. ** element of the FROM clause.
  85536. **
  85537. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  85538. ** defines FROM clause. When views appear in the FROM clause,
  85539. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  85540. ** that implements the view. A copy is made of the view's SELECT
  85541. ** statement so that we can freely modify or delete that statement
  85542. ** without worrying about messing up the presistent representation
  85543. ** of the view.
  85544. **
  85545. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  85546. ** on joins and the ON and USING clause of joins.
  85547. **
  85548. ** (4) Scan the list of columns in the result set (pEList) looking
  85549. ** for instances of the "*" operator or the TABLE.* operator.
  85550. ** If found, expand each "*" to be every column in every table
  85551. ** and TABLE.* to be every column in TABLE.
  85552. **
  85553. */
  85554. static int selectExpander(Walker *pWalker, Select *p){
  85555. Parse *pParse = pWalker->pParse;
  85556. int i, j, k;
  85557. SrcList *pTabList;
  85558. ExprList *pEList;
  85559. struct SrcList_item *pFrom;
  85560. sqlite3 *db = pParse->db;
  85561. Expr *pE, *pRight, *pExpr;
  85562. u16 selFlags = p->selFlags;
  85563. p->selFlags |= SF_Expanded;
  85564. if( db->mallocFailed ){
  85565. return WRC_Abort;
  85566. }
  85567. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  85568. return WRC_Prune;
  85569. }
  85570. pTabList = p->pSrc;
  85571. pEList = p->pEList;
  85572. /* Make sure cursor numbers have been assigned to all entries in
  85573. ** the FROM clause of the SELECT statement.
  85574. */
  85575. sqlite3SrcListAssignCursors(pParse, pTabList);
  85576. /* Look up every table named in the FROM clause of the select. If
  85577. ** an entry of the FROM clause is a subquery instead of a table or view,
  85578. ** then create a transient table structure to describe the subquery.
  85579. */
  85580. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85581. Table *pTab;
  85582. if( pFrom->pTab!=0 ){
  85583. /* This statement has already been prepared. There is no need
  85584. ** to go further. */
  85585. assert( i==0 );
  85586. return WRC_Prune;
  85587. }
  85588. if( pFrom->zName==0 ){
  85589. #ifndef SQLITE_OMIT_SUBQUERY
  85590. Select *pSel = pFrom->pSelect;
  85591. /* A sub-query in the FROM clause of a SELECT */
  85592. assert( pSel!=0 );
  85593. assert( pFrom->pTab==0 );
  85594. sqlite3WalkSelect(pWalker, pSel);
  85595. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  85596. if( pTab==0 ) return WRC_Abort;
  85597. pTab->nRef = 1;
  85598. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  85599. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  85600. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  85601. pTab->iPKey = -1;
  85602. pTab->nRowEst = 1048576;
  85603. pTab->tabFlags |= TF_Ephemeral;
  85604. #endif
  85605. }else{
  85606. /* An ordinary table or view name in the FROM clause */
  85607. assert( pFrom->pTab==0 );
  85608. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  85609. if( pTab==0 ) return WRC_Abort;
  85610. if( pTab->nRef==0xffff ){
  85611. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  85612. pTab->zName);
  85613. pFrom->pTab = 0;
  85614. return WRC_Abort;
  85615. }
  85616. pTab->nRef++;
  85617. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  85618. if( pTab->pSelect || IsVirtual(pTab) ){
  85619. /* We reach here if the named table is a really a view */
  85620. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  85621. assert( pFrom->pSelect==0 );
  85622. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  85623. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  85624. }
  85625. #endif
  85626. }
  85627. /* Locate the index named by the INDEXED BY clause, if any. */
  85628. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  85629. return WRC_Abort;
  85630. }
  85631. }
  85632. /* Process NATURAL keywords, and ON and USING clauses of joins.
  85633. */
  85634. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  85635. return WRC_Abort;
  85636. }
  85637. /* For every "*" that occurs in the column list, insert the names of
  85638. ** all columns in all tables. And for every TABLE.* insert the names
  85639. ** of all columns in TABLE. The parser inserted a special expression
  85640. ** with the TK_ALL operator for each "*" that it found in the column list.
  85641. ** The following code just has to locate the TK_ALL expressions and expand
  85642. ** each one to the list of all columns in all tables.
  85643. **
  85644. ** The first loop just checks to see if there are any "*" operators
  85645. ** that need expanding.
  85646. */
  85647. for(k=0; k<pEList->nExpr; k++){
  85648. pE = pEList->a[k].pExpr;
  85649. if( pE->op==TK_ALL ) break;
  85650. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  85651. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  85652. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  85653. }
  85654. if( k<pEList->nExpr ){
  85655. /*
  85656. ** If we get here it means the result set contains one or more "*"
  85657. ** operators that need to be expanded. Loop through each expression
  85658. ** in the result set and expand them one by one.
  85659. */
  85660. struct ExprList_item *a = pEList->a;
  85661. ExprList *pNew = 0;
  85662. int flags = pParse->db->flags;
  85663. int longNames = (flags & SQLITE_FullColNames)!=0
  85664. && (flags & SQLITE_ShortColNames)==0;
  85665. /* When processing FROM-clause subqueries, it is always the case
  85666. ** that full_column_names=OFF and short_column_names=ON. The
  85667. ** sqlite3ResultSetOfSelect() routine makes it so. */
  85668. assert( (p->selFlags & SF_NestedFrom)==0
  85669. || ((flags & SQLITE_FullColNames)==0 &&
  85670. (flags & SQLITE_ShortColNames)!=0) );
  85671. for(k=0; k<pEList->nExpr; k++){
  85672. pE = a[k].pExpr;
  85673. pRight = pE->pRight;
  85674. assert( pE->op!=TK_DOT || pRight!=0 );
  85675. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  85676. /* This particular expression does not need to be expanded.
  85677. */
  85678. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  85679. if( pNew ){
  85680. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  85681. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  85682. a[k].zName = 0;
  85683. a[k].zSpan = 0;
  85684. }
  85685. a[k].pExpr = 0;
  85686. }else{
  85687. /* This expression is a "*" or a "TABLE.*" and needs to be
  85688. ** expanded. */
  85689. int tableSeen = 0; /* Set to 1 when TABLE matches */
  85690. char *zTName = 0; /* text of name of TABLE */
  85691. if( pE->op==TK_DOT ){
  85692. assert( pE->pLeft!=0 );
  85693. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  85694. zTName = pE->pLeft->u.zToken;
  85695. }
  85696. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85697. Table *pTab = pFrom->pTab;
  85698. Select *pSub = pFrom->pSelect;
  85699. char *zTabName = pFrom->zAlias;
  85700. const char *zSchemaName = 0;
  85701. int iDb;
  85702. if( zTabName==0 ){
  85703. zTabName = pTab->zName;
  85704. }
  85705. if( db->mallocFailed ) break;
  85706. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  85707. pSub = 0;
  85708. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  85709. continue;
  85710. }
  85711. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85712. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  85713. }
  85714. for(j=0; j<pTab->nCol; j++){
  85715. char *zName = pTab->aCol[j].zName;
  85716. char *zColname; /* The computed column name */
  85717. char *zToFree; /* Malloced string that needs to be freed */
  85718. Token sColname; /* Computed column name as a token */
  85719. assert( zName );
  85720. if( zTName && pSub
  85721. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  85722. ){
  85723. continue;
  85724. }
  85725. /* If a column is marked as 'hidden' (currently only possible
  85726. ** for virtual tables), do not include it in the expanded
  85727. ** result-set list.
  85728. */
  85729. if( IsHiddenColumn(&pTab->aCol[j]) ){
  85730. assert(IsVirtual(pTab));
  85731. continue;
  85732. }
  85733. tableSeen = 1;
  85734. if( i>0 && zTName==0 ){
  85735. if( (pFrom->jointype & JT_NATURAL)!=0
  85736. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  85737. ){
  85738. /* In a NATURAL join, omit the join columns from the
  85739. ** table to the right of the join */
  85740. continue;
  85741. }
  85742. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  85743. /* In a join with a USING clause, omit columns in the
  85744. ** using clause from the table on the right. */
  85745. continue;
  85746. }
  85747. }
  85748. pRight = sqlite3Expr(db, TK_ID, zName);
  85749. zColname = zName;
  85750. zToFree = 0;
  85751. if( longNames || pTabList->nSrc>1 ){
  85752. Expr *pLeft;
  85753. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  85754. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  85755. if( zSchemaName ){
  85756. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  85757. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  85758. }
  85759. if( longNames ){
  85760. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  85761. zToFree = zColname;
  85762. }
  85763. }else{
  85764. pExpr = pRight;
  85765. }
  85766. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  85767. sColname.z = zColname;
  85768. sColname.n = sqlite3Strlen30(zColname);
  85769. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  85770. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  85771. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  85772. if( pSub ){
  85773. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  85774. testcase( pX->zSpan==0 );
  85775. }else{
  85776. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  85777. zSchemaName, zTabName, zColname);
  85778. testcase( pX->zSpan==0 );
  85779. }
  85780. pX->bSpanIsTab = 1;
  85781. }
  85782. sqlite3DbFree(db, zToFree);
  85783. }
  85784. }
  85785. if( !tableSeen ){
  85786. if( zTName ){
  85787. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  85788. }else{
  85789. sqlite3ErrorMsg(pParse, "no tables specified");
  85790. }
  85791. }
  85792. }
  85793. }
  85794. sqlite3ExprListDelete(db, pEList);
  85795. p->pEList = pNew;
  85796. }
  85797. #if SQLITE_MAX_COLUMN
  85798. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  85799. sqlite3ErrorMsg(pParse, "too many columns in result set");
  85800. }
  85801. #endif
  85802. return WRC_Continue;
  85803. }
  85804. /*
  85805. ** No-op routine for the parse-tree walker.
  85806. **
  85807. ** When this routine is the Walker.xExprCallback then expression trees
  85808. ** are walked without any actions being taken at each node. Presumably,
  85809. ** when this routine is used for Walker.xExprCallback then
  85810. ** Walker.xSelectCallback is set to do something useful for every
  85811. ** subquery in the parser tree.
  85812. */
  85813. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  85814. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  85815. return WRC_Continue;
  85816. }
  85817. /*
  85818. ** This routine "expands" a SELECT statement and all of its subqueries.
  85819. ** For additional information on what it means to "expand" a SELECT
  85820. ** statement, see the comment on the selectExpand worker callback above.
  85821. **
  85822. ** Expanding a SELECT statement is the first step in processing a
  85823. ** SELECT statement. The SELECT statement must be expanded before
  85824. ** name resolution is performed.
  85825. **
  85826. ** If anything goes wrong, an error message is written into pParse.
  85827. ** The calling function can detect the problem by looking at pParse->nErr
  85828. ** and/or pParse->db->mallocFailed.
  85829. */
  85830. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  85831. Walker w;
  85832. memset(&w, 0, sizeof(w));
  85833. w.xExprCallback = exprWalkNoop;
  85834. w.pParse = pParse;
  85835. if( pParse->hasCompound ){
  85836. w.xSelectCallback = convertCompoundSelectToSubquery;
  85837. sqlite3WalkSelect(&w, pSelect);
  85838. }
  85839. w.xSelectCallback = selectExpander;
  85840. sqlite3WalkSelect(&w, pSelect);
  85841. }
  85842. #ifndef SQLITE_OMIT_SUBQUERY
  85843. /*
  85844. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  85845. ** interface.
  85846. **
  85847. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  85848. ** information to the Table structure that represents the result set
  85849. ** of that subquery.
  85850. **
  85851. ** The Table structure that represents the result set was constructed
  85852. ** by selectExpander() but the type and collation information was omitted
  85853. ** at that point because identifiers had not yet been resolved. This
  85854. ** routine is called after identifier resolution.
  85855. */
  85856. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  85857. Parse *pParse;
  85858. int i;
  85859. SrcList *pTabList;
  85860. struct SrcList_item *pFrom;
  85861. assert( p->selFlags & SF_Resolved );
  85862. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  85863. p->selFlags |= SF_HasTypeInfo;
  85864. pParse = pWalker->pParse;
  85865. pTabList = p->pSrc;
  85866. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85867. Table *pTab = pFrom->pTab;
  85868. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  85869. /* A sub-query in the FROM clause of a SELECT */
  85870. Select *pSel = pFrom->pSelect;
  85871. assert( pSel );
  85872. while( pSel->pPrior ) pSel = pSel->pPrior;
  85873. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  85874. }
  85875. }
  85876. }
  85877. return WRC_Continue;
  85878. }
  85879. #endif
  85880. /*
  85881. ** This routine adds datatype and collating sequence information to
  85882. ** the Table structures of all FROM-clause subqueries in a
  85883. ** SELECT statement.
  85884. **
  85885. ** Use this routine after name resolution.
  85886. */
  85887. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  85888. #ifndef SQLITE_OMIT_SUBQUERY
  85889. Walker w;
  85890. memset(&w, 0, sizeof(w));
  85891. w.xSelectCallback = selectAddSubqueryTypeInfo;
  85892. w.xExprCallback = exprWalkNoop;
  85893. w.pParse = pParse;
  85894. w.bSelectDepthFirst = 1;
  85895. sqlite3WalkSelect(&w, pSelect);
  85896. #endif
  85897. }
  85898. /*
  85899. ** This routine sets up a SELECT statement for processing. The
  85900. ** following is accomplished:
  85901. **
  85902. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  85903. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  85904. ** * ON and USING clauses are shifted into WHERE statements
  85905. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  85906. ** * Identifiers in expression are matched to tables.
  85907. **
  85908. ** This routine acts recursively on all subqueries within the SELECT.
  85909. */
  85910. SQLITE_PRIVATE void sqlite3SelectPrep(
  85911. Parse *pParse, /* The parser context */
  85912. Select *p, /* The SELECT statement being coded. */
  85913. NameContext *pOuterNC /* Name context for container */
  85914. ){
  85915. sqlite3 *db;
  85916. if( NEVER(p==0) ) return;
  85917. db = pParse->db;
  85918. if( db->mallocFailed ) return;
  85919. if( p->selFlags & SF_HasTypeInfo ) return;
  85920. sqlite3SelectExpand(pParse, p);
  85921. if( pParse->nErr || db->mallocFailed ) return;
  85922. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  85923. if( pParse->nErr || db->mallocFailed ) return;
  85924. sqlite3SelectAddTypeInfo(pParse, p);
  85925. }
  85926. /*
  85927. ** Reset the aggregate accumulator.
  85928. **
  85929. ** The aggregate accumulator is a set of memory cells that hold
  85930. ** intermediate results while calculating an aggregate. This
  85931. ** routine generates code that stores NULLs in all of those memory
  85932. ** cells.
  85933. */
  85934. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  85935. Vdbe *v = pParse->pVdbe;
  85936. int i;
  85937. struct AggInfo_func *pFunc;
  85938. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  85939. return;
  85940. }
  85941. for(i=0; i<pAggInfo->nColumn; i++){
  85942. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  85943. }
  85944. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  85945. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  85946. if( pFunc->iDistinct>=0 ){
  85947. Expr *pE = pFunc->pExpr;
  85948. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  85949. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  85950. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  85951. "argument");
  85952. pFunc->iDistinct = -1;
  85953. }else{
  85954. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  85955. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  85956. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  85957. }
  85958. }
  85959. }
  85960. }
  85961. /*
  85962. ** Invoke the OP_AggFinalize opcode for every aggregate function
  85963. ** in the AggInfo structure.
  85964. */
  85965. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  85966. Vdbe *v = pParse->pVdbe;
  85967. int i;
  85968. struct AggInfo_func *pF;
  85969. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  85970. ExprList *pList = pF->pExpr->x.pList;
  85971. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  85972. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  85973. (void*)pF->pFunc, P4_FUNCDEF);
  85974. }
  85975. }
  85976. /*
  85977. ** Update the accumulator memory cells for an aggregate based on
  85978. ** the current cursor position.
  85979. */
  85980. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  85981. Vdbe *v = pParse->pVdbe;
  85982. int i;
  85983. int regHit = 0;
  85984. int addrHitTest = 0;
  85985. struct AggInfo_func *pF;
  85986. struct AggInfo_col *pC;
  85987. pAggInfo->directMode = 1;
  85988. sqlite3ExprCacheClear(pParse);
  85989. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  85990. int nArg;
  85991. int addrNext = 0;
  85992. int regAgg;
  85993. ExprList *pList = pF->pExpr->x.pList;
  85994. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  85995. if( pList ){
  85996. nArg = pList->nExpr;
  85997. regAgg = sqlite3GetTempRange(pParse, nArg);
  85998. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  85999. }else{
  86000. nArg = 0;
  86001. regAgg = 0;
  86002. }
  86003. if( pF->iDistinct>=0 ){
  86004. addrNext = sqlite3VdbeMakeLabel(v);
  86005. assert( nArg==1 );
  86006. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  86007. }
  86008. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  86009. CollSeq *pColl = 0;
  86010. struct ExprList_item *pItem;
  86011. int j;
  86012. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  86013. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  86014. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  86015. }
  86016. if( !pColl ){
  86017. pColl = pParse->db->pDfltColl;
  86018. }
  86019. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  86020. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  86021. }
  86022. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  86023. (void*)pF->pFunc, P4_FUNCDEF);
  86024. sqlite3VdbeChangeP5(v, (u8)nArg);
  86025. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  86026. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  86027. if( addrNext ){
  86028. sqlite3VdbeResolveLabel(v, addrNext);
  86029. sqlite3ExprCacheClear(pParse);
  86030. }
  86031. }
  86032. /* Before populating the accumulator registers, clear the column cache.
  86033. ** Otherwise, if any of the required column values are already present
  86034. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  86035. ** to pC->iMem. But by the time the value is used, the original register
  86036. ** may have been used, invalidating the underlying buffer holding the
  86037. ** text or blob value. See ticket [883034dcb5].
  86038. **
  86039. ** Another solution would be to change the OP_SCopy used to copy cached
  86040. ** values to an OP_Copy.
  86041. */
  86042. if( regHit ){
  86043. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  86044. }
  86045. sqlite3ExprCacheClear(pParse);
  86046. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  86047. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  86048. }
  86049. pAggInfo->directMode = 0;
  86050. sqlite3ExprCacheClear(pParse);
  86051. if( addrHitTest ){
  86052. sqlite3VdbeJumpHere(v, addrHitTest);
  86053. }
  86054. }
  86055. /*
  86056. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  86057. ** count(*) query ("SELECT count(*) FROM pTab").
  86058. */
  86059. #ifndef SQLITE_OMIT_EXPLAIN
  86060. static void explainSimpleCount(
  86061. Parse *pParse, /* Parse context */
  86062. Table *pTab, /* Table being queried */
  86063. Index *pIdx /* Index used to optimize scan, or NULL */
  86064. ){
  86065. if( pParse->explain==2 ){
  86066. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  86067. pTab->zName,
  86068. pIdx ? " USING COVERING INDEX " : "",
  86069. pIdx ? pIdx->zName : ""
  86070. );
  86071. sqlite3VdbeAddOp4(
  86072. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  86073. );
  86074. }
  86075. }
  86076. #else
  86077. # define explainSimpleCount(a,b,c)
  86078. #endif
  86079. /*
  86080. ** Generate code for the SELECT statement given in the p argument.
  86081. **
  86082. ** The results are distributed in various ways depending on the
  86083. ** contents of the SelectDest structure pointed to by argument pDest
  86084. ** as follows:
  86085. **
  86086. ** pDest->eDest Result
  86087. ** ------------ -------------------------------------------
  86088. ** SRT_Output Generate a row of output (using the OP_ResultRow
  86089. ** opcode) for each row in the result set.
  86090. **
  86091. ** SRT_Mem Only valid if the result is a single column.
  86092. ** Store the first column of the first result row
  86093. ** in register pDest->iSDParm then abandon the rest
  86094. ** of the query. This destination implies "LIMIT 1".
  86095. **
  86096. ** SRT_Set The result must be a single column. Store each
  86097. ** row of result as the key in table pDest->iSDParm.
  86098. ** Apply the affinity pDest->affSdst before storing
  86099. ** results. Used to implement "IN (SELECT ...)".
  86100. **
  86101. ** SRT_Union Store results as a key in a temporary table
  86102. ** identified by pDest->iSDParm.
  86103. **
  86104. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  86105. **
  86106. ** SRT_Table Store results in temporary table pDest->iSDParm.
  86107. ** This is like SRT_EphemTab except that the table
  86108. ** is assumed to already be open.
  86109. **
  86110. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  86111. ** the result there. The cursor is left open after
  86112. ** returning. This is like SRT_Table except that
  86113. ** this destination uses OP_OpenEphemeral to create
  86114. ** the table first.
  86115. **
  86116. ** SRT_Coroutine Generate a co-routine that returns a new row of
  86117. ** results each time it is invoked. The entry point
  86118. ** of the co-routine is stored in register pDest->iSDParm.
  86119. **
  86120. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  86121. ** set is not empty.
  86122. **
  86123. ** SRT_Discard Throw the results away. This is used by SELECT
  86124. ** statements within triggers whose only purpose is
  86125. ** the side-effects of functions.
  86126. **
  86127. ** This routine returns the number of errors. If any errors are
  86128. ** encountered, then an appropriate error message is left in
  86129. ** pParse->zErrMsg.
  86130. **
  86131. ** This routine does NOT free the Select structure passed in. The
  86132. ** calling function needs to do that.
  86133. */
  86134. SQLITE_PRIVATE int sqlite3Select(
  86135. Parse *pParse, /* The parser context */
  86136. Select *p, /* The SELECT statement being coded. */
  86137. SelectDest *pDest /* What to do with the query results */
  86138. ){
  86139. int i, j; /* Loop counters */
  86140. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  86141. Vdbe *v; /* The virtual machine under construction */
  86142. int isAgg; /* True for select lists like "count(*)" */
  86143. ExprList *pEList; /* List of columns to extract. */
  86144. SrcList *pTabList; /* List of tables to select from */
  86145. Expr *pWhere; /* The WHERE clause. May be NULL */
  86146. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  86147. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  86148. Expr *pHaving; /* The HAVING clause. May be NULL */
  86149. int rc = 1; /* Value to return from this function */
  86150. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  86151. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  86152. AggInfo sAggInfo; /* Information used by aggregate queries */
  86153. int iEnd; /* Address of the end of the query */
  86154. sqlite3 *db; /* The database connection */
  86155. #ifndef SQLITE_OMIT_EXPLAIN
  86156. int iRestoreSelectId = pParse->iSelectId;
  86157. pParse->iSelectId = pParse->iNextSelectId++;
  86158. #endif
  86159. db = pParse->db;
  86160. if( p==0 || db->mallocFailed || pParse->nErr ){
  86161. return 1;
  86162. }
  86163. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  86164. memset(&sAggInfo, 0, sizeof(sAggInfo));
  86165. if( IgnorableOrderby(pDest) ){
  86166. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  86167. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  86168. /* If ORDER BY makes no difference in the output then neither does
  86169. ** DISTINCT so it can be removed too. */
  86170. sqlite3ExprListDelete(db, p->pOrderBy);
  86171. p->pOrderBy = 0;
  86172. p->selFlags &= ~SF_Distinct;
  86173. }
  86174. sqlite3SelectPrep(pParse, p, 0);
  86175. pOrderBy = p->pOrderBy;
  86176. pTabList = p->pSrc;
  86177. pEList = p->pEList;
  86178. if( pParse->nErr || db->mallocFailed ){
  86179. goto select_end;
  86180. }
  86181. isAgg = (p->selFlags & SF_Aggregate)!=0;
  86182. assert( pEList!=0 );
  86183. /* Begin generating code.
  86184. */
  86185. v = sqlite3GetVdbe(pParse);
  86186. if( v==0 ) goto select_end;
  86187. /* If writing to memory or generating a set
  86188. ** only a single column may be output.
  86189. */
  86190. #ifndef SQLITE_OMIT_SUBQUERY
  86191. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  86192. goto select_end;
  86193. }
  86194. #endif
  86195. /* Generate code for all sub-queries in the FROM clause
  86196. */
  86197. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  86198. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  86199. struct SrcList_item *pItem = &pTabList->a[i];
  86200. SelectDest dest;
  86201. Select *pSub = pItem->pSelect;
  86202. int isAggSub;
  86203. if( pSub==0 ) continue;
  86204. /* Sometimes the code for a subquery will be generated more than
  86205. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  86206. ** for example. In that case, do not regenerate the code to manifest
  86207. ** a view or the co-routine to implement a view. The first instance
  86208. ** is sufficient, though the subroutine to manifest the view does need
  86209. ** to be invoked again. */
  86210. if( pItem->addrFillSub ){
  86211. if( pItem->viaCoroutine==0 ){
  86212. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  86213. }
  86214. continue;
  86215. }
  86216. /* Increment Parse.nHeight by the height of the largest expression
  86217. ** tree referred to by this, the parent select. The child select
  86218. ** may contain expression trees of at most
  86219. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  86220. ** more conservative than necessary, but much easier than enforcing
  86221. ** an exact limit.
  86222. */
  86223. pParse->nHeight += sqlite3SelectExprHeight(p);
  86224. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  86225. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  86226. /* This subquery can be absorbed into its parent. */
  86227. if( isAggSub ){
  86228. isAgg = 1;
  86229. p->selFlags |= SF_Aggregate;
  86230. }
  86231. i = -1;
  86232. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  86233. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  86234. ){
  86235. /* Implement a co-routine that will return a single row of the result
  86236. ** set on each invocation.
  86237. */
  86238. int addrTop;
  86239. int addrEof;
  86240. pItem->regReturn = ++pParse->nMem;
  86241. addrEof = ++pParse->nMem;
  86242. /* Before coding the OP_Goto to jump to the start of the main routine,
  86243. ** ensure that the jump to the verify-schema routine has already
  86244. ** been coded. Otherwise, the verify-schema would likely be coded as
  86245. ** part of the co-routine. If the main routine then accessed the
  86246. ** database before invoking the co-routine for the first time (for
  86247. ** example to initialize a LIMIT register from a sub-select), it would
  86248. ** be doing so without having verified the schema version and obtained
  86249. ** the required db locks. See ticket d6b36be38. */
  86250. sqlite3CodeVerifySchema(pParse, -1);
  86251. sqlite3VdbeAddOp0(v, OP_Goto);
  86252. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  86253. sqlite3VdbeChangeP5(v, 1);
  86254. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  86255. pItem->addrFillSub = addrTop;
  86256. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  86257. sqlite3VdbeChangeP5(v, 1);
  86258. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  86259. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  86260. sqlite3Select(pParse, pSub, &dest);
  86261. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  86262. pItem->viaCoroutine = 1;
  86263. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  86264. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  86265. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  86266. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  86267. VdbeComment((v, "end %s", pItem->pTab->zName));
  86268. sqlite3VdbeJumpHere(v, addrTop-1);
  86269. sqlite3ClearTempRegCache(pParse);
  86270. }else{
  86271. /* Generate a subroutine that will fill an ephemeral table with
  86272. ** the content of this subquery. pItem->addrFillSub will point
  86273. ** to the address of the generated subroutine. pItem->regReturn
  86274. ** is a register allocated to hold the subroutine return address
  86275. */
  86276. int topAddr;
  86277. int onceAddr = 0;
  86278. int retAddr;
  86279. assert( pItem->addrFillSub==0 );
  86280. pItem->regReturn = ++pParse->nMem;
  86281. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  86282. pItem->addrFillSub = topAddr+1;
  86283. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  86284. if( pItem->isCorrelated==0 ){
  86285. /* If the subquery is not correlated and if we are not inside of
  86286. ** a trigger, then we only need to compute the value of the subquery
  86287. ** once. */
  86288. onceAddr = sqlite3CodeOnce(pParse);
  86289. }
  86290. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  86291. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  86292. sqlite3Select(pParse, pSub, &dest);
  86293. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  86294. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  86295. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  86296. VdbeComment((v, "end %s", pItem->pTab->zName));
  86297. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  86298. sqlite3ClearTempRegCache(pParse);
  86299. }
  86300. if( /*pParse->nErr ||*/ db->mallocFailed ){
  86301. goto select_end;
  86302. }
  86303. pParse->nHeight -= sqlite3SelectExprHeight(p);
  86304. pTabList = p->pSrc;
  86305. if( !IgnorableOrderby(pDest) ){
  86306. pOrderBy = p->pOrderBy;
  86307. }
  86308. }
  86309. pEList = p->pEList;
  86310. #endif
  86311. pWhere = p->pWhere;
  86312. pGroupBy = p->pGroupBy;
  86313. pHaving = p->pHaving;
  86314. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  86315. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  86316. /* If there is are a sequence of queries, do the earlier ones first.
  86317. */
  86318. if( p->pPrior ){
  86319. if( p->pRightmost==0 ){
  86320. Select *pLoop, *pRight = 0;
  86321. int cnt = 0;
  86322. int mxSelect;
  86323. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  86324. pLoop->pRightmost = p;
  86325. pLoop->pNext = pRight;
  86326. pRight = pLoop;
  86327. }
  86328. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  86329. if( mxSelect && cnt>mxSelect ){
  86330. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  86331. goto select_end;
  86332. }
  86333. }
  86334. rc = multiSelect(pParse, p, pDest);
  86335. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  86336. return rc;
  86337. }
  86338. #endif
  86339. /* If there is both a GROUP BY and an ORDER BY clause and they are
  86340. ** identical, then disable the ORDER BY clause since the GROUP BY
  86341. ** will cause elements to come out in the correct order. This is
  86342. ** an optimization - the correct answer should result regardless.
  86343. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  86344. ** to disable this optimization for testing purposes.
  86345. */
  86346. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  86347. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  86348. pOrderBy = 0;
  86349. }
  86350. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  86351. ** if the select-list is the same as the ORDER BY list, then this query
  86352. ** can be rewritten as a GROUP BY. In other words, this:
  86353. **
  86354. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  86355. **
  86356. ** is transformed to:
  86357. **
  86358. ** SELECT xyz FROM ... GROUP BY xyz
  86359. **
  86360. ** The second form is preferred as a single index (or temp-table) may be
  86361. ** used for both the ORDER BY and DISTINCT processing. As originally
  86362. ** written the query must use a temp-table for at least one of the ORDER
  86363. ** BY and DISTINCT, and an index or separate temp-table for the other.
  86364. */
  86365. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  86366. && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  86367. ){
  86368. p->selFlags &= ~SF_Distinct;
  86369. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  86370. pGroupBy = p->pGroupBy;
  86371. pOrderBy = 0;
  86372. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  86373. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  86374. ** original setting of the SF_Distinct flag, not the current setting */
  86375. assert( sDistinct.isTnct );
  86376. }
  86377. /* If there is an ORDER BY clause, then this sorting
  86378. ** index might end up being unused if the data can be
  86379. ** extracted in pre-sorted order. If that is the case, then the
  86380. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  86381. ** we figure out that the sorting index is not needed. The addrSortIndex
  86382. ** variable is used to facilitate that change.
  86383. */
  86384. if( pOrderBy ){
  86385. KeyInfo *pKeyInfo;
  86386. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  86387. pOrderBy->iECursor = pParse->nTab++;
  86388. p->addrOpenEphm[2] = addrSortIndex =
  86389. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  86390. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  86391. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  86392. }else{
  86393. addrSortIndex = -1;
  86394. }
  86395. /* If the output is destined for a temporary table, open that table.
  86396. */
  86397. if( pDest->eDest==SRT_EphemTab ){
  86398. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  86399. }
  86400. /* Set the limiter.
  86401. */
  86402. iEnd = sqlite3VdbeMakeLabel(v);
  86403. p->nSelectRow = LARGEST_INT64;
  86404. computeLimitRegisters(pParse, p, iEnd);
  86405. if( p->iLimit==0 && addrSortIndex>=0 ){
  86406. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  86407. p->selFlags |= SF_UseSorter;
  86408. }
  86409. /* Open a virtual index to use for the distinct set.
  86410. */
  86411. if( p->selFlags & SF_Distinct ){
  86412. sDistinct.tabTnct = pParse->nTab++;
  86413. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  86414. sDistinct.tabTnct, 0, 0,
  86415. (char*)keyInfoFromExprList(pParse, p->pEList),
  86416. P4_KEYINFO_HANDOFF);
  86417. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  86418. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  86419. }else{
  86420. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  86421. }
  86422. if( !isAgg && pGroupBy==0 ){
  86423. /* No aggregate functions and no GROUP BY clause */
  86424. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  86425. /* Begin the database scan. */
  86426. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
  86427. wctrlFlags, 0);
  86428. if( pWInfo==0 ) goto select_end;
  86429. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  86430. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  86431. }
  86432. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  86433. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  86434. }
  86435. if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
  86436. /* If sorting index that was created by a prior OP_OpenEphemeral
  86437. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  86438. ** into an OP_Noop.
  86439. */
  86440. if( addrSortIndex>=0 && pOrderBy==0 ){
  86441. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  86442. p->addrOpenEphm[2] = -1;
  86443. }
  86444. /* Use the standard inner loop. */
  86445. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  86446. sqlite3WhereContinueLabel(pWInfo),
  86447. sqlite3WhereBreakLabel(pWInfo));
  86448. /* End the database scan loop.
  86449. */
  86450. sqlite3WhereEnd(pWInfo);
  86451. }else{
  86452. /* This case when there exist aggregate functions or a GROUP BY clause
  86453. ** or both */
  86454. NameContext sNC; /* Name context for processing aggregate information */
  86455. int iAMem; /* First Mem address for storing current GROUP BY */
  86456. int iBMem; /* First Mem address for previous GROUP BY */
  86457. int iUseFlag; /* Mem address holding flag indicating that at least
  86458. ** one row of the input to the aggregator has been
  86459. ** processed */
  86460. int iAbortFlag; /* Mem address which causes query abort if positive */
  86461. int groupBySort; /* Rows come from source in GROUP BY order */
  86462. int addrEnd; /* End of processing for this SELECT */
  86463. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  86464. int sortOut = 0; /* Output register from the sorter */
  86465. /* Remove any and all aliases between the result set and the
  86466. ** GROUP BY clause.
  86467. */
  86468. if( pGroupBy ){
  86469. int k; /* Loop counter */
  86470. struct ExprList_item *pItem; /* For looping over expression in a list */
  86471. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  86472. pItem->iAlias = 0;
  86473. }
  86474. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  86475. pItem->iAlias = 0;
  86476. }
  86477. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  86478. }else{
  86479. p->nSelectRow = 1;
  86480. }
  86481. /* Create a label to jump to when we want to abort the query */
  86482. addrEnd = sqlite3VdbeMakeLabel(v);
  86483. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  86484. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  86485. ** SELECT statement.
  86486. */
  86487. memset(&sNC, 0, sizeof(sNC));
  86488. sNC.pParse = pParse;
  86489. sNC.pSrcList = pTabList;
  86490. sNC.pAggInfo = &sAggInfo;
  86491. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  86492. sAggInfo.pGroupBy = pGroupBy;
  86493. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  86494. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  86495. if( pHaving ){
  86496. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  86497. }
  86498. sAggInfo.nAccumulator = sAggInfo.nColumn;
  86499. for(i=0; i<sAggInfo.nFunc; i++){
  86500. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  86501. sNC.ncFlags |= NC_InAggFunc;
  86502. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  86503. sNC.ncFlags &= ~NC_InAggFunc;
  86504. }
  86505. if( db->mallocFailed ) goto select_end;
  86506. /* Processing for aggregates with GROUP BY is very different and
  86507. ** much more complex than aggregates without a GROUP BY.
  86508. */
  86509. if( pGroupBy ){
  86510. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  86511. int j1; /* A-vs-B comparision jump */
  86512. int addrOutputRow; /* Start of subroutine that outputs a result row */
  86513. int regOutputRow; /* Return address register for output subroutine */
  86514. int addrSetAbort; /* Set the abort flag and return */
  86515. int addrTopOfLoop; /* Top of the input loop */
  86516. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  86517. int addrReset; /* Subroutine for resetting the accumulator */
  86518. int regReset; /* Return address register for reset subroutine */
  86519. /* If there is a GROUP BY clause we might need a sorting index to
  86520. ** implement it. Allocate that sorting index now. If it turns out
  86521. ** that we do not need it after all, the OP_SorterOpen instruction
  86522. ** will be converted into a Noop.
  86523. */
  86524. sAggInfo.sortingIdx = pParse->nTab++;
  86525. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  86526. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  86527. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  86528. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  86529. /* Initialize memory locations used by GROUP BY aggregate processing
  86530. */
  86531. iUseFlag = ++pParse->nMem;
  86532. iAbortFlag = ++pParse->nMem;
  86533. regOutputRow = ++pParse->nMem;
  86534. addrOutputRow = sqlite3VdbeMakeLabel(v);
  86535. regReset = ++pParse->nMem;
  86536. addrReset = sqlite3VdbeMakeLabel(v);
  86537. iAMem = pParse->nMem + 1;
  86538. pParse->nMem += pGroupBy->nExpr;
  86539. iBMem = pParse->nMem + 1;
  86540. pParse->nMem += pGroupBy->nExpr;
  86541. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  86542. VdbeComment((v, "clear abort flag"));
  86543. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  86544. VdbeComment((v, "indicate accumulator empty"));
  86545. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  86546. /* Begin a loop that will extract all source rows in GROUP BY order.
  86547. ** This might involve two separate loops with an OP_Sort in between, or
  86548. ** it might be a single loop that uses an index to extract information
  86549. ** in the right order to begin with.
  86550. */
  86551. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  86552. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  86553. WHERE_GROUPBY, 0);
  86554. if( pWInfo==0 ) goto select_end;
  86555. if( sqlite3WhereIsOrdered(pWInfo) ){
  86556. /* The optimizer is able to deliver rows in group by order so
  86557. ** we do not have to sort. The OP_OpenEphemeral table will be
  86558. ** cancelled later because we still need to use the pKeyInfo
  86559. */
  86560. groupBySort = 0;
  86561. }else{
  86562. /* Rows are coming out in undetermined order. We have to push
  86563. ** each row into a sorting index, terminate the first loop,
  86564. ** then loop over the sorting index in order to get the output
  86565. ** in sorted order
  86566. */
  86567. int regBase;
  86568. int regRecord;
  86569. int nCol;
  86570. int nGroupBy;
  86571. explainTempTable(pParse,
  86572. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  86573. "DISTINCT" : "GROUP BY");
  86574. groupBySort = 1;
  86575. nGroupBy = pGroupBy->nExpr;
  86576. nCol = nGroupBy + 1;
  86577. j = nGroupBy+1;
  86578. for(i=0; i<sAggInfo.nColumn; i++){
  86579. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  86580. nCol++;
  86581. j++;
  86582. }
  86583. }
  86584. regBase = sqlite3GetTempRange(pParse, nCol);
  86585. sqlite3ExprCacheClear(pParse);
  86586. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  86587. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  86588. j = nGroupBy+1;
  86589. for(i=0; i<sAggInfo.nColumn; i++){
  86590. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  86591. if( pCol->iSorterColumn>=j ){
  86592. int r1 = j + regBase;
  86593. int r2;
  86594. r2 = sqlite3ExprCodeGetColumn(pParse,
  86595. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  86596. if( r1!=r2 ){
  86597. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  86598. }
  86599. j++;
  86600. }
  86601. }
  86602. regRecord = sqlite3GetTempReg(pParse);
  86603. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  86604. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  86605. sqlite3ReleaseTempReg(pParse, regRecord);
  86606. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  86607. sqlite3WhereEnd(pWInfo);
  86608. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  86609. sortOut = sqlite3GetTempReg(pParse);
  86610. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  86611. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  86612. VdbeComment((v, "GROUP BY sort"));
  86613. sAggInfo.useSortingIdx = 1;
  86614. sqlite3ExprCacheClear(pParse);
  86615. }
  86616. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  86617. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  86618. ** Then compare the current GROUP BY terms against the GROUP BY terms
  86619. ** from the previous row currently stored in a0, a1, a2...
  86620. */
  86621. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  86622. sqlite3ExprCacheClear(pParse);
  86623. if( groupBySort ){
  86624. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  86625. }
  86626. for(j=0; j<pGroupBy->nExpr; j++){
  86627. if( groupBySort ){
  86628. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  86629. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  86630. }else{
  86631. sAggInfo.directMode = 1;
  86632. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  86633. }
  86634. }
  86635. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  86636. (char*)pKeyInfo, P4_KEYINFO);
  86637. j1 = sqlite3VdbeCurrentAddr(v);
  86638. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  86639. /* Generate code that runs whenever the GROUP BY changes.
  86640. ** Changes in the GROUP BY are detected by the previous code
  86641. ** block. If there were no changes, this block is skipped.
  86642. **
  86643. ** This code copies current group by terms in b0,b1,b2,...
  86644. ** over to a0,a1,a2. It then calls the output subroutine
  86645. ** and resets the aggregate accumulator registers in preparation
  86646. ** for the next GROUP BY batch.
  86647. */
  86648. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  86649. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  86650. VdbeComment((v, "output one row"));
  86651. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  86652. VdbeComment((v, "check abort flag"));
  86653. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  86654. VdbeComment((v, "reset accumulator"));
  86655. /* Update the aggregate accumulators based on the content of
  86656. ** the current row
  86657. */
  86658. sqlite3VdbeJumpHere(v, j1);
  86659. updateAccumulator(pParse, &sAggInfo);
  86660. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  86661. VdbeComment((v, "indicate data in accumulator"));
  86662. /* End of the loop
  86663. */
  86664. if( groupBySort ){
  86665. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  86666. }else{
  86667. sqlite3WhereEnd(pWInfo);
  86668. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  86669. }
  86670. /* Output the final row of result
  86671. */
  86672. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  86673. VdbeComment((v, "output final row"));
  86674. /* Jump over the subroutines
  86675. */
  86676. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  86677. /* Generate a subroutine that outputs a single row of the result
  86678. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  86679. ** is less than or equal to zero, the subroutine is a no-op. If
  86680. ** the processing calls for the query to abort, this subroutine
  86681. ** increments the iAbortFlag memory location before returning in
  86682. ** order to signal the caller to abort.
  86683. */
  86684. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  86685. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  86686. VdbeComment((v, "set abort flag"));
  86687. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86688. sqlite3VdbeResolveLabel(v, addrOutputRow);
  86689. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  86690. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  86691. VdbeComment((v, "Groupby result generator entry point"));
  86692. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86693. finalizeAggFunctions(pParse, &sAggInfo);
  86694. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  86695. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  86696. &sDistinct, pDest,
  86697. addrOutputRow+1, addrSetAbort);
  86698. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86699. VdbeComment((v, "end groupby result generator"));
  86700. /* Generate a subroutine that will reset the group-by accumulator
  86701. */
  86702. sqlite3VdbeResolveLabel(v, addrReset);
  86703. resetAccumulator(pParse, &sAggInfo);
  86704. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  86705. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  86706. else {
  86707. ExprList *pDel = 0;
  86708. #ifndef SQLITE_OMIT_BTREECOUNT
  86709. Table *pTab;
  86710. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  86711. /* If isSimpleCount() returns a pointer to a Table structure, then
  86712. ** the SQL statement is of the form:
  86713. **
  86714. ** SELECT count(*) FROM <tbl>
  86715. **
  86716. ** where the Table structure returned represents table <tbl>.
  86717. **
  86718. ** This statement is so common that it is optimized specially. The
  86719. ** OP_Count instruction is executed either on the intkey table that
  86720. ** contains the data for table <tbl> or on one of its indexes. It
  86721. ** is better to execute the op on an index, as indexes are almost
  86722. ** always spread across less pages than their corresponding tables.
  86723. */
  86724. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  86725. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  86726. Index *pIdx; /* Iterator variable */
  86727. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  86728. Index *pBest = 0; /* Best index found so far */
  86729. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  86730. sqlite3CodeVerifySchema(pParse, iDb);
  86731. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  86732. /* Search for the index that has the lowest scan cost.
  86733. **
  86734. ** (2011-04-15) Do not do a full scan of an unordered index.
  86735. **
  86736. ** (2013-10-03) Do not count the entires in a partial index.
  86737. **
  86738. ** In practice the KeyInfo structure will not be used. It is only
  86739. ** passed to keep OP_OpenRead happy.
  86740. */
  86741. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86742. if( pIdx->bUnordered==0
  86743. && pIdx->szIdxRow<pTab->szTabRow
  86744. && pIdx->pPartIdxWhere==0
  86745. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  86746. ){
  86747. pBest = pIdx;
  86748. }
  86749. }
  86750. if( pBest ){
  86751. iRoot = pBest->tnum;
  86752. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  86753. }
  86754. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  86755. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  86756. if( pKeyInfo ){
  86757. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  86758. }
  86759. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  86760. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  86761. explainSimpleCount(pParse, pTab, pBest);
  86762. }else
  86763. #endif /* SQLITE_OMIT_BTREECOUNT */
  86764. {
  86765. /* Check if the query is of one of the following forms:
  86766. **
  86767. ** SELECT min(x) FROM ...
  86768. ** SELECT max(x) FROM ...
  86769. **
  86770. ** If it is, then ask the code in where.c to attempt to sort results
  86771. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  86772. ** If where.c is able to produce results sorted in this order, then
  86773. ** add vdbe code to break out of the processing loop after the
  86774. ** first iteration (since the first iteration of the loop is
  86775. ** guaranteed to operate on the row with the minimum or maximum
  86776. ** value of x, the only row required).
  86777. **
  86778. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  86779. ** modify behavior as follows:
  86780. **
  86781. ** + If the query is a "SELECT min(x)", then the loop coded by
  86782. ** where.c should not iterate over any values with a NULL value
  86783. ** for x.
  86784. **
  86785. ** + The optimizer code in where.c (the thing that decides which
  86786. ** index or indices to use) should place a different priority on
  86787. ** satisfying the 'ORDER BY' clause than it does in other cases.
  86788. ** Refer to code and comments in where.c for details.
  86789. */
  86790. ExprList *pMinMax = 0;
  86791. u8 flag = WHERE_ORDERBY_NORMAL;
  86792. assert( p->pGroupBy==0 );
  86793. assert( flag==0 );
  86794. if( p->pHaving==0 ){
  86795. flag = minMaxQuery(&sAggInfo, &pMinMax);
  86796. }
  86797. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  86798. if( flag ){
  86799. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  86800. pDel = pMinMax;
  86801. if( pMinMax && !db->mallocFailed ){
  86802. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  86803. pMinMax->a[0].pExpr->op = TK_COLUMN;
  86804. }
  86805. }
  86806. /* This case runs if the aggregate has no GROUP BY clause. The
  86807. ** processing is much simpler since there is only a single row
  86808. ** of output.
  86809. */
  86810. resetAccumulator(pParse, &sAggInfo);
  86811. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  86812. if( pWInfo==0 ){
  86813. sqlite3ExprListDelete(db, pDel);
  86814. goto select_end;
  86815. }
  86816. updateAccumulator(pParse, &sAggInfo);
  86817. assert( pMinMax==0 || pMinMax->nExpr==1 );
  86818. if( sqlite3WhereIsOrdered(pWInfo) ){
  86819. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  86820. VdbeComment((v, "%s() by index",
  86821. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  86822. }
  86823. sqlite3WhereEnd(pWInfo);
  86824. finalizeAggFunctions(pParse, &sAggInfo);
  86825. }
  86826. pOrderBy = 0;
  86827. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  86828. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  86829. pDest, addrEnd, addrEnd);
  86830. sqlite3ExprListDelete(db, pDel);
  86831. }
  86832. sqlite3VdbeResolveLabel(v, addrEnd);
  86833. } /* endif aggregate query */
  86834. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  86835. explainTempTable(pParse, "DISTINCT");
  86836. }
  86837. /* If there is an ORDER BY clause, then we need to sort the results
  86838. ** and send them to the callback one by one.
  86839. */
  86840. if( pOrderBy ){
  86841. explainTempTable(pParse, "ORDER BY");
  86842. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  86843. }
  86844. /* Jump here to skip this query
  86845. */
  86846. sqlite3VdbeResolveLabel(v, iEnd);
  86847. /* The SELECT was successfully coded. Set the return code to 0
  86848. ** to indicate no errors.
  86849. */
  86850. rc = 0;
  86851. /* Control jumps to here if an error is encountered above, or upon
  86852. ** successful coding of the SELECT.
  86853. */
  86854. select_end:
  86855. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  86856. /* Identify column names if results of the SELECT are to be output.
  86857. */
  86858. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  86859. generateColumnNames(pParse, pTabList, pEList);
  86860. }
  86861. sqlite3DbFree(db, sAggInfo.aCol);
  86862. sqlite3DbFree(db, sAggInfo.aFunc);
  86863. return rc;
  86864. }
  86865. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  86866. /*
  86867. ** Generate a human-readable description of a the Select object.
  86868. */
  86869. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  86870. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  86871. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  86872. if( p->selFlags & SF_Distinct ){
  86873. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  86874. }
  86875. if( p->selFlags & SF_Aggregate ){
  86876. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  86877. }
  86878. sqlite3ExplainNL(pVdbe);
  86879. sqlite3ExplainPrintf(pVdbe, " ");
  86880. }
  86881. sqlite3ExplainExprList(pVdbe, p->pEList);
  86882. sqlite3ExplainNL(pVdbe);
  86883. if( p->pSrc && p->pSrc->nSrc ){
  86884. int i;
  86885. sqlite3ExplainPrintf(pVdbe, "FROM ");
  86886. sqlite3ExplainPush(pVdbe);
  86887. for(i=0; i<p->pSrc->nSrc; i++){
  86888. struct SrcList_item *pItem = &p->pSrc->a[i];
  86889. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  86890. if( pItem->pSelect ){
  86891. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  86892. if( pItem->pTab ){
  86893. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  86894. }
  86895. }else if( pItem->zName ){
  86896. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  86897. }
  86898. if( pItem->zAlias ){
  86899. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  86900. }
  86901. if( pItem->jointype & JT_LEFT ){
  86902. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  86903. }
  86904. sqlite3ExplainNL(pVdbe);
  86905. }
  86906. sqlite3ExplainPop(pVdbe);
  86907. }
  86908. if( p->pWhere ){
  86909. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  86910. sqlite3ExplainExpr(pVdbe, p->pWhere);
  86911. sqlite3ExplainNL(pVdbe);
  86912. }
  86913. if( p->pGroupBy ){
  86914. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  86915. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  86916. sqlite3ExplainNL(pVdbe);
  86917. }
  86918. if( p->pHaving ){
  86919. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  86920. sqlite3ExplainExpr(pVdbe, p->pHaving);
  86921. sqlite3ExplainNL(pVdbe);
  86922. }
  86923. if( p->pOrderBy ){
  86924. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  86925. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  86926. sqlite3ExplainNL(pVdbe);
  86927. }
  86928. if( p->pLimit ){
  86929. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  86930. sqlite3ExplainExpr(pVdbe, p->pLimit);
  86931. sqlite3ExplainNL(pVdbe);
  86932. }
  86933. if( p->pOffset ){
  86934. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  86935. sqlite3ExplainExpr(pVdbe, p->pOffset);
  86936. sqlite3ExplainNL(pVdbe);
  86937. }
  86938. }
  86939. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  86940. if( p==0 ){
  86941. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  86942. return;
  86943. }
  86944. while( p->pPrior ){
  86945. p->pPrior->pNext = p;
  86946. p = p->pPrior;
  86947. }
  86948. sqlite3ExplainPush(pVdbe);
  86949. while( p ){
  86950. explainOneSelect(pVdbe, p);
  86951. p = p->pNext;
  86952. if( p==0 ) break;
  86953. sqlite3ExplainNL(pVdbe);
  86954. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  86955. }
  86956. sqlite3ExplainPrintf(pVdbe, "END");
  86957. sqlite3ExplainPop(pVdbe);
  86958. }
  86959. /* End of the structure debug printing code
  86960. *****************************************************************************/
  86961. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  86962. /************** End of select.c **********************************************/
  86963. /************** Begin file table.c *******************************************/
  86964. /*
  86965. ** 2001 September 15
  86966. **
  86967. ** The author disclaims copyright to this source code. In place of
  86968. ** a legal notice, here is a blessing:
  86969. **
  86970. ** May you do good and not evil.
  86971. ** May you find forgiveness for yourself and forgive others.
  86972. ** May you share freely, never taking more than you give.
  86973. **
  86974. *************************************************************************
  86975. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  86976. ** interface routines. These are just wrappers around the main
  86977. ** interface routine of sqlite3_exec().
  86978. **
  86979. ** These routines are in a separate files so that they will not be linked
  86980. ** if they are not used.
  86981. */
  86982. /* #include <stdlib.h> */
  86983. /* #include <string.h> */
  86984. #ifndef SQLITE_OMIT_GET_TABLE
  86985. /*
  86986. ** This structure is used to pass data from sqlite3_get_table() through
  86987. ** to the callback function is uses to build the result.
  86988. */
  86989. typedef struct TabResult {
  86990. char **azResult; /* Accumulated output */
  86991. char *zErrMsg; /* Error message text, if an error occurs */
  86992. int nAlloc; /* Slots allocated for azResult[] */
  86993. int nRow; /* Number of rows in the result */
  86994. int nColumn; /* Number of columns in the result */
  86995. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  86996. int rc; /* Return code from sqlite3_exec() */
  86997. } TabResult;
  86998. /*
  86999. ** This routine is called once for each row in the result table. Its job
  87000. ** is to fill in the TabResult structure appropriately, allocating new
  87001. ** memory as necessary.
  87002. */
  87003. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  87004. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  87005. int need; /* Slots needed in p->azResult[] */
  87006. int i; /* Loop counter */
  87007. char *z; /* A single column of result */
  87008. /* Make sure there is enough space in p->azResult to hold everything
  87009. ** we need to remember from this invocation of the callback.
  87010. */
  87011. if( p->nRow==0 && argv!=0 ){
  87012. need = nCol*2;
  87013. }else{
  87014. need = nCol;
  87015. }
  87016. if( p->nData + need > p->nAlloc ){
  87017. char **azNew;
  87018. p->nAlloc = p->nAlloc*2 + need;
  87019. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  87020. if( azNew==0 ) goto malloc_failed;
  87021. p->azResult = azNew;
  87022. }
  87023. /* If this is the first row, then generate an extra row containing
  87024. ** the names of all columns.
  87025. */
  87026. if( p->nRow==0 ){
  87027. p->nColumn = nCol;
  87028. for(i=0; i<nCol; i++){
  87029. z = sqlite3_mprintf("%s", colv[i]);
  87030. if( z==0 ) goto malloc_failed;
  87031. p->azResult[p->nData++] = z;
  87032. }
  87033. }else if( p->nColumn!=nCol ){
  87034. sqlite3_free(p->zErrMsg);
  87035. p->zErrMsg = sqlite3_mprintf(
  87036. "sqlite3_get_table() called with two or more incompatible queries"
  87037. );
  87038. p->rc = SQLITE_ERROR;
  87039. return 1;
  87040. }
  87041. /* Copy over the row data
  87042. */
  87043. if( argv!=0 ){
  87044. for(i=0; i<nCol; i++){
  87045. if( argv[i]==0 ){
  87046. z = 0;
  87047. }else{
  87048. int n = sqlite3Strlen30(argv[i])+1;
  87049. z = sqlite3_malloc( n );
  87050. if( z==0 ) goto malloc_failed;
  87051. memcpy(z, argv[i], n);
  87052. }
  87053. p->azResult[p->nData++] = z;
  87054. }
  87055. p->nRow++;
  87056. }
  87057. return 0;
  87058. malloc_failed:
  87059. p->rc = SQLITE_NOMEM;
  87060. return 1;
  87061. }
  87062. /*
  87063. ** Query the database. But instead of invoking a callback for each row,
  87064. ** malloc() for space to hold the result and return the entire results
  87065. ** at the conclusion of the call.
  87066. **
  87067. ** The result that is written to ***pazResult is held in memory obtained
  87068. ** from malloc(). But the caller cannot free this memory directly.
  87069. ** Instead, the entire table should be passed to sqlite3_free_table() when
  87070. ** the calling procedure is finished using it.
  87071. */
  87072. SQLITE_API int sqlite3_get_table(
  87073. sqlite3 *db, /* The database on which the SQL executes */
  87074. const char *zSql, /* The SQL to be executed */
  87075. char ***pazResult, /* Write the result table here */
  87076. int *pnRow, /* Write the number of rows in the result here */
  87077. int *pnColumn, /* Write the number of columns of result here */
  87078. char **pzErrMsg /* Write error messages here */
  87079. ){
  87080. int rc;
  87081. TabResult res;
  87082. *pazResult = 0;
  87083. if( pnColumn ) *pnColumn = 0;
  87084. if( pnRow ) *pnRow = 0;
  87085. if( pzErrMsg ) *pzErrMsg = 0;
  87086. res.zErrMsg = 0;
  87087. res.nRow = 0;
  87088. res.nColumn = 0;
  87089. res.nData = 1;
  87090. res.nAlloc = 20;
  87091. res.rc = SQLITE_OK;
  87092. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  87093. if( res.azResult==0 ){
  87094. db->errCode = SQLITE_NOMEM;
  87095. return SQLITE_NOMEM;
  87096. }
  87097. res.azResult[0] = 0;
  87098. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  87099. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  87100. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  87101. if( (rc&0xff)==SQLITE_ABORT ){
  87102. sqlite3_free_table(&res.azResult[1]);
  87103. if( res.zErrMsg ){
  87104. if( pzErrMsg ){
  87105. sqlite3_free(*pzErrMsg);
  87106. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  87107. }
  87108. sqlite3_free(res.zErrMsg);
  87109. }
  87110. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  87111. return res.rc;
  87112. }
  87113. sqlite3_free(res.zErrMsg);
  87114. if( rc!=SQLITE_OK ){
  87115. sqlite3_free_table(&res.azResult[1]);
  87116. return rc;
  87117. }
  87118. if( res.nAlloc>res.nData ){
  87119. char **azNew;
  87120. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  87121. if( azNew==0 ){
  87122. sqlite3_free_table(&res.azResult[1]);
  87123. db->errCode = SQLITE_NOMEM;
  87124. return SQLITE_NOMEM;
  87125. }
  87126. res.azResult = azNew;
  87127. }
  87128. *pazResult = &res.azResult[1];
  87129. if( pnColumn ) *pnColumn = res.nColumn;
  87130. if( pnRow ) *pnRow = res.nRow;
  87131. return rc;
  87132. }
  87133. /*
  87134. ** This routine frees the space the sqlite3_get_table() malloced.
  87135. */
  87136. SQLITE_API void sqlite3_free_table(
  87137. char **azResult /* Result returned from from sqlite3_get_table() */
  87138. ){
  87139. if( azResult ){
  87140. int i, n;
  87141. azResult--;
  87142. assert( azResult!=0 );
  87143. n = SQLITE_PTR_TO_INT(azResult[0]);
  87144. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  87145. sqlite3_free(azResult);
  87146. }
  87147. }
  87148. #endif /* SQLITE_OMIT_GET_TABLE */
  87149. /************** End of table.c ***********************************************/
  87150. /************** Begin file trigger.c *****************************************/
  87151. /*
  87152. **
  87153. ** The author disclaims copyright to this source code. In place of
  87154. ** a legal notice, here is a blessing:
  87155. **
  87156. ** May you do good and not evil.
  87157. ** May you find forgiveness for yourself and forgive others.
  87158. ** May you share freely, never taking more than you give.
  87159. **
  87160. *************************************************************************
  87161. ** This file contains the implementation for TRIGGERs
  87162. */
  87163. #ifndef SQLITE_OMIT_TRIGGER
  87164. /*
  87165. ** Delete a linked list of TriggerStep structures.
  87166. */
  87167. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  87168. while( pTriggerStep ){
  87169. TriggerStep * pTmp = pTriggerStep;
  87170. pTriggerStep = pTriggerStep->pNext;
  87171. sqlite3ExprDelete(db, pTmp->pWhere);
  87172. sqlite3ExprListDelete(db, pTmp->pExprList);
  87173. sqlite3SelectDelete(db, pTmp->pSelect);
  87174. sqlite3IdListDelete(db, pTmp->pIdList);
  87175. sqlite3DbFree(db, pTmp);
  87176. }
  87177. }
  87178. /*
  87179. ** Given table pTab, return a list of all the triggers attached to
  87180. ** the table. The list is connected by Trigger.pNext pointers.
  87181. **
  87182. ** All of the triggers on pTab that are in the same database as pTab
  87183. ** are already attached to pTab->pTrigger. But there might be additional
  87184. ** triggers on pTab in the TEMP schema. This routine prepends all
  87185. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  87186. ** and returns the combined list.
  87187. **
  87188. ** To state it another way: This routine returns a list of all triggers
  87189. ** that fire off of pTab. The list will include any TEMP triggers on
  87190. ** pTab as well as the triggers lised in pTab->pTrigger.
  87191. */
  87192. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  87193. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  87194. Trigger *pList = 0; /* List of triggers to return */
  87195. if( pParse->disableTriggers ){
  87196. return 0;
  87197. }
  87198. if( pTmpSchema!=pTab->pSchema ){
  87199. HashElem *p;
  87200. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  87201. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  87202. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  87203. if( pTrig->pTabSchema==pTab->pSchema
  87204. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  87205. ){
  87206. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  87207. pList = pTrig;
  87208. }
  87209. }
  87210. }
  87211. return (pList ? pList : pTab->pTrigger);
  87212. }
  87213. /*
  87214. ** This is called by the parser when it sees a CREATE TRIGGER statement
  87215. ** up to the point of the BEGIN before the trigger actions. A Trigger
  87216. ** structure is generated based on the information available and stored
  87217. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  87218. ** sqlite3FinishTrigger() function is called to complete the trigger
  87219. ** construction process.
  87220. */
  87221. SQLITE_PRIVATE void sqlite3BeginTrigger(
  87222. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  87223. Token *pName1, /* The name of the trigger */
  87224. Token *pName2, /* The name of the trigger */
  87225. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  87226. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  87227. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  87228. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  87229. Expr *pWhen, /* WHEN clause */
  87230. int isTemp, /* True if the TEMPORARY keyword is present */
  87231. int noErr /* Suppress errors if the trigger already exists */
  87232. ){
  87233. Trigger *pTrigger = 0; /* The new trigger */
  87234. Table *pTab; /* Table that the trigger fires off of */
  87235. char *zName = 0; /* Name of the trigger */
  87236. sqlite3 *db = pParse->db; /* The database connection */
  87237. int iDb; /* The database to store the trigger in */
  87238. Token *pName; /* The unqualified db name */
  87239. DbFixer sFix; /* State vector for the DB fixer */
  87240. int iTabDb; /* Index of the database holding pTab */
  87241. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  87242. assert( pName2!=0 );
  87243. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  87244. assert( op>0 && op<0xff );
  87245. if( isTemp ){
  87246. /* If TEMP was specified, then the trigger name may not be qualified. */
  87247. if( pName2->n>0 ){
  87248. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  87249. goto trigger_cleanup;
  87250. }
  87251. iDb = 1;
  87252. pName = pName1;
  87253. }else{
  87254. /* Figure out the db that the trigger will be created in */
  87255. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  87256. if( iDb<0 ){
  87257. goto trigger_cleanup;
  87258. }
  87259. }
  87260. if( !pTableName || db->mallocFailed ){
  87261. goto trigger_cleanup;
  87262. }
  87263. /* A long-standing parser bug is that this syntax was allowed:
  87264. **
  87265. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  87266. ** ^^^^^^^^
  87267. **
  87268. ** To maintain backwards compatibility, ignore the database
  87269. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  87270. */
  87271. if( db->init.busy && iDb!=1 ){
  87272. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  87273. pTableName->a[0].zDatabase = 0;
  87274. }
  87275. /* If the trigger name was unqualified, and the table is a temp table,
  87276. ** then set iDb to 1 to create the trigger in the temporary database.
  87277. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  87278. ** exist, the error is caught by the block below.
  87279. */
  87280. pTab = sqlite3SrcListLookup(pParse, pTableName);
  87281. if( db->init.busy==0 && pName2->n==0 && pTab
  87282. && pTab->pSchema==db->aDb[1].pSchema ){
  87283. iDb = 1;
  87284. }
  87285. /* Ensure the table name matches database name and that the table exists */
  87286. if( db->mallocFailed ) goto trigger_cleanup;
  87287. assert( pTableName->nSrc==1 );
  87288. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  87289. if( sqlite3FixSrcList(&sFix, pTableName) ){
  87290. goto trigger_cleanup;
  87291. }
  87292. pTab = sqlite3SrcListLookup(pParse, pTableName);
  87293. if( !pTab ){
  87294. /* The table does not exist. */
  87295. if( db->init.iDb==1 ){
  87296. /* Ticket #3810.
  87297. ** Normally, whenever a table is dropped, all associated triggers are
  87298. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  87299. ** and the table is dropped by a different database connection, the
  87300. ** trigger is not visible to the database connection that does the
  87301. ** drop so the trigger cannot be dropped. This results in an
  87302. ** "orphaned trigger" - a trigger whose associated table is missing.
  87303. */
  87304. db->init.orphanTrigger = 1;
  87305. }
  87306. goto trigger_cleanup;
  87307. }
  87308. if( IsVirtual(pTab) ){
  87309. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  87310. goto trigger_cleanup;
  87311. }
  87312. /* Check that the trigger name is not reserved and that no trigger of the
  87313. ** specified name exists */
  87314. zName = sqlite3NameFromToken(db, pName);
  87315. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  87316. goto trigger_cleanup;
  87317. }
  87318. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87319. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  87320. zName, sqlite3Strlen30(zName)) ){
  87321. if( !noErr ){
  87322. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  87323. }else{
  87324. assert( !db->init.busy );
  87325. sqlite3CodeVerifySchema(pParse, iDb);
  87326. }
  87327. goto trigger_cleanup;
  87328. }
  87329. /* Do not create a trigger on a system table */
  87330. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  87331. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  87332. pParse->nErr++;
  87333. goto trigger_cleanup;
  87334. }
  87335. /* INSTEAD of triggers are only for views and views only support INSTEAD
  87336. ** of triggers.
  87337. */
  87338. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  87339. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  87340. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  87341. goto trigger_cleanup;
  87342. }
  87343. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  87344. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  87345. " trigger on table: %S", pTableName, 0);
  87346. goto trigger_cleanup;
  87347. }
  87348. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87349. #ifndef SQLITE_OMIT_AUTHORIZATION
  87350. {
  87351. int code = SQLITE_CREATE_TRIGGER;
  87352. const char *zDb = db->aDb[iTabDb].zName;
  87353. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  87354. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  87355. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  87356. goto trigger_cleanup;
  87357. }
  87358. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  87359. goto trigger_cleanup;
  87360. }
  87361. }
  87362. #endif
  87363. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  87364. ** cannot appear on views. So we might as well translate every
  87365. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  87366. ** elsewhere.
  87367. */
  87368. if (tr_tm == TK_INSTEAD){
  87369. tr_tm = TK_BEFORE;
  87370. }
  87371. /* Build the Trigger object */
  87372. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  87373. if( pTrigger==0 ) goto trigger_cleanup;
  87374. pTrigger->zName = zName;
  87375. zName = 0;
  87376. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  87377. pTrigger->pSchema = db->aDb[iDb].pSchema;
  87378. pTrigger->pTabSchema = pTab->pSchema;
  87379. pTrigger->op = (u8)op;
  87380. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  87381. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  87382. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  87383. assert( pParse->pNewTrigger==0 );
  87384. pParse->pNewTrigger = pTrigger;
  87385. trigger_cleanup:
  87386. sqlite3DbFree(db, zName);
  87387. sqlite3SrcListDelete(db, pTableName);
  87388. sqlite3IdListDelete(db, pColumns);
  87389. sqlite3ExprDelete(db, pWhen);
  87390. if( !pParse->pNewTrigger ){
  87391. sqlite3DeleteTrigger(db, pTrigger);
  87392. }else{
  87393. assert( pParse->pNewTrigger==pTrigger );
  87394. }
  87395. }
  87396. /*
  87397. ** This routine is called after all of the trigger actions have been parsed
  87398. ** in order to complete the process of building the trigger.
  87399. */
  87400. SQLITE_PRIVATE void sqlite3FinishTrigger(
  87401. Parse *pParse, /* Parser context */
  87402. TriggerStep *pStepList, /* The triggered program */
  87403. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  87404. ){
  87405. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  87406. char *zName; /* Name of trigger */
  87407. sqlite3 *db = pParse->db; /* The database */
  87408. DbFixer sFix; /* Fixer object */
  87409. int iDb; /* Database containing the trigger */
  87410. Token nameToken; /* Trigger name for error reporting */
  87411. pParse->pNewTrigger = 0;
  87412. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  87413. zName = pTrig->zName;
  87414. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  87415. pTrig->step_list = pStepList;
  87416. while( pStepList ){
  87417. pStepList->pTrig = pTrig;
  87418. pStepList = pStepList->pNext;
  87419. }
  87420. nameToken.z = pTrig->zName;
  87421. nameToken.n = sqlite3Strlen30(nameToken.z);
  87422. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  87423. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  87424. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  87425. ){
  87426. goto triggerfinish_cleanup;
  87427. }
  87428. /* if we are not initializing,
  87429. ** build the sqlite_master entry
  87430. */
  87431. if( !db->init.busy ){
  87432. Vdbe *v;
  87433. char *z;
  87434. /* Make an entry in the sqlite_master table */
  87435. v = sqlite3GetVdbe(pParse);
  87436. if( v==0 ) goto triggerfinish_cleanup;
  87437. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87438. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  87439. sqlite3NestedParse(pParse,
  87440. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  87441. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  87442. pTrig->table, z);
  87443. sqlite3DbFree(db, z);
  87444. sqlite3ChangeCookie(pParse, iDb);
  87445. sqlite3VdbeAddParseSchemaOp(v, iDb,
  87446. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  87447. }
  87448. if( db->init.busy ){
  87449. Trigger *pLink = pTrig;
  87450. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  87451. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87452. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  87453. if( pTrig ){
  87454. db->mallocFailed = 1;
  87455. }else if( pLink->pSchema==pLink->pTabSchema ){
  87456. Table *pTab;
  87457. int n = sqlite3Strlen30(pLink->table);
  87458. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  87459. assert( pTab!=0 );
  87460. pLink->pNext = pTab->pTrigger;
  87461. pTab->pTrigger = pLink;
  87462. }
  87463. }
  87464. triggerfinish_cleanup:
  87465. sqlite3DeleteTrigger(db, pTrig);
  87466. assert( !pParse->pNewTrigger );
  87467. sqlite3DeleteTriggerStep(db, pStepList);
  87468. }
  87469. /*
  87470. ** Turn a SELECT statement (that the pSelect parameter points to) into
  87471. ** a trigger step. Return a pointer to a TriggerStep structure.
  87472. **
  87473. ** The parser calls this routine when it finds a SELECT statement in
  87474. ** body of a TRIGGER.
  87475. */
  87476. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  87477. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  87478. if( pTriggerStep==0 ) {
  87479. sqlite3SelectDelete(db, pSelect);
  87480. return 0;
  87481. }
  87482. pTriggerStep->op = TK_SELECT;
  87483. pTriggerStep->pSelect = pSelect;
  87484. pTriggerStep->orconf = OE_Default;
  87485. return pTriggerStep;
  87486. }
  87487. /*
  87488. ** Allocate space to hold a new trigger step. The allocated space
  87489. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  87490. **
  87491. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  87492. */
  87493. static TriggerStep *triggerStepAllocate(
  87494. sqlite3 *db, /* Database connection */
  87495. u8 op, /* Trigger opcode */
  87496. Token *pName /* The target name */
  87497. ){
  87498. TriggerStep *pTriggerStep;
  87499. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  87500. if( pTriggerStep ){
  87501. char *z = (char*)&pTriggerStep[1];
  87502. memcpy(z, pName->z, pName->n);
  87503. pTriggerStep->target.z = z;
  87504. pTriggerStep->target.n = pName->n;
  87505. pTriggerStep->op = op;
  87506. }
  87507. return pTriggerStep;
  87508. }
  87509. /*
  87510. ** Build a trigger step out of an INSERT statement. Return a pointer
  87511. ** to the new trigger step.
  87512. **
  87513. ** The parser calls this routine when it sees an INSERT inside the
  87514. ** body of a trigger.
  87515. */
  87516. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  87517. sqlite3 *db, /* The database connection */
  87518. Token *pTableName, /* Name of the table into which we insert */
  87519. IdList *pColumn, /* List of columns in pTableName to insert into */
  87520. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  87521. Select *pSelect, /* A SELECT statement that supplies values */
  87522. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  87523. ){
  87524. TriggerStep *pTriggerStep;
  87525. assert(pEList == 0 || pSelect == 0);
  87526. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  87527. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  87528. if( pTriggerStep ){
  87529. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  87530. pTriggerStep->pIdList = pColumn;
  87531. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  87532. pTriggerStep->orconf = orconf;
  87533. }else{
  87534. sqlite3IdListDelete(db, pColumn);
  87535. }
  87536. sqlite3ExprListDelete(db, pEList);
  87537. sqlite3SelectDelete(db, pSelect);
  87538. return pTriggerStep;
  87539. }
  87540. /*
  87541. ** Construct a trigger step that implements an UPDATE statement and return
  87542. ** a pointer to that trigger step. The parser calls this routine when it
  87543. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  87544. */
  87545. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  87546. sqlite3 *db, /* The database connection */
  87547. Token *pTableName, /* Name of the table to be updated */
  87548. ExprList *pEList, /* The SET clause: list of column and new values */
  87549. Expr *pWhere, /* The WHERE clause */
  87550. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  87551. ){
  87552. TriggerStep *pTriggerStep;
  87553. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  87554. if( pTriggerStep ){
  87555. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  87556. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  87557. pTriggerStep->orconf = orconf;
  87558. }
  87559. sqlite3ExprListDelete(db, pEList);
  87560. sqlite3ExprDelete(db, pWhere);
  87561. return pTriggerStep;
  87562. }
  87563. /*
  87564. ** Construct a trigger step that implements a DELETE statement and return
  87565. ** a pointer to that trigger step. The parser calls this routine when it
  87566. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  87567. */
  87568. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  87569. sqlite3 *db, /* Database connection */
  87570. Token *pTableName, /* The table from which rows are deleted */
  87571. Expr *pWhere /* The WHERE clause */
  87572. ){
  87573. TriggerStep *pTriggerStep;
  87574. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  87575. if( pTriggerStep ){
  87576. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  87577. pTriggerStep->orconf = OE_Default;
  87578. }
  87579. sqlite3ExprDelete(db, pWhere);
  87580. return pTriggerStep;
  87581. }
  87582. /*
  87583. ** Recursively delete a Trigger structure
  87584. */
  87585. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  87586. if( pTrigger==0 ) return;
  87587. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  87588. sqlite3DbFree(db, pTrigger->zName);
  87589. sqlite3DbFree(db, pTrigger->table);
  87590. sqlite3ExprDelete(db, pTrigger->pWhen);
  87591. sqlite3IdListDelete(db, pTrigger->pColumns);
  87592. sqlite3DbFree(db, pTrigger);
  87593. }
  87594. /*
  87595. ** This function is called to drop a trigger from the database schema.
  87596. **
  87597. ** This may be called directly from the parser and therefore identifies
  87598. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  87599. ** same job as this routine except it takes a pointer to the trigger
  87600. ** instead of the trigger name.
  87601. **/
  87602. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  87603. Trigger *pTrigger = 0;
  87604. int i;
  87605. const char *zDb;
  87606. const char *zName;
  87607. int nName;
  87608. sqlite3 *db = pParse->db;
  87609. if( db->mallocFailed ) goto drop_trigger_cleanup;
  87610. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87611. goto drop_trigger_cleanup;
  87612. }
  87613. assert( pName->nSrc==1 );
  87614. zDb = pName->a[0].zDatabase;
  87615. zName = pName->a[0].zName;
  87616. nName = sqlite3Strlen30(zName);
  87617. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  87618. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  87619. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  87620. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  87621. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  87622. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  87623. if( pTrigger ) break;
  87624. }
  87625. if( !pTrigger ){
  87626. if( !noErr ){
  87627. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  87628. }else{
  87629. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  87630. }
  87631. pParse->checkSchema = 1;
  87632. goto drop_trigger_cleanup;
  87633. }
  87634. sqlite3DropTriggerPtr(pParse, pTrigger);
  87635. drop_trigger_cleanup:
  87636. sqlite3SrcListDelete(db, pName);
  87637. }
  87638. /*
  87639. ** Return a pointer to the Table structure for the table that a trigger
  87640. ** is set on.
  87641. */
  87642. static Table *tableOfTrigger(Trigger *pTrigger){
  87643. int n = sqlite3Strlen30(pTrigger->table);
  87644. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  87645. }
  87646. /*
  87647. ** Drop a trigger given a pointer to that trigger.
  87648. */
  87649. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  87650. Table *pTable;
  87651. Vdbe *v;
  87652. sqlite3 *db = pParse->db;
  87653. int iDb;
  87654. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  87655. assert( iDb>=0 && iDb<db->nDb );
  87656. pTable = tableOfTrigger(pTrigger);
  87657. assert( pTable );
  87658. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  87659. #ifndef SQLITE_OMIT_AUTHORIZATION
  87660. {
  87661. int code = SQLITE_DROP_TRIGGER;
  87662. const char *zDb = db->aDb[iDb].zName;
  87663. const char *zTab = SCHEMA_TABLE(iDb);
  87664. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  87665. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  87666. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  87667. return;
  87668. }
  87669. }
  87670. #endif
  87671. /* Generate code to destroy the database record of the trigger.
  87672. */
  87673. assert( pTable!=0 );
  87674. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  87675. int base;
  87676. static const VdbeOpList dropTrigger[] = {
  87677. { OP_Rewind, 0, ADDR(9), 0},
  87678. { OP_String8, 0, 1, 0}, /* 1 */
  87679. { OP_Column, 0, 1, 2},
  87680. { OP_Ne, 2, ADDR(8), 1},
  87681. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  87682. { OP_Column, 0, 0, 2},
  87683. { OP_Ne, 2, ADDR(8), 1},
  87684. { OP_Delete, 0, 0, 0},
  87685. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  87686. };
  87687. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87688. sqlite3OpenMasterTable(pParse, iDb);
  87689. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  87690. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  87691. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  87692. sqlite3ChangeCookie(pParse, iDb);
  87693. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  87694. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  87695. if( pParse->nMem<3 ){
  87696. pParse->nMem = 3;
  87697. }
  87698. }
  87699. }
  87700. /*
  87701. ** Remove a trigger from the hash tables of the sqlite* pointer.
  87702. */
  87703. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  87704. Trigger *pTrigger;
  87705. Hash *pHash;
  87706. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87707. pHash = &(db->aDb[iDb].pSchema->trigHash);
  87708. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  87709. if( ALWAYS(pTrigger) ){
  87710. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  87711. Table *pTab = tableOfTrigger(pTrigger);
  87712. Trigger **pp;
  87713. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  87714. *pp = (*pp)->pNext;
  87715. }
  87716. sqlite3DeleteTrigger(db, pTrigger);
  87717. db->flags |= SQLITE_InternChanges;
  87718. }
  87719. }
  87720. /*
  87721. ** pEList is the SET clause of an UPDATE statement. Each entry
  87722. ** in pEList is of the format <id>=<expr>. If any of the entries
  87723. ** in pEList have an <id> which matches an identifier in pIdList,
  87724. ** then return TRUE. If pIdList==NULL, then it is considered a
  87725. ** wildcard that matches anything. Likewise if pEList==NULL then
  87726. ** it matches anything so always return true. Return false only
  87727. ** if there is no match.
  87728. */
  87729. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  87730. int e;
  87731. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  87732. for(e=0; e<pEList->nExpr; e++){
  87733. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  87734. }
  87735. return 0;
  87736. }
  87737. /*
  87738. ** Return a list of all triggers on table pTab if there exists at least
  87739. ** one trigger that must be fired when an operation of type 'op' is
  87740. ** performed on the table, and, if that operation is an UPDATE, if at
  87741. ** least one of the columns in pChanges is being modified.
  87742. */
  87743. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  87744. Parse *pParse, /* Parse context */
  87745. Table *pTab, /* The table the contains the triggers */
  87746. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  87747. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  87748. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  87749. ){
  87750. int mask = 0;
  87751. Trigger *pList = 0;
  87752. Trigger *p;
  87753. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  87754. pList = sqlite3TriggerList(pParse, pTab);
  87755. }
  87756. assert( pList==0 || IsVirtual(pTab)==0 );
  87757. for(p=pList; p; p=p->pNext){
  87758. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  87759. mask |= p->tr_tm;
  87760. }
  87761. }
  87762. if( pMask ){
  87763. *pMask = mask;
  87764. }
  87765. return (mask ? pList : 0);
  87766. }
  87767. /*
  87768. ** Convert the pStep->target token into a SrcList and return a pointer
  87769. ** to that SrcList.
  87770. **
  87771. ** This routine adds a specific database name, if needed, to the target when
  87772. ** forming the SrcList. This prevents a trigger in one database from
  87773. ** referring to a target in another database. An exception is when the
  87774. ** trigger is in TEMP in which case it can refer to any other database it
  87775. ** wants.
  87776. */
  87777. static SrcList *targetSrcList(
  87778. Parse *pParse, /* The parsing context */
  87779. TriggerStep *pStep /* The trigger containing the target token */
  87780. ){
  87781. int iDb; /* Index of the database to use */
  87782. SrcList *pSrc; /* SrcList to be returned */
  87783. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  87784. if( pSrc ){
  87785. assert( pSrc->nSrc>0 );
  87786. assert( pSrc->a!=0 );
  87787. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  87788. if( iDb==0 || iDb>=2 ){
  87789. sqlite3 *db = pParse->db;
  87790. assert( iDb<pParse->db->nDb );
  87791. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  87792. }
  87793. }
  87794. return pSrc;
  87795. }
  87796. /*
  87797. ** Generate VDBE code for the statements inside the body of a single
  87798. ** trigger.
  87799. */
  87800. static int codeTriggerProgram(
  87801. Parse *pParse, /* The parser context */
  87802. TriggerStep *pStepList, /* List of statements inside the trigger body */
  87803. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  87804. ){
  87805. TriggerStep *pStep;
  87806. Vdbe *v = pParse->pVdbe;
  87807. sqlite3 *db = pParse->db;
  87808. assert( pParse->pTriggerTab && pParse->pToplevel );
  87809. assert( pStepList );
  87810. assert( v!=0 );
  87811. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  87812. /* Figure out the ON CONFLICT policy that will be used for this step
  87813. ** of the trigger program. If the statement that caused this trigger
  87814. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  87815. ** the ON CONFLICT policy that was specified as part of the trigger
  87816. ** step statement. Example:
  87817. **
  87818. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  87819. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  87820. ** END;
  87821. **
  87822. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  87823. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  87824. */
  87825. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  87826. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  87827. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  87828. ** that it is not safe to refactor constants (this happens after the
  87829. ** start of the first loop in the SQL statement is coded - at that
  87830. ** point code may be conditionally executed, so it is no longer safe to
  87831. ** initialize constant register values). */
  87832. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  87833. pParse->cookieGoto = 0;
  87834. switch( pStep->op ){
  87835. case TK_UPDATE: {
  87836. sqlite3Update(pParse,
  87837. targetSrcList(pParse, pStep),
  87838. sqlite3ExprListDup(db, pStep->pExprList, 0),
  87839. sqlite3ExprDup(db, pStep->pWhere, 0),
  87840. pParse->eOrconf
  87841. );
  87842. break;
  87843. }
  87844. case TK_INSERT: {
  87845. sqlite3Insert(pParse,
  87846. targetSrcList(pParse, pStep),
  87847. sqlite3ExprListDup(db, pStep->pExprList, 0),
  87848. sqlite3SelectDup(db, pStep->pSelect, 0),
  87849. sqlite3IdListDup(db, pStep->pIdList),
  87850. pParse->eOrconf
  87851. );
  87852. break;
  87853. }
  87854. case TK_DELETE: {
  87855. sqlite3DeleteFrom(pParse,
  87856. targetSrcList(pParse, pStep),
  87857. sqlite3ExprDup(db, pStep->pWhere, 0)
  87858. );
  87859. break;
  87860. }
  87861. default: assert( pStep->op==TK_SELECT ); {
  87862. SelectDest sDest;
  87863. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  87864. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  87865. sqlite3Select(pParse, pSelect, &sDest);
  87866. sqlite3SelectDelete(db, pSelect);
  87867. break;
  87868. }
  87869. }
  87870. if( pStep->op!=TK_SELECT ){
  87871. sqlite3VdbeAddOp0(v, OP_ResetCount);
  87872. }
  87873. }
  87874. return 0;
  87875. }
  87876. #ifdef SQLITE_DEBUG
  87877. /*
  87878. ** This function is used to add VdbeComment() annotations to a VDBE
  87879. ** program. It is not used in production code, only for debugging.
  87880. */
  87881. static const char *onErrorText(int onError){
  87882. switch( onError ){
  87883. case OE_Abort: return "abort";
  87884. case OE_Rollback: return "rollback";
  87885. case OE_Fail: return "fail";
  87886. case OE_Replace: return "replace";
  87887. case OE_Ignore: return "ignore";
  87888. case OE_Default: return "default";
  87889. }
  87890. return "n/a";
  87891. }
  87892. #endif
  87893. /*
  87894. ** Parse context structure pFrom has just been used to create a sub-vdbe
  87895. ** (trigger program). If an error has occurred, transfer error information
  87896. ** from pFrom to pTo.
  87897. */
  87898. static void transferParseError(Parse *pTo, Parse *pFrom){
  87899. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  87900. assert( pTo->zErrMsg==0 || pTo->nErr );
  87901. if( pTo->nErr==0 ){
  87902. pTo->zErrMsg = pFrom->zErrMsg;
  87903. pTo->nErr = pFrom->nErr;
  87904. }else{
  87905. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  87906. }
  87907. }
  87908. /*
  87909. ** Create and populate a new TriggerPrg object with a sub-program
  87910. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  87911. */
  87912. static TriggerPrg *codeRowTrigger(
  87913. Parse *pParse, /* Current parse context */
  87914. Trigger *pTrigger, /* Trigger to code */
  87915. Table *pTab, /* The table pTrigger is attached to */
  87916. int orconf /* ON CONFLICT policy to code trigger program with */
  87917. ){
  87918. Parse *pTop = sqlite3ParseToplevel(pParse);
  87919. sqlite3 *db = pParse->db; /* Database handle */
  87920. TriggerPrg *pPrg; /* Value to return */
  87921. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  87922. Vdbe *v; /* Temporary VM */
  87923. NameContext sNC; /* Name context for sub-vdbe */
  87924. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  87925. Parse *pSubParse; /* Parse context for sub-vdbe */
  87926. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  87927. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  87928. assert( pTop->pVdbe );
  87929. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  87930. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  87931. ** list of the top-level Parse object sooner rather than later. */
  87932. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  87933. if( !pPrg ) return 0;
  87934. pPrg->pNext = pTop->pTriggerPrg;
  87935. pTop->pTriggerPrg = pPrg;
  87936. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  87937. if( !pProgram ) return 0;
  87938. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  87939. pPrg->pTrigger = pTrigger;
  87940. pPrg->orconf = orconf;
  87941. pPrg->aColmask[0] = 0xffffffff;
  87942. pPrg->aColmask[1] = 0xffffffff;
  87943. /* Allocate and populate a new Parse context to use for coding the
  87944. ** trigger sub-program. */
  87945. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  87946. if( !pSubParse ) return 0;
  87947. memset(&sNC, 0, sizeof(sNC));
  87948. sNC.pParse = pSubParse;
  87949. pSubParse->db = db;
  87950. pSubParse->pTriggerTab = pTab;
  87951. pSubParse->pToplevel = pTop;
  87952. pSubParse->zAuthContext = pTrigger->zName;
  87953. pSubParse->eTriggerOp = pTrigger->op;
  87954. pSubParse->nQueryLoop = pParse->nQueryLoop;
  87955. v = sqlite3GetVdbe(pSubParse);
  87956. if( v ){
  87957. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  87958. pTrigger->zName, onErrorText(orconf),
  87959. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  87960. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  87961. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  87962. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  87963. pTab->zName
  87964. ));
  87965. #ifndef SQLITE_OMIT_TRACE
  87966. sqlite3VdbeChangeP4(v, -1,
  87967. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  87968. );
  87969. #endif
  87970. /* If one was specified, code the WHEN clause. If it evaluates to false
  87971. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  87972. ** OP_Halt inserted at the end of the program. */
  87973. if( pTrigger->pWhen ){
  87974. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  87975. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  87976. && db->mallocFailed==0
  87977. ){
  87978. iEndTrigger = sqlite3VdbeMakeLabel(v);
  87979. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  87980. }
  87981. sqlite3ExprDelete(db, pWhen);
  87982. }
  87983. /* Code the trigger program into the sub-vdbe. */
  87984. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  87985. /* Insert an OP_Halt at the end of the sub-program. */
  87986. if( iEndTrigger ){
  87987. sqlite3VdbeResolveLabel(v, iEndTrigger);
  87988. }
  87989. sqlite3VdbeAddOp0(v, OP_Halt);
  87990. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  87991. transferParseError(pParse, pSubParse);
  87992. if( db->mallocFailed==0 ){
  87993. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  87994. }
  87995. pProgram->nMem = pSubParse->nMem;
  87996. pProgram->nCsr = pSubParse->nTab;
  87997. pProgram->nOnce = pSubParse->nOnce;
  87998. pProgram->token = (void *)pTrigger;
  87999. pPrg->aColmask[0] = pSubParse->oldmask;
  88000. pPrg->aColmask[1] = pSubParse->newmask;
  88001. sqlite3VdbeDelete(v);
  88002. }
  88003. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  88004. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  88005. sqlite3StackFree(db, pSubParse);
  88006. return pPrg;
  88007. }
  88008. /*
  88009. ** Return a pointer to a TriggerPrg object containing the sub-program for
  88010. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  88011. ** TriggerPrg object exists, a new object is allocated and populated before
  88012. ** being returned.
  88013. */
  88014. static TriggerPrg *getRowTrigger(
  88015. Parse *pParse, /* Current parse context */
  88016. Trigger *pTrigger, /* Trigger to code */
  88017. Table *pTab, /* The table trigger pTrigger is attached to */
  88018. int orconf /* ON CONFLICT algorithm. */
  88019. ){
  88020. Parse *pRoot = sqlite3ParseToplevel(pParse);
  88021. TriggerPrg *pPrg;
  88022. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  88023. /* It may be that this trigger has already been coded (or is in the
  88024. ** process of being coded). If this is the case, then an entry with
  88025. ** a matching TriggerPrg.pTrigger field will be present somewhere
  88026. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  88027. for(pPrg=pRoot->pTriggerPrg;
  88028. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  88029. pPrg=pPrg->pNext
  88030. );
  88031. /* If an existing TriggerPrg could not be located, create a new one. */
  88032. if( !pPrg ){
  88033. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  88034. }
  88035. return pPrg;
  88036. }
  88037. /*
  88038. ** Generate code for the trigger program associated with trigger p on
  88039. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  88040. ** function are the same as those described in the header function for
  88041. ** sqlite3CodeRowTrigger()
  88042. */
  88043. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  88044. Parse *pParse, /* Parse context */
  88045. Trigger *p, /* Trigger to code */
  88046. Table *pTab, /* The table to code triggers from */
  88047. int reg, /* Reg array containing OLD.* and NEW.* values */
  88048. int orconf, /* ON CONFLICT policy */
  88049. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  88050. ){
  88051. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  88052. TriggerPrg *pPrg;
  88053. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  88054. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  88055. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  88056. ** is a pointer to the sub-vdbe containing the trigger program. */
  88057. if( pPrg ){
  88058. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  88059. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  88060. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  88061. VdbeComment(
  88062. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  88063. /* Set the P5 operand of the OP_Program instruction to non-zero if
  88064. ** recursive invocation of this trigger program is disallowed. Recursive
  88065. ** invocation is disallowed if (a) the sub-program is really a trigger,
  88066. ** not a foreign key action, and (b) the flag to enable recursive triggers
  88067. ** is clear. */
  88068. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  88069. }
  88070. }
  88071. /*
  88072. ** This is called to code the required FOR EACH ROW triggers for an operation
  88073. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  88074. ** is given by the op parameter. The tr_tm parameter determines whether the
  88075. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  88076. ** parameter pChanges is passed the list of columns being modified.
  88077. **
  88078. ** If there are no triggers that fire at the specified time for the specified
  88079. ** operation on pTab, this function is a no-op.
  88080. **
  88081. ** The reg argument is the address of the first in an array of registers
  88082. ** that contain the values substituted for the new.* and old.* references
  88083. ** in the trigger program. If N is the number of columns in table pTab
  88084. ** (a copy of pTab->nCol), then registers are populated as follows:
  88085. **
  88086. ** Register Contains
  88087. ** ------------------------------------------------------
  88088. ** reg+0 OLD.rowid
  88089. ** reg+1 OLD.* value of left-most column of pTab
  88090. ** ... ...
  88091. ** reg+N OLD.* value of right-most column of pTab
  88092. ** reg+N+1 NEW.rowid
  88093. ** reg+N+2 OLD.* value of left-most column of pTab
  88094. ** ... ...
  88095. ** reg+N+N+1 NEW.* value of right-most column of pTab
  88096. **
  88097. ** For ON DELETE triggers, the registers containing the NEW.* values will
  88098. ** never be accessed by the trigger program, so they are not allocated or
  88099. ** populated by the caller (there is no data to populate them with anyway).
  88100. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  88101. ** are never accessed, and so are not allocated by the caller. So, for an
  88102. ** ON INSERT trigger, the value passed to this function as parameter reg
  88103. ** is not a readable register, although registers (reg+N) through
  88104. ** (reg+N+N+1) are.
  88105. **
  88106. ** Parameter orconf is the default conflict resolution algorithm for the
  88107. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  88108. ** is the instruction that control should jump to if a trigger program
  88109. ** raises an IGNORE exception.
  88110. */
  88111. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  88112. Parse *pParse, /* Parse context */
  88113. Trigger *pTrigger, /* List of triggers on table pTab */
  88114. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  88115. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  88116. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  88117. Table *pTab, /* The table to code triggers from */
  88118. int reg, /* The first in an array of registers (see above) */
  88119. int orconf, /* ON CONFLICT policy */
  88120. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  88121. ){
  88122. Trigger *p; /* Used to iterate through pTrigger list */
  88123. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  88124. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  88125. assert( (op==TK_UPDATE)==(pChanges!=0) );
  88126. for(p=pTrigger; p; p=p->pNext){
  88127. /* Sanity checking: The schema for the trigger and for the table are
  88128. ** always defined. The trigger must be in the same schema as the table
  88129. ** or else it must be a TEMP trigger. */
  88130. assert( p->pSchema!=0 );
  88131. assert( p->pTabSchema!=0 );
  88132. assert( p->pSchema==p->pTabSchema
  88133. || p->pSchema==pParse->db->aDb[1].pSchema );
  88134. /* Determine whether we should code this trigger */
  88135. if( p->op==op
  88136. && p->tr_tm==tr_tm
  88137. && checkColumnOverlap(p->pColumns, pChanges)
  88138. ){
  88139. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  88140. }
  88141. }
  88142. }
  88143. /*
  88144. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  88145. ** This function returns a 32-bit bitmask indicating which columns of the
  88146. ** old.* or new.* tables actually are used by triggers. This information
  88147. ** may be used by the caller, for example, to avoid having to load the entire
  88148. ** old.* record into memory when executing an UPDATE or DELETE command.
  88149. **
  88150. ** Bit 0 of the returned mask is set if the left-most column of the
  88151. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  88152. ** the second leftmost column value is required, and so on. If there
  88153. ** are more than 32 columns in the table, and at least one of the columns
  88154. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  88155. **
  88156. ** It is not possible to determine if the old.rowid or new.rowid column is
  88157. ** accessed by triggers. The caller must always assume that it is.
  88158. **
  88159. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  88160. ** applies to the old.* table. If 1, the new.* table.
  88161. **
  88162. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  88163. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  88164. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  88165. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  88166. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  88167. */
  88168. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  88169. Parse *pParse, /* Parse context */
  88170. Trigger *pTrigger, /* List of triggers on table pTab */
  88171. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  88172. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  88173. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  88174. Table *pTab, /* The table to code triggers from */
  88175. int orconf /* Default ON CONFLICT policy for trigger steps */
  88176. ){
  88177. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  88178. u32 mask = 0;
  88179. Trigger *p;
  88180. assert( isNew==1 || isNew==0 );
  88181. for(p=pTrigger; p; p=p->pNext){
  88182. if( p->op==op && (tr_tm&p->tr_tm)
  88183. && checkColumnOverlap(p->pColumns,pChanges)
  88184. ){
  88185. TriggerPrg *pPrg;
  88186. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  88187. if( pPrg ){
  88188. mask |= pPrg->aColmask[isNew];
  88189. }
  88190. }
  88191. }
  88192. return mask;
  88193. }
  88194. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  88195. /************** End of trigger.c *********************************************/
  88196. /************** Begin file update.c ******************************************/
  88197. /*
  88198. ** 2001 September 15
  88199. **
  88200. ** The author disclaims copyright to this source code. In place of
  88201. ** a legal notice, here is a blessing:
  88202. **
  88203. ** May you do good and not evil.
  88204. ** May you find forgiveness for yourself and forgive others.
  88205. ** May you share freely, never taking more than you give.
  88206. **
  88207. *************************************************************************
  88208. ** This file contains C code routines that are called by the parser
  88209. ** to handle UPDATE statements.
  88210. */
  88211. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88212. /* Forward declaration */
  88213. static void updateVirtualTable(
  88214. Parse *pParse, /* The parsing context */
  88215. SrcList *pSrc, /* The virtual table to be modified */
  88216. Table *pTab, /* The virtual table */
  88217. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  88218. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  88219. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  88220. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  88221. int onError /* ON CONFLICT strategy */
  88222. );
  88223. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  88224. /*
  88225. ** The most recently coded instruction was an OP_Column to retrieve the
  88226. ** i-th column of table pTab. This routine sets the P4 parameter of the
  88227. ** OP_Column to the default value, if any.
  88228. **
  88229. ** The default value of a column is specified by a DEFAULT clause in the
  88230. ** column definition. This was either supplied by the user when the table
  88231. ** was created, or added later to the table definition by an ALTER TABLE
  88232. ** command. If the latter, then the row-records in the table btree on disk
  88233. ** may not contain a value for the column and the default value, taken
  88234. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  88235. ** If the former, then all row-records are guaranteed to include a value
  88236. ** for the column and the P4 value is not required.
  88237. **
  88238. ** Column definitions created by an ALTER TABLE command may only have
  88239. ** literal default values specified: a number, null or a string. (If a more
  88240. ** complicated default expression value was provided, it is evaluated
  88241. ** when the ALTER TABLE is executed and one of the literal values written
  88242. ** into the sqlite_master table.)
  88243. **
  88244. ** Therefore, the P4 parameter is only required if the default value for
  88245. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  88246. ** function is capable of transforming these types of expressions into
  88247. ** sqlite3_value objects.
  88248. **
  88249. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  88250. ** on register iReg. This is used when an equivalent integer value is
  88251. ** stored in place of an 8-byte floating point value in order to save
  88252. ** space.
  88253. */
  88254. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  88255. assert( pTab!=0 );
  88256. if( !pTab->pSelect ){
  88257. sqlite3_value *pValue = 0;
  88258. u8 enc = ENC(sqlite3VdbeDb(v));
  88259. Column *pCol = &pTab->aCol[i];
  88260. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  88261. assert( i<pTab->nCol );
  88262. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  88263. pCol->affinity, &pValue);
  88264. if( pValue ){
  88265. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  88266. }
  88267. #ifndef SQLITE_OMIT_FLOATING_POINT
  88268. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  88269. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  88270. }
  88271. #endif
  88272. }
  88273. }
  88274. /*
  88275. ** Process an UPDATE statement.
  88276. **
  88277. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  88278. ** \_______/ \________/ \______/ \________________/
  88279. * onError pTabList pChanges pWhere
  88280. */
  88281. SQLITE_PRIVATE void sqlite3Update(
  88282. Parse *pParse, /* The parser context */
  88283. SrcList *pTabList, /* The table in which we should change things */
  88284. ExprList *pChanges, /* Things to be changed */
  88285. Expr *pWhere, /* The WHERE clause. May be null */
  88286. int onError /* How to handle constraint errors */
  88287. ){
  88288. int i, j; /* Loop counters */
  88289. Table *pTab; /* The table to be updated */
  88290. int addr = 0; /* VDBE instruction address of the start of the loop */
  88291. WhereInfo *pWInfo; /* Information about the WHERE clause */
  88292. Vdbe *v; /* The virtual database engine */
  88293. Index *pIdx; /* For looping over indices */
  88294. int nIdx; /* Number of indices that need updating */
  88295. int iCur; /* VDBE Cursor number of pTab */
  88296. sqlite3 *db; /* The database structure */
  88297. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  88298. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  88299. ** an expression for the i-th column of the table.
  88300. ** aXRef[i]==-1 if the i-th column is not changed. */
  88301. int chngRowid; /* True if the record number is being changed */
  88302. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  88303. int openAll = 0; /* True if all indices need to be opened */
  88304. AuthContext sContext; /* The authorization context */
  88305. NameContext sNC; /* The name-context to resolve expressions in */
  88306. int iDb; /* Database containing the table being updated */
  88307. int okOnePass; /* True for one-pass algorithm without the FIFO */
  88308. int hasFK; /* True if foreign key processing is required */
  88309. #ifndef SQLITE_OMIT_TRIGGER
  88310. int isView; /* True when updating a view (INSTEAD OF trigger) */
  88311. Trigger *pTrigger; /* List of triggers on pTab, if required */
  88312. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  88313. #endif
  88314. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  88315. /* Register Allocations */
  88316. int regRowCount = 0; /* A count of rows changed */
  88317. int regOldRowid; /* The old rowid */
  88318. int regNewRowid; /* The new rowid */
  88319. int regNew; /* Content of the NEW.* table in triggers */
  88320. int regOld = 0; /* Content of OLD.* table in triggers */
  88321. int regRowSet = 0; /* Rowset of rows to be updated */
  88322. memset(&sContext, 0, sizeof(sContext));
  88323. db = pParse->db;
  88324. if( pParse->nErr || db->mallocFailed ){
  88325. goto update_cleanup;
  88326. }
  88327. assert( pTabList->nSrc==1 );
  88328. /* Locate the table which we want to update.
  88329. */
  88330. pTab = sqlite3SrcListLookup(pParse, pTabList);
  88331. if( pTab==0 ) goto update_cleanup;
  88332. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88333. /* Figure out if we have any triggers and if the table being
  88334. ** updated is a view.
  88335. */
  88336. #ifndef SQLITE_OMIT_TRIGGER
  88337. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  88338. isView = pTab->pSelect!=0;
  88339. assert( pTrigger || tmask==0 );
  88340. #else
  88341. # define pTrigger 0
  88342. # define isView 0
  88343. # define tmask 0
  88344. #endif
  88345. #ifdef SQLITE_OMIT_VIEW
  88346. # undef isView
  88347. # define isView 0
  88348. #endif
  88349. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  88350. goto update_cleanup;
  88351. }
  88352. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  88353. goto update_cleanup;
  88354. }
  88355. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  88356. if( aXRef==0 ) goto update_cleanup;
  88357. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  88358. /* Allocate a cursors for the main database table and for all indices.
  88359. ** The index cursors might not be used, but if they are used they
  88360. ** need to occur right after the database cursor. So go ahead and
  88361. ** allocate enough space, just in case.
  88362. */
  88363. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  88364. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88365. pParse->nTab++;
  88366. }
  88367. /* Initialize the name-context */
  88368. memset(&sNC, 0, sizeof(sNC));
  88369. sNC.pParse = pParse;
  88370. sNC.pSrcList = pTabList;
  88371. /* Resolve the column names in all the expressions of the
  88372. ** of the UPDATE statement. Also find the column index
  88373. ** for each column to be updated in the pChanges array. For each
  88374. ** column to be updated, make sure we have authorization to change
  88375. ** that column.
  88376. */
  88377. chngRowid = 0;
  88378. for(i=0; i<pChanges->nExpr; i++){
  88379. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  88380. goto update_cleanup;
  88381. }
  88382. for(j=0; j<pTab->nCol; j++){
  88383. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  88384. if( j==pTab->iPKey ){
  88385. chngRowid = 1;
  88386. pRowidExpr = pChanges->a[i].pExpr;
  88387. }
  88388. aXRef[j] = i;
  88389. break;
  88390. }
  88391. }
  88392. if( j>=pTab->nCol ){
  88393. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  88394. j = -1;
  88395. chngRowid = 1;
  88396. pRowidExpr = pChanges->a[i].pExpr;
  88397. }else{
  88398. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  88399. pParse->checkSchema = 1;
  88400. goto update_cleanup;
  88401. }
  88402. }
  88403. #ifndef SQLITE_OMIT_AUTHORIZATION
  88404. {
  88405. int rc;
  88406. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  88407. j<0 ? "ROWID" : pTab->aCol[j].zName,
  88408. db->aDb[iDb].zName);
  88409. if( rc==SQLITE_DENY ){
  88410. goto update_cleanup;
  88411. }else if( rc==SQLITE_IGNORE ){
  88412. aXRef[j] = -1;
  88413. }
  88414. }
  88415. #endif
  88416. }
  88417. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  88418. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  88419. ** array for each index associated with table being updated. Fill in
  88420. ** the value with a register number for indices that are to be used
  88421. ** and with zero for unused indices.
  88422. */
  88423. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  88424. if( nIdx>0 ){
  88425. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  88426. if( aRegIdx==0 ) goto update_cleanup;
  88427. }
  88428. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  88429. int reg;
  88430. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  88431. reg = ++pParse->nMem;
  88432. }else{
  88433. reg = 0;
  88434. for(i=0; i<pIdx->nColumn; i++){
  88435. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  88436. reg = ++pParse->nMem;
  88437. break;
  88438. }
  88439. }
  88440. }
  88441. aRegIdx[j] = reg;
  88442. }
  88443. /* Begin generating code. */
  88444. v = sqlite3GetVdbe(pParse);
  88445. if( v==0 ) goto update_cleanup;
  88446. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  88447. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88448. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88449. /* Virtual tables must be handled separately */
  88450. if( IsVirtual(pTab) ){
  88451. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  88452. pWhere, onError);
  88453. pWhere = 0;
  88454. pTabList = 0;
  88455. goto update_cleanup;
  88456. }
  88457. #endif
  88458. /* Allocate required registers. */
  88459. regRowSet = ++pParse->nMem;
  88460. regOldRowid = regNewRowid = ++pParse->nMem;
  88461. if( pTrigger || hasFK ){
  88462. regOld = pParse->nMem + 1;
  88463. pParse->nMem += pTab->nCol;
  88464. }
  88465. if( chngRowid || pTrigger || hasFK ){
  88466. regNewRowid = ++pParse->nMem;
  88467. }
  88468. regNew = pParse->nMem + 1;
  88469. pParse->nMem += pTab->nCol;
  88470. /* Start the view context. */
  88471. if( isView ){
  88472. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  88473. }
  88474. /* If we are trying to update a view, realize that view into
  88475. ** a ephemeral table.
  88476. */
  88477. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  88478. if( isView ){
  88479. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  88480. }
  88481. #endif
  88482. /* Resolve the column names in all the expressions in the
  88483. ** WHERE clause.
  88484. */
  88485. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  88486. goto update_cleanup;
  88487. }
  88488. /* Begin the database scan
  88489. */
  88490. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  88491. pWInfo = sqlite3WhereBegin(
  88492. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  88493. );
  88494. if( pWInfo==0 ) goto update_cleanup;
  88495. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  88496. /* Remember the rowid of every item to be updated.
  88497. */
  88498. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  88499. if( !okOnePass ){
  88500. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  88501. }
  88502. /* End the database scan loop.
  88503. */
  88504. sqlite3WhereEnd(pWInfo);
  88505. /* Initialize the count of updated rows
  88506. */
  88507. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  88508. regRowCount = ++pParse->nMem;
  88509. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  88510. }
  88511. if( !isView ){
  88512. /*
  88513. ** Open every index that needs updating. Note that if any
  88514. ** index could potentially invoke a REPLACE conflict resolution
  88515. ** action, then we need to open all indices because we might need
  88516. ** to be deleting some records.
  88517. */
  88518. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  88519. if( onError==OE_Replace ){
  88520. openAll = 1;
  88521. }else{
  88522. openAll = 0;
  88523. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88524. if( pIdx->onError==OE_Replace ){
  88525. openAll = 1;
  88526. break;
  88527. }
  88528. }
  88529. }
  88530. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  88531. assert( aRegIdx );
  88532. if( openAll || aRegIdx[i]>0 ){
  88533. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  88534. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  88535. (char*)pKey, P4_KEYINFO_HANDOFF);
  88536. assert( pParse->nTab>iCur+i+1 );
  88537. }
  88538. }
  88539. }
  88540. /* Top of the update loop */
  88541. if( okOnePass ){
  88542. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  88543. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  88544. sqlite3VdbeJumpHere(v, a1);
  88545. }else{
  88546. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  88547. }
  88548. /* Make cursor iCur point to the record that is being updated. If
  88549. ** this record does not exist for some reason (deleted by a trigger,
  88550. ** for example, then jump to the next iteration of the RowSet loop. */
  88551. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  88552. /* If the record number will change, set register regNewRowid to
  88553. ** contain the new value. If the record number is not being modified,
  88554. ** then regNewRowid is the same register as regOldRowid, which is
  88555. ** already populated. */
  88556. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  88557. if( chngRowid ){
  88558. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  88559. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  88560. }
  88561. /* If there are triggers on this table, populate an array of registers
  88562. ** with the required old.* column data. */
  88563. if( hasFK || pTrigger ){
  88564. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  88565. oldmask |= sqlite3TriggerColmask(pParse,
  88566. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  88567. );
  88568. for(i=0; i<pTab->nCol; i++){
  88569. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  88570. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  88571. }else{
  88572. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  88573. }
  88574. }
  88575. if( chngRowid==0 ){
  88576. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  88577. }
  88578. }
  88579. /* Populate the array of registers beginning at regNew with the new
  88580. ** row data. This array is used to check constaints, create the new
  88581. ** table and index records, and as the values for any new.* references
  88582. ** made by triggers.
  88583. **
  88584. ** If there are one or more BEFORE triggers, then do not populate the
  88585. ** registers associated with columns that are (a) not modified by
  88586. ** this UPDATE statement and (b) not accessed by new.* references. The
  88587. ** values for registers not modified by the UPDATE must be reloaded from
  88588. ** the database after the BEFORE triggers are fired anyway (as the trigger
  88589. ** may have modified them). So not loading those that are not going to
  88590. ** be used eliminates some redundant opcodes.
  88591. */
  88592. newmask = sqlite3TriggerColmask(
  88593. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  88594. );
  88595. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  88596. for(i=0; i<pTab->nCol; i++){
  88597. if( i==pTab->iPKey ){
  88598. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  88599. }else{
  88600. j = aXRef[i];
  88601. if( j>=0 ){
  88602. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  88603. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  88604. /* This branch loads the value of a column that will not be changed
  88605. ** into a register. This is done if there are no BEFORE triggers, or
  88606. ** if there are one or more BEFORE triggers that use this value via
  88607. ** a new.* reference in a trigger program.
  88608. */
  88609. testcase( i==31 );
  88610. testcase( i==32 );
  88611. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  88612. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  88613. }
  88614. }
  88615. }
  88616. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  88617. ** verified. One could argue that this is wrong.
  88618. */
  88619. if( tmask&TRIGGER_BEFORE ){
  88620. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  88621. sqlite3TableAffinityStr(v, pTab);
  88622. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  88623. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  88624. /* The row-trigger may have deleted the row being updated. In this
  88625. ** case, jump to the next row. No updates or AFTER triggers are
  88626. ** required. This behavior - what happens when the row being updated
  88627. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  88628. ** documentation.
  88629. */
  88630. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  88631. /* If it did not delete it, the row-trigger may still have modified
  88632. ** some of the columns of the row being updated. Load the values for
  88633. ** all columns not modified by the update statement into their
  88634. ** registers in case this has happened.
  88635. */
  88636. for(i=0; i<pTab->nCol; i++){
  88637. if( aXRef[i]<0 && i!=pTab->iPKey ){
  88638. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  88639. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  88640. }
  88641. }
  88642. }
  88643. if( !isView ){
  88644. int j1; /* Address of jump instruction */
  88645. /* Do constraint checks. */
  88646. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  88647. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  88648. /* Do FK constraint checks. */
  88649. if( hasFK ){
  88650. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  88651. }
  88652. /* Delete the index entries associated with the current record. */
  88653. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  88654. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  88655. /* If changing the record number, delete the old record. */
  88656. if( hasFK || chngRowid ){
  88657. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  88658. }
  88659. sqlite3VdbeJumpHere(v, j1);
  88660. if( hasFK ){
  88661. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  88662. }
  88663. /* Insert the new index entries and the new record. */
  88664. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  88665. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  88666. ** handle rows (possibly in other tables) that refer via a foreign key
  88667. ** to the row just updated. */
  88668. if( hasFK ){
  88669. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  88670. }
  88671. }
  88672. /* Increment the row counter
  88673. */
  88674. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  88675. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  88676. }
  88677. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  88678. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  88679. /* Repeat the above with the next record to be updated, until
  88680. ** all record selected by the WHERE clause have been updated.
  88681. */
  88682. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  88683. sqlite3VdbeJumpHere(v, addr);
  88684. /* Close all tables */
  88685. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  88686. assert( aRegIdx );
  88687. if( openAll || aRegIdx[i]>0 ){
  88688. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  88689. }
  88690. }
  88691. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  88692. /* Update the sqlite_sequence table by storing the content of the
  88693. ** maximum rowid counter values recorded while inserting into
  88694. ** autoincrement tables.
  88695. */
  88696. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  88697. sqlite3AutoincrementEnd(pParse);
  88698. }
  88699. /*
  88700. ** Return the number of rows that were changed. If this routine is
  88701. ** generating code because of a call to sqlite3NestedParse(), do not
  88702. ** invoke the callback function.
  88703. */
  88704. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  88705. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  88706. sqlite3VdbeSetNumCols(v, 1);
  88707. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  88708. }
  88709. update_cleanup:
  88710. sqlite3AuthContextPop(&sContext);
  88711. sqlite3DbFree(db, aRegIdx);
  88712. sqlite3DbFree(db, aXRef);
  88713. sqlite3SrcListDelete(db, pTabList);
  88714. sqlite3ExprListDelete(db, pChanges);
  88715. sqlite3ExprDelete(db, pWhere);
  88716. return;
  88717. }
  88718. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  88719. ** thely may interfere with compilation of other functions in this file
  88720. ** (or in another file, if this file becomes part of the amalgamation). */
  88721. #ifdef isView
  88722. #undef isView
  88723. #endif
  88724. #ifdef pTrigger
  88725. #undef pTrigger
  88726. #endif
  88727. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88728. /*
  88729. ** Generate code for an UPDATE of a virtual table.
  88730. **
  88731. ** The strategy is that we create an ephemerial table that contains
  88732. ** for each row to be changed:
  88733. **
  88734. ** (A) The original rowid of that row.
  88735. ** (B) The revised rowid for the row. (note1)
  88736. ** (C) The content of every column in the row.
  88737. **
  88738. ** Then we loop over this ephemeral table and for each row in
  88739. ** the ephermeral table call VUpdate.
  88740. **
  88741. ** When finished, drop the ephemeral table.
  88742. **
  88743. ** (note1) Actually, if we know in advance that (A) is always the same
  88744. ** as (B) we only store (A), then duplicate (A) when pulling
  88745. ** it out of the ephemeral table before calling VUpdate.
  88746. */
  88747. static void updateVirtualTable(
  88748. Parse *pParse, /* The parsing context */
  88749. SrcList *pSrc, /* The virtual table to be modified */
  88750. Table *pTab, /* The virtual table */
  88751. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  88752. Expr *pRowid, /* Expression used to recompute the rowid */
  88753. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  88754. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  88755. int onError /* ON CONFLICT strategy */
  88756. ){
  88757. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  88758. ExprList *pEList = 0; /* The result set of the SELECT statement */
  88759. Select *pSelect = 0; /* The SELECT statement */
  88760. Expr *pExpr; /* Temporary expression */
  88761. int ephemTab; /* Table holding the result of the SELECT */
  88762. int i; /* Loop counter */
  88763. int addr; /* Address of top of loop */
  88764. int iReg; /* First register in set passed to OP_VUpdate */
  88765. sqlite3 *db = pParse->db; /* Database connection */
  88766. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  88767. SelectDest dest;
  88768. /* Construct the SELECT statement that will find the new values for
  88769. ** all updated rows.
  88770. */
  88771. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  88772. if( pRowid ){
  88773. pEList = sqlite3ExprListAppend(pParse, pEList,
  88774. sqlite3ExprDup(db, pRowid, 0));
  88775. }
  88776. assert( pTab->iPKey<0 );
  88777. for(i=0; i<pTab->nCol; i++){
  88778. if( aXRef[i]>=0 ){
  88779. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  88780. }else{
  88781. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  88782. }
  88783. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  88784. }
  88785. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  88786. /* Create the ephemeral table into which the update results will
  88787. ** be stored.
  88788. */
  88789. assert( v );
  88790. ephemTab = pParse->nTab++;
  88791. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  88792. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  88793. /* fill the ephemeral table
  88794. */
  88795. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  88796. sqlite3Select(pParse, pSelect, &dest);
  88797. /* Generate code to scan the ephemeral table and call VUpdate. */
  88798. iReg = ++pParse->nMem;
  88799. pParse->nMem += pTab->nCol+1;
  88800. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  88801. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  88802. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  88803. for(i=0; i<pTab->nCol; i++){
  88804. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  88805. }
  88806. sqlite3VtabMakeWritable(pParse, pTab);
  88807. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  88808. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  88809. sqlite3MayAbort(pParse);
  88810. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  88811. sqlite3VdbeJumpHere(v, addr);
  88812. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  88813. /* Cleanup */
  88814. sqlite3SelectDelete(db, pSelect);
  88815. }
  88816. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  88817. /************** End of update.c **********************************************/
  88818. /************** Begin file vacuum.c ******************************************/
  88819. /*
  88820. ** 2003 April 6
  88821. **
  88822. ** The author disclaims copyright to this source code. In place of
  88823. ** a legal notice, here is a blessing:
  88824. **
  88825. ** May you do good and not evil.
  88826. ** May you find forgiveness for yourself and forgive others.
  88827. ** May you share freely, never taking more than you give.
  88828. **
  88829. *************************************************************************
  88830. ** This file contains code used to implement the VACUUM command.
  88831. **
  88832. ** Most of the code in this file may be omitted by defining the
  88833. ** SQLITE_OMIT_VACUUM macro.
  88834. */
  88835. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  88836. /*
  88837. ** Finalize a prepared statement. If there was an error, store the
  88838. ** text of the error message in *pzErrMsg. Return the result code.
  88839. */
  88840. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  88841. int rc;
  88842. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  88843. if( rc ){
  88844. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  88845. }
  88846. return rc;
  88847. }
  88848. /*
  88849. ** Execute zSql on database db. Return an error code.
  88850. */
  88851. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  88852. sqlite3_stmt *pStmt;
  88853. VVA_ONLY( int rc; )
  88854. if( !zSql ){
  88855. return SQLITE_NOMEM;
  88856. }
  88857. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  88858. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  88859. return sqlite3_errcode(db);
  88860. }
  88861. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  88862. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  88863. return vacuumFinalize(db, pStmt, pzErrMsg);
  88864. }
  88865. /*
  88866. ** Execute zSql on database db. The statement returns exactly
  88867. ** one column. Execute this as SQL on the same database.
  88868. */
  88869. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  88870. sqlite3_stmt *pStmt;
  88871. int rc;
  88872. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  88873. if( rc!=SQLITE_OK ) return rc;
  88874. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  88875. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  88876. if( rc!=SQLITE_OK ){
  88877. vacuumFinalize(db, pStmt, pzErrMsg);
  88878. return rc;
  88879. }
  88880. }
  88881. return vacuumFinalize(db, pStmt, pzErrMsg);
  88882. }
  88883. /*
  88884. ** The VACUUM command is used to clean up the database,
  88885. ** collapse free space, etc. It is modelled after the VACUUM command
  88886. ** in PostgreSQL. The VACUUM command works as follows:
  88887. **
  88888. ** (1) Create a new transient database file
  88889. ** (2) Copy all content from the database being vacuumed into
  88890. ** the new transient database file
  88891. ** (3) Copy content from the transient database back into the
  88892. ** original database.
  88893. **
  88894. ** The transient database requires temporary disk space approximately
  88895. ** equal to the size of the original database. The copy operation of
  88896. ** step (3) requires additional temporary disk space approximately equal
  88897. ** to the size of the original database for the rollback journal.
  88898. ** Hence, temporary disk space that is approximately 2x the size of the
  88899. ** orginal database is required. Every page of the database is written
  88900. ** approximately 3 times: Once for step (2) and twice for step (3).
  88901. ** Two writes per page are required in step (3) because the original
  88902. ** database content must be written into the rollback journal prior to
  88903. ** overwriting the database with the vacuumed content.
  88904. **
  88905. ** Only 1x temporary space and only 1x writes would be required if
  88906. ** the copy of step (3) were replace by deleting the original database
  88907. ** and renaming the transient database as the original. But that will
  88908. ** not work if other processes are attached to the original database.
  88909. ** And a power loss in between deleting the original and renaming the
  88910. ** transient would cause the database file to appear to be deleted
  88911. ** following reboot.
  88912. */
  88913. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  88914. Vdbe *v = sqlite3GetVdbe(pParse);
  88915. if( v ){
  88916. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  88917. sqlite3VdbeUsesBtree(v, 0);
  88918. }
  88919. return;
  88920. }
  88921. /*
  88922. ** This routine implements the OP_Vacuum opcode of the VDBE.
  88923. */
  88924. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  88925. int rc = SQLITE_OK; /* Return code from service routines */
  88926. Btree *pMain; /* The database being vacuumed */
  88927. Btree *pTemp; /* The temporary database we vacuum into */
  88928. char *zSql = 0; /* SQL statements */
  88929. int saved_flags; /* Saved value of the db->flags */
  88930. int saved_nChange; /* Saved value of db->nChange */
  88931. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  88932. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  88933. Db *pDb = 0; /* Database to detach at end of vacuum */
  88934. int isMemDb; /* True if vacuuming a :memory: database */
  88935. int nRes; /* Bytes of reserved space at the end of each page */
  88936. int nDb; /* Number of attached databases */
  88937. if( !db->autoCommit ){
  88938. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  88939. return SQLITE_ERROR;
  88940. }
  88941. if( db->nVdbeActive>1 ){
  88942. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  88943. return SQLITE_ERROR;
  88944. }
  88945. /* Save the current value of the database flags so that it can be
  88946. ** restored before returning. Then set the writable-schema flag, and
  88947. ** disable CHECK and foreign key constraints. */
  88948. saved_flags = db->flags;
  88949. saved_nChange = db->nChange;
  88950. saved_nTotalChange = db->nTotalChange;
  88951. saved_xTrace = db->xTrace;
  88952. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  88953. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  88954. db->xTrace = 0;
  88955. pMain = db->aDb[0].pBt;
  88956. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  88957. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  88958. ** can be set to 'off' for this file, as it is not recovered if a crash
  88959. ** occurs anyway. The integrity of the database is maintained by a
  88960. ** (possibly synchronous) transaction opened on the main database before
  88961. ** sqlite3BtreeCopyFile() is called.
  88962. **
  88963. ** An optimisation would be to use a non-journaled pager.
  88964. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  88965. ** that actually made the VACUUM run slower. Very little journalling
  88966. ** actually occurs when doing a vacuum since the vacuum_db is initially
  88967. ** empty. Only the journal header is written. Apparently it takes more
  88968. ** time to parse and run the PRAGMA to turn journalling off than it does
  88969. ** to write the journal header file.
  88970. */
  88971. nDb = db->nDb;
  88972. if( sqlite3TempInMemory(db) ){
  88973. zSql = "ATTACH ':memory:' AS vacuum_db;";
  88974. }else{
  88975. zSql = "ATTACH '' AS vacuum_db;";
  88976. }
  88977. rc = execSql(db, pzErrMsg, zSql);
  88978. if( db->nDb>nDb ){
  88979. pDb = &db->aDb[db->nDb-1];
  88980. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  88981. }
  88982. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  88983. pTemp = db->aDb[db->nDb-1].pBt;
  88984. /* The call to execSql() to attach the temp database has left the file
  88985. ** locked (as there was more than one active statement when the transaction
  88986. ** to read the schema was concluded. Unlock it here so that this doesn't
  88987. ** cause problems for the call to BtreeSetPageSize() below. */
  88988. sqlite3BtreeCommit(pTemp);
  88989. nRes = sqlite3BtreeGetReserve(pMain);
  88990. /* A VACUUM cannot change the pagesize of an encrypted database. */
  88991. #ifdef SQLITE_HAS_CODEC
  88992. if( db->nextPagesize ){
  88993. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  88994. int nKey;
  88995. char *zKey;
  88996. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  88997. if( nKey ) db->nextPagesize = 0;
  88998. }
  88999. #endif
  89000. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  89001. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89002. /* Begin a transaction and take an exclusive lock on the main database
  89003. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  89004. ** to ensure that we do not try to change the page-size on a WAL database.
  89005. */
  89006. rc = execSql(db, pzErrMsg, "BEGIN;");
  89007. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89008. rc = sqlite3BtreeBeginTrans(pMain, 2);
  89009. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89010. /* Do not attempt to change the page size for a WAL database */
  89011. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  89012. ==PAGER_JOURNALMODE_WAL ){
  89013. db->nextPagesize = 0;
  89014. }
  89015. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  89016. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  89017. || NEVER(db->mallocFailed)
  89018. ){
  89019. rc = SQLITE_NOMEM;
  89020. goto end_of_vacuum;
  89021. }
  89022. #ifndef SQLITE_OMIT_AUTOVACUUM
  89023. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  89024. sqlite3BtreeGetAutoVacuum(pMain));
  89025. #endif
  89026. /* Query the schema of the main database. Create a mirror schema
  89027. ** in the temporary database.
  89028. */
  89029. rc = execExecSql(db, pzErrMsg,
  89030. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  89031. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  89032. " AND rootpage>0"
  89033. );
  89034. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89035. rc = execExecSql(db, pzErrMsg,
  89036. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  89037. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  89038. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89039. rc = execExecSql(db, pzErrMsg,
  89040. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  89041. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  89042. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89043. /* Loop through the tables in the main database. For each, do
  89044. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  89045. ** the contents to the temporary database.
  89046. */
  89047. rc = execExecSql(db, pzErrMsg,
  89048. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  89049. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  89050. "FROM main.sqlite_master "
  89051. "WHERE type = 'table' AND name!='sqlite_sequence' "
  89052. " AND rootpage>0"
  89053. );
  89054. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89055. /* Copy over the sequence table
  89056. */
  89057. rc = execExecSql(db, pzErrMsg,
  89058. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  89059. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  89060. );
  89061. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89062. rc = execExecSql(db, pzErrMsg,
  89063. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  89064. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  89065. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  89066. );
  89067. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89068. /* Copy the triggers, views, and virtual tables from the main database
  89069. ** over to the temporary database. None of these objects has any
  89070. ** associated storage, so all we have to do is copy their entries
  89071. ** from the SQLITE_MASTER table.
  89072. */
  89073. rc = execSql(db, pzErrMsg,
  89074. "INSERT INTO vacuum_db.sqlite_master "
  89075. " SELECT type, name, tbl_name, rootpage, sql"
  89076. " FROM main.sqlite_master"
  89077. " WHERE type='view' OR type='trigger'"
  89078. " OR (type='table' AND rootpage=0)"
  89079. );
  89080. if( rc ) goto end_of_vacuum;
  89081. /* At this point, there is a write transaction open on both the
  89082. ** vacuum database and the main database. Assuming no error occurs,
  89083. ** both transactions are closed by this block - the main database
  89084. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  89085. ** call to sqlite3BtreeCommit().
  89086. */
  89087. {
  89088. u32 meta;
  89089. int i;
  89090. /* This array determines which meta meta values are preserved in the
  89091. ** vacuum. Even entries are the meta value number and odd entries
  89092. ** are an increment to apply to the meta value after the vacuum.
  89093. ** The increment is used to increase the schema cookie so that other
  89094. ** connections to the same database will know to reread the schema.
  89095. */
  89096. static const unsigned char aCopy[] = {
  89097. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  89098. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  89099. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  89100. BTREE_USER_VERSION, 0, /* Preserve the user version */
  89101. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  89102. };
  89103. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  89104. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  89105. /* Copy Btree meta values */
  89106. for(i=0; i<ArraySize(aCopy); i+=2){
  89107. /* GetMeta() and UpdateMeta() cannot fail in this context because
  89108. ** we already have page 1 loaded into cache and marked dirty. */
  89109. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  89110. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  89111. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  89112. }
  89113. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  89114. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89115. rc = sqlite3BtreeCommit(pTemp);
  89116. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89117. #ifndef SQLITE_OMIT_AUTOVACUUM
  89118. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  89119. #endif
  89120. }
  89121. assert( rc==SQLITE_OK );
  89122. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  89123. end_of_vacuum:
  89124. /* Restore the original value of db->flags */
  89125. db->flags = saved_flags;
  89126. db->nChange = saved_nChange;
  89127. db->nTotalChange = saved_nTotalChange;
  89128. db->xTrace = saved_xTrace;
  89129. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  89130. /* Currently there is an SQL level transaction open on the vacuum
  89131. ** database. No locks are held on any other files (since the main file
  89132. ** was committed at the btree level). So it safe to end the transaction
  89133. ** by manually setting the autoCommit flag to true and detaching the
  89134. ** vacuum database. The vacuum_db journal file is deleted when the pager
  89135. ** is closed by the DETACH.
  89136. */
  89137. db->autoCommit = 1;
  89138. if( pDb ){
  89139. sqlite3BtreeClose(pDb->pBt);
  89140. pDb->pBt = 0;
  89141. pDb->pSchema = 0;
  89142. }
  89143. /* This both clears the schemas and reduces the size of the db->aDb[]
  89144. ** array. */
  89145. sqlite3ResetAllSchemasOfConnection(db);
  89146. return rc;
  89147. }
  89148. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  89149. /************** End of vacuum.c **********************************************/
  89150. /************** Begin file vtab.c ********************************************/
  89151. /*
  89152. ** 2006 June 10
  89153. **
  89154. ** The author disclaims copyright to this source code. In place of
  89155. ** a legal notice, here is a blessing:
  89156. **
  89157. ** May you do good and not evil.
  89158. ** May you find forgiveness for yourself and forgive others.
  89159. ** May you share freely, never taking more than you give.
  89160. **
  89161. *************************************************************************
  89162. ** This file contains code used to help implement virtual tables.
  89163. */
  89164. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89165. /*
  89166. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  89167. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  89168. ** this struct allocated on the stack. It is used by the implementation of
  89169. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  89170. ** are invoked only from within xCreate and xConnect methods.
  89171. */
  89172. struct VtabCtx {
  89173. VTable *pVTable; /* The virtual table being constructed */
  89174. Table *pTab; /* The Table object to which the virtual table belongs */
  89175. };
  89176. /*
  89177. ** The actual function that does the work of creating a new module.
  89178. ** This function implements the sqlite3_create_module() and
  89179. ** sqlite3_create_module_v2() interfaces.
  89180. */
  89181. static int createModule(
  89182. sqlite3 *db, /* Database in which module is registered */
  89183. const char *zName, /* Name assigned to this module */
  89184. const sqlite3_module *pModule, /* The definition of the module */
  89185. void *pAux, /* Context pointer for xCreate/xConnect */
  89186. void (*xDestroy)(void *) /* Module destructor function */
  89187. ){
  89188. int rc = SQLITE_OK;
  89189. int nName;
  89190. sqlite3_mutex_enter(db->mutex);
  89191. nName = sqlite3Strlen30(zName);
  89192. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  89193. rc = SQLITE_MISUSE_BKPT;
  89194. }else{
  89195. Module *pMod;
  89196. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  89197. if( pMod ){
  89198. Module *pDel;
  89199. char *zCopy = (char *)(&pMod[1]);
  89200. memcpy(zCopy, zName, nName+1);
  89201. pMod->zName = zCopy;
  89202. pMod->pModule = pModule;
  89203. pMod->pAux = pAux;
  89204. pMod->xDestroy = xDestroy;
  89205. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  89206. assert( pDel==0 || pDel==pMod );
  89207. if( pDel ){
  89208. db->mallocFailed = 1;
  89209. sqlite3DbFree(db, pDel);
  89210. }
  89211. }
  89212. }
  89213. rc = sqlite3ApiExit(db, rc);
  89214. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  89215. sqlite3_mutex_leave(db->mutex);
  89216. return rc;
  89217. }
  89218. /*
  89219. ** External API function used to create a new virtual-table module.
  89220. */
  89221. SQLITE_API int sqlite3_create_module(
  89222. sqlite3 *db, /* Database in which module is registered */
  89223. const char *zName, /* Name assigned to this module */
  89224. const sqlite3_module *pModule, /* The definition of the module */
  89225. void *pAux /* Context pointer for xCreate/xConnect */
  89226. ){
  89227. return createModule(db, zName, pModule, pAux, 0);
  89228. }
  89229. /*
  89230. ** External API function used to create a new virtual-table module.
  89231. */
  89232. SQLITE_API int sqlite3_create_module_v2(
  89233. sqlite3 *db, /* Database in which module is registered */
  89234. const char *zName, /* Name assigned to this module */
  89235. const sqlite3_module *pModule, /* The definition of the module */
  89236. void *pAux, /* Context pointer for xCreate/xConnect */
  89237. void (*xDestroy)(void *) /* Module destructor function */
  89238. ){
  89239. return createModule(db, zName, pModule, pAux, xDestroy);
  89240. }
  89241. /*
  89242. ** Lock the virtual table so that it cannot be disconnected.
  89243. ** Locks nest. Every lock should have a corresponding unlock.
  89244. ** If an unlock is omitted, resources leaks will occur.
  89245. **
  89246. ** If a disconnect is attempted while a virtual table is locked,
  89247. ** the disconnect is deferred until all locks have been removed.
  89248. */
  89249. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  89250. pVTab->nRef++;
  89251. }
  89252. /*
  89253. ** pTab is a pointer to a Table structure representing a virtual-table.
  89254. ** Return a pointer to the VTable object used by connection db to access
  89255. ** this virtual-table, if one has been created, or NULL otherwise.
  89256. */
  89257. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  89258. VTable *pVtab;
  89259. assert( IsVirtual(pTab) );
  89260. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  89261. return pVtab;
  89262. }
  89263. /*
  89264. ** Decrement the ref-count on a virtual table object. When the ref-count
  89265. ** reaches zero, call the xDisconnect() method to delete the object.
  89266. */
  89267. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  89268. sqlite3 *db = pVTab->db;
  89269. assert( db );
  89270. assert( pVTab->nRef>0 );
  89271. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  89272. pVTab->nRef--;
  89273. if( pVTab->nRef==0 ){
  89274. sqlite3_vtab *p = pVTab->pVtab;
  89275. if( p ){
  89276. p->pModule->xDisconnect(p);
  89277. }
  89278. sqlite3DbFree(db, pVTab);
  89279. }
  89280. }
  89281. /*
  89282. ** Table p is a virtual table. This function moves all elements in the
  89283. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  89284. ** database connections to be disconnected at the next opportunity.
  89285. ** Except, if argument db is not NULL, then the entry associated with
  89286. ** connection db is left in the p->pVTable list.
  89287. */
  89288. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  89289. VTable *pRet = 0;
  89290. VTable *pVTable = p->pVTable;
  89291. p->pVTable = 0;
  89292. /* Assert that the mutex (if any) associated with the BtShared database
  89293. ** that contains table p is held by the caller. See header comments
  89294. ** above function sqlite3VtabUnlockList() for an explanation of why
  89295. ** this makes it safe to access the sqlite3.pDisconnect list of any
  89296. ** database connection that may have an entry in the p->pVTable list.
  89297. */
  89298. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  89299. while( pVTable ){
  89300. sqlite3 *db2 = pVTable->db;
  89301. VTable *pNext = pVTable->pNext;
  89302. assert( db2 );
  89303. if( db2==db ){
  89304. pRet = pVTable;
  89305. p->pVTable = pRet;
  89306. pRet->pNext = 0;
  89307. }else{
  89308. pVTable->pNext = db2->pDisconnect;
  89309. db2->pDisconnect = pVTable;
  89310. }
  89311. pVTable = pNext;
  89312. }
  89313. assert( !db || pRet );
  89314. return pRet;
  89315. }
  89316. /*
  89317. ** Table *p is a virtual table. This function removes the VTable object
  89318. ** for table *p associated with database connection db from the linked
  89319. ** list in p->pVTab. It also decrements the VTable ref count. This is
  89320. ** used when closing database connection db to free all of its VTable
  89321. ** objects without disturbing the rest of the Schema object (which may
  89322. ** be being used by other shared-cache connections).
  89323. */
  89324. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  89325. VTable **ppVTab;
  89326. assert( IsVirtual(p) );
  89327. assert( sqlite3BtreeHoldsAllMutexes(db) );
  89328. assert( sqlite3_mutex_held(db->mutex) );
  89329. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  89330. if( (*ppVTab)->db==db ){
  89331. VTable *pVTab = *ppVTab;
  89332. *ppVTab = pVTab->pNext;
  89333. sqlite3VtabUnlock(pVTab);
  89334. break;
  89335. }
  89336. }
  89337. }
  89338. /*
  89339. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  89340. **
  89341. ** This function may only be called when the mutexes associated with all
  89342. ** shared b-tree databases opened using connection db are held by the
  89343. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  89344. ** sqlite3.pDisconnect list is accessed only as follows:
  89345. **
  89346. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  89347. ** associated with the database handle itself must be held.
  89348. **
  89349. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  89350. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  89351. ** associated with the database the virtual table is stored in is held
  89352. ** or, if the virtual table is stored in a non-sharable database, then
  89353. ** the database handle mutex is held.
  89354. **
  89355. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  89356. ** by multiple threads. It is thread-safe.
  89357. */
  89358. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  89359. VTable *p = db->pDisconnect;
  89360. db->pDisconnect = 0;
  89361. assert( sqlite3BtreeHoldsAllMutexes(db) );
  89362. assert( sqlite3_mutex_held(db->mutex) );
  89363. if( p ){
  89364. sqlite3ExpirePreparedStatements(db);
  89365. do {
  89366. VTable *pNext = p->pNext;
  89367. sqlite3VtabUnlock(p);
  89368. p = pNext;
  89369. }while( p );
  89370. }
  89371. }
  89372. /*
  89373. ** Clear any and all virtual-table information from the Table record.
  89374. ** This routine is called, for example, just before deleting the Table
  89375. ** record.
  89376. **
  89377. ** Since it is a virtual-table, the Table structure contains a pointer
  89378. ** to the head of a linked list of VTable structures. Each VTable
  89379. ** structure is associated with a single sqlite3* user of the schema.
  89380. ** The reference count of the VTable structure associated with database
  89381. ** connection db is decremented immediately (which may lead to the
  89382. ** structure being xDisconnected and free). Any other VTable structures
  89383. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  89384. ** database connection.
  89385. */
  89386. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  89387. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  89388. if( p->azModuleArg ){
  89389. int i;
  89390. for(i=0; i<p->nModuleArg; i++){
  89391. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  89392. }
  89393. sqlite3DbFree(db, p->azModuleArg);
  89394. }
  89395. }
  89396. /*
  89397. ** Add a new module argument to pTable->azModuleArg[].
  89398. ** The string is not copied - the pointer is stored. The
  89399. ** string will be freed automatically when the table is
  89400. ** deleted.
  89401. */
  89402. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  89403. int i = pTable->nModuleArg++;
  89404. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  89405. char **azModuleArg;
  89406. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  89407. if( azModuleArg==0 ){
  89408. int j;
  89409. for(j=0; j<i; j++){
  89410. sqlite3DbFree(db, pTable->azModuleArg[j]);
  89411. }
  89412. sqlite3DbFree(db, zArg);
  89413. sqlite3DbFree(db, pTable->azModuleArg);
  89414. pTable->nModuleArg = 0;
  89415. }else{
  89416. azModuleArg[i] = zArg;
  89417. azModuleArg[i+1] = 0;
  89418. }
  89419. pTable->azModuleArg = azModuleArg;
  89420. }
  89421. /*
  89422. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  89423. ** statement. The module name has been parsed, but the optional list
  89424. ** of parameters that follow the module name are still pending.
  89425. */
  89426. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  89427. Parse *pParse, /* Parsing context */
  89428. Token *pName1, /* Name of new table, or database name */
  89429. Token *pName2, /* Name of new table or NULL */
  89430. Token *pModuleName, /* Name of the module for the virtual table */
  89431. int ifNotExists /* No error if the table already exists */
  89432. ){
  89433. int iDb; /* The database the table is being created in */
  89434. Table *pTable; /* The new virtual table */
  89435. sqlite3 *db; /* Database connection */
  89436. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  89437. pTable = pParse->pNewTable;
  89438. if( pTable==0 ) return;
  89439. assert( 0==pTable->pIndex );
  89440. db = pParse->db;
  89441. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  89442. assert( iDb>=0 );
  89443. pTable->tabFlags |= TF_Virtual;
  89444. pTable->nModuleArg = 0;
  89445. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  89446. addModuleArgument(db, pTable, 0);
  89447. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  89448. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  89449. #ifndef SQLITE_OMIT_AUTHORIZATION
  89450. /* Creating a virtual table invokes the authorization callback twice.
  89451. ** The first invocation, to obtain permission to INSERT a row into the
  89452. ** sqlite_master table, has already been made by sqlite3StartTable().
  89453. ** The second call, to obtain permission to create the table, is made now.
  89454. */
  89455. if( pTable->azModuleArg ){
  89456. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  89457. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  89458. }
  89459. #endif
  89460. }
  89461. /*
  89462. ** This routine takes the module argument that has been accumulating
  89463. ** in pParse->zArg[] and appends it to the list of arguments on the
  89464. ** virtual table currently under construction in pParse->pTable.
  89465. */
  89466. static void addArgumentToVtab(Parse *pParse){
  89467. if( pParse->sArg.z && pParse->pNewTable ){
  89468. const char *z = (const char*)pParse->sArg.z;
  89469. int n = pParse->sArg.n;
  89470. sqlite3 *db = pParse->db;
  89471. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  89472. }
  89473. }
  89474. /*
  89475. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  89476. ** has been completely parsed.
  89477. */
  89478. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  89479. Table *pTab = pParse->pNewTable; /* The table being constructed */
  89480. sqlite3 *db = pParse->db; /* The database connection */
  89481. if( pTab==0 ) return;
  89482. addArgumentToVtab(pParse);
  89483. pParse->sArg.z = 0;
  89484. if( pTab->nModuleArg<1 ) return;
  89485. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  89486. ** first time (in other words if the virtual table is actually being
  89487. ** created now instead of just being read out of sqlite_master) then
  89488. ** do additional initialization work and store the statement text
  89489. ** in the sqlite_master table.
  89490. */
  89491. if( !db->init.busy ){
  89492. char *zStmt;
  89493. char *zWhere;
  89494. int iDb;
  89495. Vdbe *v;
  89496. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  89497. if( pEnd ){
  89498. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  89499. }
  89500. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  89501. /* A slot for the record has already been allocated in the
  89502. ** SQLITE_MASTER table. We just need to update that slot with all
  89503. ** the information we've collected.
  89504. **
  89505. ** The VM register number pParse->regRowid holds the rowid of an
  89506. ** entry in the sqlite_master table tht was created for this vtab
  89507. ** by sqlite3StartTable().
  89508. */
  89509. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89510. sqlite3NestedParse(pParse,
  89511. "UPDATE %Q.%s "
  89512. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  89513. "WHERE rowid=#%d",
  89514. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  89515. pTab->zName,
  89516. pTab->zName,
  89517. zStmt,
  89518. pParse->regRowid
  89519. );
  89520. sqlite3DbFree(db, zStmt);
  89521. v = sqlite3GetVdbe(pParse);
  89522. sqlite3ChangeCookie(pParse, iDb);
  89523. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  89524. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  89525. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  89526. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  89527. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  89528. }
  89529. /* If we are rereading the sqlite_master table create the in-memory
  89530. ** record of the table. The xConnect() method is not called until
  89531. ** the first time the virtual table is used in an SQL statement. This
  89532. ** allows a schema that contains virtual tables to be loaded before
  89533. ** the required virtual table implementations are registered. */
  89534. else {
  89535. Table *pOld;
  89536. Schema *pSchema = pTab->pSchema;
  89537. const char *zName = pTab->zName;
  89538. int nName = sqlite3Strlen30(zName);
  89539. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  89540. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  89541. if( pOld ){
  89542. db->mallocFailed = 1;
  89543. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  89544. return;
  89545. }
  89546. pParse->pNewTable = 0;
  89547. }
  89548. }
  89549. /*
  89550. ** The parser calls this routine when it sees the first token
  89551. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  89552. */
  89553. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  89554. addArgumentToVtab(pParse);
  89555. pParse->sArg.z = 0;
  89556. pParse->sArg.n = 0;
  89557. }
  89558. /*
  89559. ** The parser calls this routine for each token after the first token
  89560. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  89561. */
  89562. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  89563. Token *pArg = &pParse->sArg;
  89564. if( pArg->z==0 ){
  89565. pArg->z = p->z;
  89566. pArg->n = p->n;
  89567. }else{
  89568. assert(pArg->z < p->z);
  89569. pArg->n = (int)(&p->z[p->n] - pArg->z);
  89570. }
  89571. }
  89572. /*
  89573. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  89574. ** pointer to the function to invoke is passed as the fourth parameter
  89575. ** to this procedure.
  89576. */
  89577. static int vtabCallConstructor(
  89578. sqlite3 *db,
  89579. Table *pTab,
  89580. Module *pMod,
  89581. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  89582. char **pzErr
  89583. ){
  89584. VtabCtx sCtx, *pPriorCtx;
  89585. VTable *pVTable;
  89586. int rc;
  89587. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  89588. int nArg = pTab->nModuleArg;
  89589. char *zErr = 0;
  89590. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  89591. int iDb;
  89592. if( !zModuleName ){
  89593. return SQLITE_NOMEM;
  89594. }
  89595. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  89596. if( !pVTable ){
  89597. sqlite3DbFree(db, zModuleName);
  89598. return SQLITE_NOMEM;
  89599. }
  89600. pVTable->db = db;
  89601. pVTable->pMod = pMod;
  89602. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89603. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  89604. /* Invoke the virtual table constructor */
  89605. assert( &db->pVtabCtx );
  89606. assert( xConstruct );
  89607. sCtx.pTab = pTab;
  89608. sCtx.pVTable = pVTable;
  89609. pPriorCtx = db->pVtabCtx;
  89610. db->pVtabCtx = &sCtx;
  89611. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  89612. db->pVtabCtx = pPriorCtx;
  89613. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  89614. if( SQLITE_OK!=rc ){
  89615. if( zErr==0 ){
  89616. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  89617. }else {
  89618. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  89619. sqlite3_free(zErr);
  89620. }
  89621. sqlite3DbFree(db, pVTable);
  89622. }else if( ALWAYS(pVTable->pVtab) ){
  89623. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  89624. ** the sqlite3_vtab object if successful. */
  89625. pVTable->pVtab->pModule = pMod->pModule;
  89626. pVTable->nRef = 1;
  89627. if( sCtx.pTab ){
  89628. const char *zFormat = "vtable constructor did not declare schema: %s";
  89629. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  89630. sqlite3VtabUnlock(pVTable);
  89631. rc = SQLITE_ERROR;
  89632. }else{
  89633. int iCol;
  89634. /* If everything went according to plan, link the new VTable structure
  89635. ** into the linked list headed by pTab->pVTable. Then loop through the
  89636. ** columns of the table to see if any of them contain the token "hidden".
  89637. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  89638. ** the type string. */
  89639. pVTable->pNext = pTab->pVTable;
  89640. pTab->pVTable = pVTable;
  89641. for(iCol=0; iCol<pTab->nCol; iCol++){
  89642. char *zType = pTab->aCol[iCol].zType;
  89643. int nType;
  89644. int i = 0;
  89645. if( !zType ) continue;
  89646. nType = sqlite3Strlen30(zType);
  89647. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  89648. for(i=0; i<nType; i++){
  89649. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  89650. && (zType[i+7]=='\0' || zType[i+7]==' ')
  89651. ){
  89652. i++;
  89653. break;
  89654. }
  89655. }
  89656. }
  89657. if( i<nType ){
  89658. int j;
  89659. int nDel = 6 + (zType[i+6] ? 1 : 0);
  89660. for(j=i; (j+nDel)<=nType; j++){
  89661. zType[j] = zType[j+nDel];
  89662. }
  89663. if( zType[i]=='\0' && i>0 ){
  89664. assert(zType[i-1]==' ');
  89665. zType[i-1] = '\0';
  89666. }
  89667. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  89668. }
  89669. }
  89670. }
  89671. }
  89672. sqlite3DbFree(db, zModuleName);
  89673. return rc;
  89674. }
  89675. /*
  89676. ** This function is invoked by the parser to call the xConnect() method
  89677. ** of the virtual table pTab. If an error occurs, an error code is returned
  89678. ** and an error left in pParse.
  89679. **
  89680. ** This call is a no-op if table pTab is not a virtual table.
  89681. */
  89682. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  89683. sqlite3 *db = pParse->db;
  89684. const char *zMod;
  89685. Module *pMod;
  89686. int rc;
  89687. assert( pTab );
  89688. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  89689. return SQLITE_OK;
  89690. }
  89691. /* Locate the required virtual table module */
  89692. zMod = pTab->azModuleArg[0];
  89693. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  89694. if( !pMod ){
  89695. const char *zModule = pTab->azModuleArg[0];
  89696. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  89697. rc = SQLITE_ERROR;
  89698. }else{
  89699. char *zErr = 0;
  89700. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  89701. if( rc!=SQLITE_OK ){
  89702. sqlite3ErrorMsg(pParse, "%s", zErr);
  89703. }
  89704. sqlite3DbFree(db, zErr);
  89705. }
  89706. return rc;
  89707. }
  89708. /*
  89709. ** Grow the db->aVTrans[] array so that there is room for at least one
  89710. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  89711. */
  89712. static int growVTrans(sqlite3 *db){
  89713. const int ARRAY_INCR = 5;
  89714. /* Grow the sqlite3.aVTrans array if required */
  89715. if( (db->nVTrans%ARRAY_INCR)==0 ){
  89716. VTable **aVTrans;
  89717. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  89718. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  89719. if( !aVTrans ){
  89720. return SQLITE_NOMEM;
  89721. }
  89722. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  89723. db->aVTrans = aVTrans;
  89724. }
  89725. return SQLITE_OK;
  89726. }
  89727. /*
  89728. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  89729. ** have already been reserved using growVTrans().
  89730. */
  89731. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  89732. /* Add pVtab to the end of sqlite3.aVTrans */
  89733. db->aVTrans[db->nVTrans++] = pVTab;
  89734. sqlite3VtabLock(pVTab);
  89735. }
  89736. /*
  89737. ** This function is invoked by the vdbe to call the xCreate method
  89738. ** of the virtual table named zTab in database iDb.
  89739. **
  89740. ** If an error occurs, *pzErr is set to point an an English language
  89741. ** description of the error and an SQLITE_XXX error code is returned.
  89742. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  89743. */
  89744. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  89745. int rc = SQLITE_OK;
  89746. Table *pTab;
  89747. Module *pMod;
  89748. const char *zMod;
  89749. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  89750. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  89751. /* Locate the required virtual table module */
  89752. zMod = pTab->azModuleArg[0];
  89753. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  89754. /* If the module has been registered and includes a Create method,
  89755. ** invoke it now. If the module has not been registered, return an
  89756. ** error. Otherwise, do nothing.
  89757. */
  89758. if( !pMod ){
  89759. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  89760. rc = SQLITE_ERROR;
  89761. }else{
  89762. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  89763. }
  89764. /* Justification of ALWAYS(): The xConstructor method is required to
  89765. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  89766. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  89767. rc = growVTrans(db);
  89768. if( rc==SQLITE_OK ){
  89769. addToVTrans(db, sqlite3GetVTable(db, pTab));
  89770. }
  89771. }
  89772. return rc;
  89773. }
  89774. /*
  89775. ** This function is used to set the schema of a virtual table. It is only
  89776. ** valid to call this function from within the xCreate() or xConnect() of a
  89777. ** virtual table module.
  89778. */
  89779. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  89780. Parse *pParse;
  89781. int rc = SQLITE_OK;
  89782. Table *pTab;
  89783. char *zErr = 0;
  89784. sqlite3_mutex_enter(db->mutex);
  89785. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  89786. sqlite3Error(db, SQLITE_MISUSE, 0);
  89787. sqlite3_mutex_leave(db->mutex);
  89788. return SQLITE_MISUSE_BKPT;
  89789. }
  89790. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  89791. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  89792. if( pParse==0 ){
  89793. rc = SQLITE_NOMEM;
  89794. }else{
  89795. pParse->declareVtab = 1;
  89796. pParse->db = db;
  89797. pParse->nQueryLoop = 1;
  89798. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  89799. && pParse->pNewTable
  89800. && !db->mallocFailed
  89801. && !pParse->pNewTable->pSelect
  89802. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  89803. ){
  89804. if( !pTab->aCol ){
  89805. pTab->aCol = pParse->pNewTable->aCol;
  89806. pTab->nCol = pParse->pNewTable->nCol;
  89807. pParse->pNewTable->nCol = 0;
  89808. pParse->pNewTable->aCol = 0;
  89809. }
  89810. db->pVtabCtx->pTab = 0;
  89811. }else{
  89812. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  89813. sqlite3DbFree(db, zErr);
  89814. rc = SQLITE_ERROR;
  89815. }
  89816. pParse->declareVtab = 0;
  89817. if( pParse->pVdbe ){
  89818. sqlite3VdbeFinalize(pParse->pVdbe);
  89819. }
  89820. sqlite3DeleteTable(db, pParse->pNewTable);
  89821. sqlite3StackFree(db, pParse);
  89822. }
  89823. assert( (rc&0xff)==rc );
  89824. rc = sqlite3ApiExit(db, rc);
  89825. sqlite3_mutex_leave(db->mutex);
  89826. return rc;
  89827. }
  89828. /*
  89829. ** This function is invoked by the vdbe to call the xDestroy method
  89830. ** of the virtual table named zTab in database iDb. This occurs
  89831. ** when a DROP TABLE is mentioned.
  89832. **
  89833. ** This call is a no-op if zTab is not a virtual table.
  89834. */
  89835. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  89836. int rc = SQLITE_OK;
  89837. Table *pTab;
  89838. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  89839. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  89840. VTable *p = vtabDisconnectAll(db, pTab);
  89841. assert( rc==SQLITE_OK );
  89842. rc = p->pMod->pModule->xDestroy(p->pVtab);
  89843. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  89844. if( rc==SQLITE_OK ){
  89845. assert( pTab->pVTable==p && p->pNext==0 );
  89846. p->pVtab = 0;
  89847. pTab->pVTable = 0;
  89848. sqlite3VtabUnlock(p);
  89849. }
  89850. }
  89851. return rc;
  89852. }
  89853. /*
  89854. ** This function invokes either the xRollback or xCommit method
  89855. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  89856. ** called is identified by the second argument, "offset", which is
  89857. ** the offset of the method to call in the sqlite3_module structure.
  89858. **
  89859. ** The array is cleared after invoking the callbacks.
  89860. */
  89861. static void callFinaliser(sqlite3 *db, int offset){
  89862. int i;
  89863. if( db->aVTrans ){
  89864. for(i=0; i<db->nVTrans; i++){
  89865. VTable *pVTab = db->aVTrans[i];
  89866. sqlite3_vtab *p = pVTab->pVtab;
  89867. if( p ){
  89868. int (*x)(sqlite3_vtab *);
  89869. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  89870. if( x ) x(p);
  89871. }
  89872. pVTab->iSavepoint = 0;
  89873. sqlite3VtabUnlock(pVTab);
  89874. }
  89875. sqlite3DbFree(db, db->aVTrans);
  89876. db->nVTrans = 0;
  89877. db->aVTrans = 0;
  89878. }
  89879. }
  89880. /*
  89881. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  89882. ** array. Return the error code for the first error that occurs, or
  89883. ** SQLITE_OK if all xSync operations are successful.
  89884. **
  89885. ** If an error message is available, leave it in p->zErrMsg.
  89886. */
  89887. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  89888. int i;
  89889. int rc = SQLITE_OK;
  89890. VTable **aVTrans = db->aVTrans;
  89891. db->aVTrans = 0;
  89892. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  89893. int (*x)(sqlite3_vtab *);
  89894. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  89895. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  89896. rc = x(pVtab);
  89897. sqlite3VtabImportErrmsg(p, pVtab);
  89898. }
  89899. }
  89900. db->aVTrans = aVTrans;
  89901. return rc;
  89902. }
  89903. /*
  89904. ** Invoke the xRollback method of all virtual tables in the
  89905. ** sqlite3.aVTrans array. Then clear the array itself.
  89906. */
  89907. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  89908. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  89909. return SQLITE_OK;
  89910. }
  89911. /*
  89912. ** Invoke the xCommit method of all virtual tables in the
  89913. ** sqlite3.aVTrans array. Then clear the array itself.
  89914. */
  89915. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  89916. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  89917. return SQLITE_OK;
  89918. }
  89919. /*
  89920. ** If the virtual table pVtab supports the transaction interface
  89921. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  89922. ** not currently open, invoke the xBegin method now.
  89923. **
  89924. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  89925. ** in the sqlite3.aVTrans array.
  89926. */
  89927. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  89928. int rc = SQLITE_OK;
  89929. const sqlite3_module *pModule;
  89930. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  89931. ** than zero, then this function is being called from within a
  89932. ** virtual module xSync() callback. It is illegal to write to
  89933. ** virtual module tables in this case, so return SQLITE_LOCKED.
  89934. */
  89935. if( sqlite3VtabInSync(db) ){
  89936. return SQLITE_LOCKED;
  89937. }
  89938. if( !pVTab ){
  89939. return SQLITE_OK;
  89940. }
  89941. pModule = pVTab->pVtab->pModule;
  89942. if( pModule->xBegin ){
  89943. int i;
  89944. /* If pVtab is already in the aVTrans array, return early */
  89945. for(i=0; i<db->nVTrans; i++){
  89946. if( db->aVTrans[i]==pVTab ){
  89947. return SQLITE_OK;
  89948. }
  89949. }
  89950. /* Invoke the xBegin method. If successful, add the vtab to the
  89951. ** sqlite3.aVTrans[] array. */
  89952. rc = growVTrans(db);
  89953. if( rc==SQLITE_OK ){
  89954. rc = pModule->xBegin(pVTab->pVtab);
  89955. if( rc==SQLITE_OK ){
  89956. addToVTrans(db, pVTab);
  89957. }
  89958. }
  89959. }
  89960. return rc;
  89961. }
  89962. /*
  89963. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  89964. ** virtual tables that currently have an open transaction. Pass iSavepoint
  89965. ** as the second argument to the virtual table method invoked.
  89966. **
  89967. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  89968. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  89969. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  89970. ** an open transaction is invoked.
  89971. **
  89972. ** If any virtual table method returns an error code other than SQLITE_OK,
  89973. ** processing is abandoned and the error returned to the caller of this
  89974. ** function immediately. If all calls to virtual table methods are successful,
  89975. ** SQLITE_OK is returned.
  89976. */
  89977. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  89978. int rc = SQLITE_OK;
  89979. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  89980. assert( iSavepoint>=0 );
  89981. if( db->aVTrans ){
  89982. int i;
  89983. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  89984. VTable *pVTab = db->aVTrans[i];
  89985. const sqlite3_module *pMod = pVTab->pMod->pModule;
  89986. if( pVTab->pVtab && pMod->iVersion>=2 ){
  89987. int (*xMethod)(sqlite3_vtab *, int);
  89988. switch( op ){
  89989. case SAVEPOINT_BEGIN:
  89990. xMethod = pMod->xSavepoint;
  89991. pVTab->iSavepoint = iSavepoint+1;
  89992. break;
  89993. case SAVEPOINT_ROLLBACK:
  89994. xMethod = pMod->xRollbackTo;
  89995. break;
  89996. default:
  89997. xMethod = pMod->xRelease;
  89998. break;
  89999. }
  90000. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  90001. rc = xMethod(pVTab->pVtab, iSavepoint);
  90002. }
  90003. }
  90004. }
  90005. }
  90006. return rc;
  90007. }
  90008. /*
  90009. ** The first parameter (pDef) is a function implementation. The
  90010. ** second parameter (pExpr) is the first argument to this function.
  90011. ** If pExpr is a column in a virtual table, then let the virtual
  90012. ** table implementation have an opportunity to overload the function.
  90013. **
  90014. ** This routine is used to allow virtual table implementations to
  90015. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  90016. **
  90017. ** Return either the pDef argument (indicating no change) or a
  90018. ** new FuncDef structure that is marked as ephemeral using the
  90019. ** SQLITE_FUNC_EPHEM flag.
  90020. */
  90021. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  90022. sqlite3 *db, /* Database connection for reporting malloc problems */
  90023. FuncDef *pDef, /* Function to possibly overload */
  90024. int nArg, /* Number of arguments to the function */
  90025. Expr *pExpr /* First argument to the function */
  90026. ){
  90027. Table *pTab;
  90028. sqlite3_vtab *pVtab;
  90029. sqlite3_module *pMod;
  90030. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  90031. void *pArg = 0;
  90032. FuncDef *pNew;
  90033. int rc = 0;
  90034. char *zLowerName;
  90035. unsigned char *z;
  90036. /* Check to see the left operand is a column in a virtual table */
  90037. if( NEVER(pExpr==0) ) return pDef;
  90038. if( pExpr->op!=TK_COLUMN ) return pDef;
  90039. pTab = pExpr->pTab;
  90040. if( NEVER(pTab==0) ) return pDef;
  90041. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  90042. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  90043. assert( pVtab!=0 );
  90044. assert( pVtab->pModule!=0 );
  90045. pMod = (sqlite3_module *)pVtab->pModule;
  90046. if( pMod->xFindFunction==0 ) return pDef;
  90047. /* Call the xFindFunction method on the virtual table implementation
  90048. ** to see if the implementation wants to overload this function
  90049. */
  90050. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  90051. if( zLowerName ){
  90052. for(z=(unsigned char*)zLowerName; *z; z++){
  90053. *z = sqlite3UpperToLower[*z];
  90054. }
  90055. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  90056. sqlite3DbFree(db, zLowerName);
  90057. }
  90058. if( rc==0 ){
  90059. return pDef;
  90060. }
  90061. /* Create a new ephemeral function definition for the overloaded
  90062. ** function */
  90063. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  90064. + sqlite3Strlen30(pDef->zName) + 1);
  90065. if( pNew==0 ){
  90066. return pDef;
  90067. }
  90068. *pNew = *pDef;
  90069. pNew->zName = (char *)&pNew[1];
  90070. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  90071. pNew->xFunc = xFunc;
  90072. pNew->pUserData = pArg;
  90073. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  90074. return pNew;
  90075. }
  90076. /*
  90077. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  90078. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  90079. ** array if it is missing. If pTab is already in the array, this routine
  90080. ** is a no-op.
  90081. */
  90082. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  90083. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90084. int i, n;
  90085. Table **apVtabLock;
  90086. assert( IsVirtual(pTab) );
  90087. for(i=0; i<pToplevel->nVtabLock; i++){
  90088. if( pTab==pToplevel->apVtabLock[i] ) return;
  90089. }
  90090. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  90091. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  90092. if( apVtabLock ){
  90093. pToplevel->apVtabLock = apVtabLock;
  90094. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  90095. }else{
  90096. pToplevel->db->mallocFailed = 1;
  90097. }
  90098. }
  90099. /*
  90100. ** Return the ON CONFLICT resolution mode in effect for the virtual
  90101. ** table update operation currently in progress.
  90102. **
  90103. ** The results of this routine are undefined unless it is called from
  90104. ** within an xUpdate method.
  90105. */
  90106. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  90107. static const unsigned char aMap[] = {
  90108. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  90109. };
  90110. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  90111. assert( OE_Ignore==4 && OE_Replace==5 );
  90112. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  90113. return (int)aMap[db->vtabOnConflict-1];
  90114. }
  90115. /*
  90116. ** Call from within the xCreate() or xConnect() methods to provide
  90117. ** the SQLite core with additional information about the behavior
  90118. ** of the virtual table being implemented.
  90119. */
  90120. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  90121. va_list ap;
  90122. int rc = SQLITE_OK;
  90123. sqlite3_mutex_enter(db->mutex);
  90124. va_start(ap, op);
  90125. switch( op ){
  90126. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  90127. VtabCtx *p = db->pVtabCtx;
  90128. if( !p ){
  90129. rc = SQLITE_MISUSE_BKPT;
  90130. }else{
  90131. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  90132. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  90133. }
  90134. break;
  90135. }
  90136. default:
  90137. rc = SQLITE_MISUSE_BKPT;
  90138. break;
  90139. }
  90140. va_end(ap);
  90141. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  90142. sqlite3_mutex_leave(db->mutex);
  90143. return rc;
  90144. }
  90145. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  90146. /************** End of vtab.c ************************************************/
  90147. /************** Begin file where.c *******************************************/
  90148. /*
  90149. ** 2001 September 15
  90150. **
  90151. ** The author disclaims copyright to this source code. In place of
  90152. ** a legal notice, here is a blessing:
  90153. **
  90154. ** May you do good and not evil.
  90155. ** May you find forgiveness for yourself and forgive others.
  90156. ** May you share freely, never taking more than you give.
  90157. **
  90158. *************************************************************************
  90159. ** This module contains C code that generates VDBE code used to process
  90160. ** the WHERE clause of SQL statements. This module is responsible for
  90161. ** generating the code that loops through a table looking for applicable
  90162. ** rows. Indices are selected and used to speed the search when doing
  90163. ** so is applicable. Because this module is responsible for selecting
  90164. ** indices, you might also think of this module as the "query optimizer".
  90165. */
  90166. /*
  90167. ** Trace output macros
  90168. */
  90169. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  90170. /***/ int sqlite3WhereTrace = 0;
  90171. #endif
  90172. #if defined(SQLITE_DEBUG) \
  90173. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  90174. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  90175. # define WHERETRACE_ENABLED 1
  90176. #else
  90177. # define WHERETRACE(K,X)
  90178. #endif
  90179. /* Forward references
  90180. */
  90181. typedef struct WhereClause WhereClause;
  90182. typedef struct WhereMaskSet WhereMaskSet;
  90183. typedef struct WhereOrInfo WhereOrInfo;
  90184. typedef struct WhereAndInfo WhereAndInfo;
  90185. typedef struct WhereLevel WhereLevel;
  90186. typedef struct WhereLoop WhereLoop;
  90187. typedef struct WherePath WherePath;
  90188. typedef struct WhereTerm WhereTerm;
  90189. typedef struct WhereLoopBuilder WhereLoopBuilder;
  90190. typedef struct WhereScan WhereScan;
  90191. typedef struct WhereOrCost WhereOrCost;
  90192. typedef struct WhereOrSet WhereOrSet;
  90193. /*
  90194. ** This object contains information needed to implement a single nested
  90195. ** loop in WHERE clause.
  90196. **
  90197. ** Contrast this object with WhereLoop. This object describes the
  90198. ** implementation of the loop. WhereLoop describes the algorithm.
  90199. ** This object contains a pointer to the WhereLoop algorithm as one of
  90200. ** its elements.
  90201. **
  90202. ** The WhereInfo object contains a single instance of this object for
  90203. ** each term in the FROM clause (which is to say, for each of the
  90204. ** nested loops as implemented). The order of WhereLevel objects determines
  90205. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  90206. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  90207. */
  90208. struct WhereLevel {
  90209. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  90210. int iTabCur; /* The VDBE cursor used to access the table */
  90211. int iIdxCur; /* The VDBE cursor used to access pIdx */
  90212. int addrBrk; /* Jump here to break out of the loop */
  90213. int addrNxt; /* Jump here to start the next IN combination */
  90214. int addrCont; /* Jump here to continue with the next loop cycle */
  90215. int addrFirst; /* First instruction of interior of the loop */
  90216. int addrBody; /* Beginning of the body of this loop */
  90217. u8 iFrom; /* Which entry in the FROM clause */
  90218. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  90219. int p1, p2; /* Operands of the opcode used to ends the loop */
  90220. union { /* Information that depends on pWLoop->wsFlags */
  90221. struct {
  90222. int nIn; /* Number of entries in aInLoop[] */
  90223. struct InLoop {
  90224. int iCur; /* The VDBE cursor used by this IN operator */
  90225. int addrInTop; /* Top of the IN loop */
  90226. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  90227. } *aInLoop; /* Information about each nested IN operator */
  90228. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  90229. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  90230. } u;
  90231. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  90232. Bitmask notReady; /* FROM entries not usable at this level */
  90233. };
  90234. /*
  90235. ** Each instance of this object represents an algorithm for evaluating one
  90236. ** term of a join. Every term of the FROM clause will have at least
  90237. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  90238. ** prevent a query solution - which is an error) and many terms of the
  90239. ** FROM clause will have multiple WhereLoop objects, each describing a
  90240. ** potential way of implementing that FROM-clause term, together with
  90241. ** dependencies and cost estimates for using the chosen algorithm.
  90242. **
  90243. ** Query planning consists of building up a collection of these WhereLoop
  90244. ** objects, then computing a particular sequence of WhereLoop objects, with
  90245. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  90246. ** and that minimize the overall cost.
  90247. */
  90248. struct WhereLoop {
  90249. Bitmask prereq; /* Bitmask of other loops that must run first */
  90250. Bitmask maskSelf; /* Bitmask identifying table iTab */
  90251. #ifdef SQLITE_DEBUG
  90252. char cId; /* Symbolic ID of this loop for debugging use */
  90253. #endif
  90254. u8 iTab; /* Position in FROM clause of table for this loop */
  90255. u8 iSortIdx; /* Sorting index number. 0==None */
  90256. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  90257. LogEst rRun; /* Cost of running each loop */
  90258. LogEst nOut; /* Estimated number of output rows */
  90259. union {
  90260. struct { /* Information for internal btree tables */
  90261. int nEq; /* Number of equality constraints */
  90262. Index *pIndex; /* Index used, or NULL */
  90263. } btree;
  90264. struct { /* Information for virtual tables */
  90265. int idxNum; /* Index number */
  90266. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  90267. u8 isOrdered; /* True if satisfies ORDER BY */
  90268. u16 omitMask; /* Terms that may be omitted */
  90269. char *idxStr; /* Index identifier string */
  90270. } vtab;
  90271. } u;
  90272. u32 wsFlags; /* WHERE_* flags describing the plan */
  90273. u16 nLTerm; /* Number of entries in aLTerm[] */
  90274. /**** whereLoopXfer() copies fields above ***********************/
  90275. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  90276. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  90277. WhereTerm **aLTerm; /* WhereTerms used */
  90278. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  90279. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  90280. };
  90281. /* This object holds the prerequisites and the cost of running a
  90282. ** subquery on one operand of an OR operator in the WHERE clause.
  90283. ** See WhereOrSet for additional information
  90284. */
  90285. struct WhereOrCost {
  90286. Bitmask prereq; /* Prerequisites */
  90287. LogEst rRun; /* Cost of running this subquery */
  90288. LogEst nOut; /* Number of outputs for this subquery */
  90289. };
  90290. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  90291. ** correspond to the subquery(s) of OR-clause processing. Only the
  90292. ** best N_OR_COST elements are retained.
  90293. */
  90294. #define N_OR_COST 3
  90295. struct WhereOrSet {
  90296. u16 n; /* Number of valid a[] entries */
  90297. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  90298. };
  90299. /* Forward declaration of methods */
  90300. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  90301. /*
  90302. ** Each instance of this object holds a sequence of WhereLoop objects
  90303. ** that implement some or all of a query plan.
  90304. **
  90305. ** Think of each WhereLoop object as a node in a graph with arcs
  90306. ** showing dependencies and costs for travelling between nodes. (That is
  90307. ** not a completely accurate description because WhereLoop costs are a
  90308. ** vector, not a scalar, and because dependencies are many-to-one, not
  90309. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  90310. ** Then a WherePath object is a path through the graph that visits some
  90311. ** or all of the WhereLoop objects once.
  90312. **
  90313. ** The "solver" works by creating the N best WherePath objects of length
  90314. ** 1. Then using those as a basis to compute the N best WherePath objects
  90315. ** of length 2. And so forth until the length of WherePaths equals the
  90316. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  90317. ** at the end is the choosen query plan.
  90318. */
  90319. struct WherePath {
  90320. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  90321. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  90322. LogEst nRow; /* Estimated number of rows generated by this path */
  90323. LogEst rCost; /* Total cost of this path */
  90324. u8 isOrdered; /* True if this path satisfies ORDER BY */
  90325. u8 isOrderedValid; /* True if the isOrdered field is valid */
  90326. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  90327. };
  90328. /*
  90329. ** The query generator uses an array of instances of this structure to
  90330. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  90331. ** clause subexpression is separated from the others by AND operators,
  90332. ** usually, or sometimes subexpressions separated by OR.
  90333. **
  90334. ** All WhereTerms are collected into a single WhereClause structure.
  90335. ** The following identity holds:
  90336. **
  90337. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  90338. **
  90339. ** When a term is of the form:
  90340. **
  90341. ** X <op> <expr>
  90342. **
  90343. ** where X is a column name and <op> is one of certain operators,
  90344. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  90345. ** cursor number and column number for X. WhereTerm.eOperator records
  90346. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  90347. ** use of a bitmask encoding for the operator allows us to search
  90348. ** quickly for terms that match any of several different operators.
  90349. **
  90350. ** A WhereTerm might also be two or more subterms connected by OR:
  90351. **
  90352. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  90353. **
  90354. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  90355. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  90356. ** is collected about the OR clause.
  90357. **
  90358. ** If a term in the WHERE clause does not match either of the two previous
  90359. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  90360. ** to the original subexpression content and wtFlags is set up appropriately
  90361. ** but no other fields in the WhereTerm object are meaningful.
  90362. **
  90363. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  90364. ** but they do so indirectly. A single WhereMaskSet structure translates
  90365. ** cursor number into bits and the translated bit is stored in the prereq
  90366. ** fields. The translation is used in order to maximize the number of
  90367. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  90368. ** spread out over the non-negative integers. For example, the cursor
  90369. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  90370. ** translates these sparse cursor numbers into consecutive integers
  90371. ** beginning with 0 in order to make the best possible use of the available
  90372. ** bits in the Bitmask. So, in the example above, the cursor numbers
  90373. ** would be mapped into integers 0 through 7.
  90374. **
  90375. ** The number of terms in a join is limited by the number of bits
  90376. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  90377. ** is only able to process joins with 64 or fewer tables.
  90378. */
  90379. struct WhereTerm {
  90380. Expr *pExpr; /* Pointer to the subexpression that is this term */
  90381. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  90382. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  90383. union {
  90384. int leftColumn; /* Column number of X in "X <op> <expr>" */
  90385. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  90386. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  90387. } u;
  90388. LogEst truthProb; /* Probability of truth for this expression */
  90389. u16 eOperator; /* A WO_xx value describing <op> */
  90390. u8 wtFlags; /* TERM_xxx bit flags. See below */
  90391. u8 nChild; /* Number of children that must disable us */
  90392. WhereClause *pWC; /* The clause this term is part of */
  90393. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  90394. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  90395. };
  90396. /*
  90397. ** Allowed values of WhereTerm.wtFlags
  90398. */
  90399. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  90400. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  90401. #define TERM_CODED 0x04 /* This term is already coded */
  90402. #define TERM_COPIED 0x08 /* Has a child */
  90403. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  90404. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  90405. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  90406. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  90407. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  90408. #else
  90409. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  90410. #endif
  90411. /*
  90412. ** An instance of the WhereScan object is used as an iterator for locating
  90413. ** terms in the WHERE clause that are useful to the query planner.
  90414. */
  90415. struct WhereScan {
  90416. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  90417. WhereClause *pWC; /* WhereClause currently being scanned */
  90418. char *zCollName; /* Required collating sequence, if not NULL */
  90419. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  90420. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  90421. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  90422. u32 opMask; /* Acceptable operators */
  90423. int k; /* Resume scanning at this->pWC->a[this->k] */
  90424. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  90425. };
  90426. /*
  90427. ** An instance of the following structure holds all information about a
  90428. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  90429. **
  90430. ** Explanation of pOuter: For a WHERE clause of the form
  90431. **
  90432. ** a AND ((b AND c) OR (d AND e)) AND f
  90433. **
  90434. ** There are separate WhereClause objects for the whole clause and for
  90435. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  90436. ** subclauses points to the WhereClause object for the whole clause.
  90437. */
  90438. struct WhereClause {
  90439. WhereInfo *pWInfo; /* WHERE clause processing context */
  90440. WhereClause *pOuter; /* Outer conjunction */
  90441. u8 op; /* Split operator. TK_AND or TK_OR */
  90442. int nTerm; /* Number of terms */
  90443. int nSlot; /* Number of entries in a[] */
  90444. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  90445. #if defined(SQLITE_SMALL_STACK)
  90446. WhereTerm aStatic[1]; /* Initial static space for a[] */
  90447. #else
  90448. WhereTerm aStatic[8]; /* Initial static space for a[] */
  90449. #endif
  90450. };
  90451. /*
  90452. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  90453. ** a dynamically allocated instance of the following structure.
  90454. */
  90455. struct WhereOrInfo {
  90456. WhereClause wc; /* Decomposition into subterms */
  90457. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  90458. };
  90459. /*
  90460. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  90461. ** a dynamically allocated instance of the following structure.
  90462. */
  90463. struct WhereAndInfo {
  90464. WhereClause wc; /* The subexpression broken out */
  90465. };
  90466. /*
  90467. ** An instance of the following structure keeps track of a mapping
  90468. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  90469. **
  90470. ** The VDBE cursor numbers are small integers contained in
  90471. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  90472. ** clause, the cursor numbers might not begin with 0 and they might
  90473. ** contain gaps in the numbering sequence. But we want to make maximum
  90474. ** use of the bits in our bitmasks. This structure provides a mapping
  90475. ** from the sparse cursor numbers into consecutive integers beginning
  90476. ** with 0.
  90477. **
  90478. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  90479. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  90480. **
  90481. ** For example, if the WHERE clause expression used these VDBE
  90482. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  90483. ** would map those cursor numbers into bits 0 through 5.
  90484. **
  90485. ** Note that the mapping is not necessarily ordered. In the example
  90486. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  90487. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  90488. ** does not really matter. What is important is that sparse cursor
  90489. ** numbers all get mapped into bit numbers that begin with 0 and contain
  90490. ** no gaps.
  90491. */
  90492. struct WhereMaskSet {
  90493. int n; /* Number of assigned cursor values */
  90494. int ix[BMS]; /* Cursor assigned to each bit */
  90495. };
  90496. /*
  90497. ** This object is a convenience wrapper holding all information needed
  90498. ** to construct WhereLoop objects for a particular query.
  90499. */
  90500. struct WhereLoopBuilder {
  90501. WhereInfo *pWInfo; /* Information about this WHERE */
  90502. WhereClause *pWC; /* WHERE clause terms */
  90503. ExprList *pOrderBy; /* ORDER BY clause */
  90504. WhereLoop *pNew; /* Template WhereLoop */
  90505. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  90506. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  90507. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  90508. int nRecValid; /* Number of valid fields currently in pRec */
  90509. #endif
  90510. };
  90511. /*
  90512. ** The WHERE clause processing routine has two halves. The
  90513. ** first part does the start of the WHERE loop and the second
  90514. ** half does the tail of the WHERE loop. An instance of
  90515. ** this structure is returned by the first half and passed
  90516. ** into the second half to give some continuity.
  90517. **
  90518. ** An instance of this object holds the complete state of the query
  90519. ** planner.
  90520. */
  90521. struct WhereInfo {
  90522. Parse *pParse; /* Parsing and code generating context */
  90523. SrcList *pTabList; /* List of tables in the join */
  90524. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  90525. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  90526. WhereLoop *pLoops; /* List of all WhereLoop objects */
  90527. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  90528. LogEst nRowOut; /* Estimated number of output rows */
  90529. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  90530. u8 bOBSat; /* ORDER BY satisfied by indices */
  90531. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  90532. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  90533. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  90534. u8 nLevel; /* Number of nested loop */
  90535. int iTop; /* The very beginning of the WHERE loop */
  90536. int iContinue; /* Jump here to continue with next record */
  90537. int iBreak; /* Jump here to break out of the loop */
  90538. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  90539. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  90540. WhereClause sWC; /* Decomposition of the WHERE clause */
  90541. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  90542. };
  90543. /*
  90544. ** Bitmasks for the operators on WhereTerm objects. These are all
  90545. ** operators that are of interest to the query planner. An
  90546. ** OR-ed combination of these values can be used when searching for
  90547. ** particular WhereTerms within a WhereClause.
  90548. */
  90549. #define WO_IN 0x001
  90550. #define WO_EQ 0x002
  90551. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  90552. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  90553. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  90554. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  90555. #define WO_MATCH 0x040
  90556. #define WO_ISNULL 0x080
  90557. #define WO_OR 0x100 /* Two or more OR-connected terms */
  90558. #define WO_AND 0x200 /* Two or more AND-connected terms */
  90559. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  90560. #define WO_NOOP 0x800 /* This term does not restrict search space */
  90561. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  90562. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  90563. /*
  90564. ** These are definitions of bits in the WhereLoop.wsFlags field.
  90565. ** The particular combination of bits in each WhereLoop help to
  90566. ** determine the algorithm that WhereLoop represents.
  90567. */
  90568. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  90569. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  90570. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  90571. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  90572. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  90573. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  90574. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  90575. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  90576. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  90577. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  90578. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  90579. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  90580. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  90581. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  90582. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  90583. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  90584. /*
  90585. ** Return the estimated number of output rows from a WHERE clause
  90586. */
  90587. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  90588. return sqlite3LogEstToInt(pWInfo->nRowOut);
  90589. }
  90590. /*
  90591. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  90592. ** WHERE clause returns outputs for DISTINCT processing.
  90593. */
  90594. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  90595. return pWInfo->eDistinct;
  90596. }
  90597. /*
  90598. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  90599. ** Return FALSE if the output needs to be sorted.
  90600. */
  90601. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  90602. return pWInfo->bOBSat!=0;
  90603. }
  90604. /*
  90605. ** Return the VDBE address or label to jump to in order to continue
  90606. ** immediately with the next row of a WHERE clause.
  90607. */
  90608. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  90609. return pWInfo->iContinue;
  90610. }
  90611. /*
  90612. ** Return the VDBE address or label to jump to in order to break
  90613. ** out of a WHERE loop.
  90614. */
  90615. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  90616. return pWInfo->iBreak;
  90617. }
  90618. /*
  90619. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  90620. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  90621. ** UPDATE or DELETE might change subsequent WHERE clause results.
  90622. */
  90623. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  90624. return pWInfo->okOnePass;
  90625. }
  90626. /*
  90627. ** Move the content of pSrc into pDest
  90628. */
  90629. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  90630. pDest->n = pSrc->n;
  90631. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  90632. }
  90633. /*
  90634. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  90635. **
  90636. ** The new entry might overwrite an existing entry, or it might be
  90637. ** appended, or it might be discarded. Do whatever is the right thing
  90638. ** so that pSet keeps the N_OR_COST best entries seen so far.
  90639. */
  90640. static int whereOrInsert(
  90641. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  90642. Bitmask prereq, /* Prerequisites of the new entry */
  90643. LogEst rRun, /* Run-cost of the new entry */
  90644. LogEst nOut /* Number of outputs for the new entry */
  90645. ){
  90646. u16 i;
  90647. WhereOrCost *p;
  90648. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  90649. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  90650. goto whereOrInsert_done;
  90651. }
  90652. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  90653. return 0;
  90654. }
  90655. }
  90656. if( pSet->n<N_OR_COST ){
  90657. p = &pSet->a[pSet->n++];
  90658. p->nOut = nOut;
  90659. }else{
  90660. p = pSet->a;
  90661. for(i=1; i<pSet->n; i++){
  90662. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  90663. }
  90664. if( p->rRun<=rRun ) return 0;
  90665. }
  90666. whereOrInsert_done:
  90667. p->prereq = prereq;
  90668. p->rRun = rRun;
  90669. if( p->nOut>nOut ) p->nOut = nOut;
  90670. return 1;
  90671. }
  90672. /*
  90673. ** Initialize a preallocated WhereClause structure.
  90674. */
  90675. static void whereClauseInit(
  90676. WhereClause *pWC, /* The WhereClause to be initialized */
  90677. WhereInfo *pWInfo /* The WHERE processing context */
  90678. ){
  90679. pWC->pWInfo = pWInfo;
  90680. pWC->pOuter = 0;
  90681. pWC->nTerm = 0;
  90682. pWC->nSlot = ArraySize(pWC->aStatic);
  90683. pWC->a = pWC->aStatic;
  90684. }
  90685. /* Forward reference */
  90686. static void whereClauseClear(WhereClause*);
  90687. /*
  90688. ** Deallocate all memory associated with a WhereOrInfo object.
  90689. */
  90690. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  90691. whereClauseClear(&p->wc);
  90692. sqlite3DbFree(db, p);
  90693. }
  90694. /*
  90695. ** Deallocate all memory associated with a WhereAndInfo object.
  90696. */
  90697. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  90698. whereClauseClear(&p->wc);
  90699. sqlite3DbFree(db, p);
  90700. }
  90701. /*
  90702. ** Deallocate a WhereClause structure. The WhereClause structure
  90703. ** itself is not freed. This routine is the inverse of whereClauseInit().
  90704. */
  90705. static void whereClauseClear(WhereClause *pWC){
  90706. int i;
  90707. WhereTerm *a;
  90708. sqlite3 *db = pWC->pWInfo->pParse->db;
  90709. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  90710. if( a->wtFlags & TERM_DYNAMIC ){
  90711. sqlite3ExprDelete(db, a->pExpr);
  90712. }
  90713. if( a->wtFlags & TERM_ORINFO ){
  90714. whereOrInfoDelete(db, a->u.pOrInfo);
  90715. }else if( a->wtFlags & TERM_ANDINFO ){
  90716. whereAndInfoDelete(db, a->u.pAndInfo);
  90717. }
  90718. }
  90719. if( pWC->a!=pWC->aStatic ){
  90720. sqlite3DbFree(db, pWC->a);
  90721. }
  90722. }
  90723. /*
  90724. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  90725. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  90726. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  90727. ** 0 is returned if the new WhereTerm could not be added due to a memory
  90728. ** allocation error. The memory allocation failure will be recorded in
  90729. ** the db->mallocFailed flag so that higher-level functions can detect it.
  90730. **
  90731. ** This routine will increase the size of the pWC->a[] array as necessary.
  90732. **
  90733. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  90734. ** for freeing the expression p is assumed by the WhereClause object pWC.
  90735. ** This is true even if this routine fails to allocate a new WhereTerm.
  90736. **
  90737. ** WARNING: This routine might reallocate the space used to store
  90738. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  90739. ** calling this routine. Such pointers may be reinitialized by referencing
  90740. ** the pWC->a[] array.
  90741. */
  90742. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  90743. WhereTerm *pTerm;
  90744. int idx;
  90745. testcase( wtFlags & TERM_VIRTUAL );
  90746. if( pWC->nTerm>=pWC->nSlot ){
  90747. WhereTerm *pOld = pWC->a;
  90748. sqlite3 *db = pWC->pWInfo->pParse->db;
  90749. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  90750. if( pWC->a==0 ){
  90751. if( wtFlags & TERM_DYNAMIC ){
  90752. sqlite3ExprDelete(db, p);
  90753. }
  90754. pWC->a = pOld;
  90755. return 0;
  90756. }
  90757. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  90758. if( pOld!=pWC->aStatic ){
  90759. sqlite3DbFree(db, pOld);
  90760. }
  90761. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  90762. }
  90763. pTerm = &pWC->a[idx = pWC->nTerm++];
  90764. if( p && ExprHasProperty(p, EP_Unlikely) ){
  90765. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  90766. }else{
  90767. pTerm->truthProb = -1;
  90768. }
  90769. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  90770. pTerm->wtFlags = wtFlags;
  90771. pTerm->pWC = pWC;
  90772. pTerm->iParent = -1;
  90773. return idx;
  90774. }
  90775. /*
  90776. ** This routine identifies subexpressions in the WHERE clause where
  90777. ** each subexpression is separated by the AND operator or some other
  90778. ** operator specified in the op parameter. The WhereClause structure
  90779. ** is filled with pointers to subexpressions. For example:
  90780. **
  90781. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  90782. ** \________/ \_______________/ \________________/
  90783. ** slot[0] slot[1] slot[2]
  90784. **
  90785. ** The original WHERE clause in pExpr is unaltered. All this routine
  90786. ** does is make slot[] entries point to substructure within pExpr.
  90787. **
  90788. ** In the previous sentence and in the diagram, "slot[]" refers to
  90789. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  90790. ** all terms of the WHERE clause.
  90791. */
  90792. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  90793. pWC->op = op;
  90794. if( pExpr==0 ) return;
  90795. if( pExpr->op!=op ){
  90796. whereClauseInsert(pWC, pExpr, 0);
  90797. }else{
  90798. whereSplit(pWC, pExpr->pLeft, op);
  90799. whereSplit(pWC, pExpr->pRight, op);
  90800. }
  90801. }
  90802. /*
  90803. ** Initialize a WhereMaskSet object
  90804. */
  90805. #define initMaskSet(P) (P)->n=0
  90806. /*
  90807. ** Return the bitmask for the given cursor number. Return 0 if
  90808. ** iCursor is not in the set.
  90809. */
  90810. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  90811. int i;
  90812. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  90813. for(i=0; i<pMaskSet->n; i++){
  90814. if( pMaskSet->ix[i]==iCursor ){
  90815. return MASKBIT(i);
  90816. }
  90817. }
  90818. return 0;
  90819. }
  90820. /*
  90821. ** Create a new mask for cursor iCursor.
  90822. **
  90823. ** There is one cursor per table in the FROM clause. The number of
  90824. ** tables in the FROM clause is limited by a test early in the
  90825. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  90826. ** array will never overflow.
  90827. */
  90828. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  90829. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  90830. pMaskSet->ix[pMaskSet->n++] = iCursor;
  90831. }
  90832. /*
  90833. ** These routines walk (recursively) an expression tree and generate
  90834. ** a bitmask indicating which tables are used in that expression
  90835. ** tree.
  90836. */
  90837. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  90838. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  90839. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  90840. Bitmask mask = 0;
  90841. if( p==0 ) return 0;
  90842. if( p->op==TK_COLUMN ){
  90843. mask = getMask(pMaskSet, p->iTable);
  90844. return mask;
  90845. }
  90846. mask = exprTableUsage(pMaskSet, p->pRight);
  90847. mask |= exprTableUsage(pMaskSet, p->pLeft);
  90848. if( ExprHasProperty(p, EP_xIsSelect) ){
  90849. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  90850. }else{
  90851. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  90852. }
  90853. return mask;
  90854. }
  90855. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  90856. int i;
  90857. Bitmask mask = 0;
  90858. if( pList ){
  90859. for(i=0; i<pList->nExpr; i++){
  90860. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  90861. }
  90862. }
  90863. return mask;
  90864. }
  90865. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  90866. Bitmask mask = 0;
  90867. while( pS ){
  90868. SrcList *pSrc = pS->pSrc;
  90869. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  90870. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  90871. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  90872. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  90873. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  90874. if( ALWAYS(pSrc!=0) ){
  90875. int i;
  90876. for(i=0; i<pSrc->nSrc; i++){
  90877. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  90878. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  90879. }
  90880. }
  90881. pS = pS->pPrior;
  90882. }
  90883. return mask;
  90884. }
  90885. /*
  90886. ** Return TRUE if the given operator is one of the operators that is
  90887. ** allowed for an indexable WHERE clause term. The allowed operators are
  90888. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  90889. */
  90890. static int allowedOp(int op){
  90891. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  90892. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  90893. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  90894. assert( TK_GE==TK_EQ+4 );
  90895. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  90896. }
  90897. /*
  90898. ** Swap two objects of type TYPE.
  90899. */
  90900. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  90901. /*
  90902. ** Commute a comparison operator. Expressions of the form "X op Y"
  90903. ** are converted into "Y op X".
  90904. **
  90905. ** If left/right precedence rules come into play when determining the
  90906. ** collating sequence, then COLLATE operators are adjusted to ensure
  90907. ** that the collating sequence does not change. For example:
  90908. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  90909. ** the left hand side of a comparison overrides any collation sequence
  90910. ** attached to the right. For the same reason the EP_Collate flag
  90911. ** is not commuted.
  90912. */
  90913. static void exprCommute(Parse *pParse, Expr *pExpr){
  90914. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  90915. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  90916. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  90917. if( expRight==expLeft ){
  90918. /* Either X and Y both have COLLATE operator or neither do */
  90919. if( expRight ){
  90920. /* Both X and Y have COLLATE operators. Make sure X is always
  90921. ** used by clearing the EP_Collate flag from Y. */
  90922. pExpr->pRight->flags &= ~EP_Collate;
  90923. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  90924. /* Neither X nor Y have COLLATE operators, but X has a non-default
  90925. ** collating sequence. So add the EP_Collate marker on X to cause
  90926. ** it to be searched first. */
  90927. pExpr->pLeft->flags |= EP_Collate;
  90928. }
  90929. }
  90930. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  90931. if( pExpr->op>=TK_GT ){
  90932. assert( TK_LT==TK_GT+2 );
  90933. assert( TK_GE==TK_LE+2 );
  90934. assert( TK_GT>TK_EQ );
  90935. assert( TK_GT<TK_LE );
  90936. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  90937. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  90938. }
  90939. }
  90940. /*
  90941. ** Translate from TK_xx operator to WO_xx bitmask.
  90942. */
  90943. static u16 operatorMask(int op){
  90944. u16 c;
  90945. assert( allowedOp(op) );
  90946. if( op==TK_IN ){
  90947. c = WO_IN;
  90948. }else if( op==TK_ISNULL ){
  90949. c = WO_ISNULL;
  90950. }else{
  90951. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  90952. c = (u16)(WO_EQ<<(op-TK_EQ));
  90953. }
  90954. assert( op!=TK_ISNULL || c==WO_ISNULL );
  90955. assert( op!=TK_IN || c==WO_IN );
  90956. assert( op!=TK_EQ || c==WO_EQ );
  90957. assert( op!=TK_LT || c==WO_LT );
  90958. assert( op!=TK_LE || c==WO_LE );
  90959. assert( op!=TK_GT || c==WO_GT );
  90960. assert( op!=TK_GE || c==WO_GE );
  90961. return c;
  90962. }
  90963. /*
  90964. ** Advance to the next WhereTerm that matches according to the criteria
  90965. ** established when the pScan object was initialized by whereScanInit().
  90966. ** Return NULL if there are no more matching WhereTerms.
  90967. */
  90968. static WhereTerm *whereScanNext(WhereScan *pScan){
  90969. int iCur; /* The cursor on the LHS of the term */
  90970. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  90971. Expr *pX; /* An expression being tested */
  90972. WhereClause *pWC; /* Shorthand for pScan->pWC */
  90973. WhereTerm *pTerm; /* The term being tested */
  90974. int k = pScan->k; /* Where to start scanning */
  90975. while( pScan->iEquiv<=pScan->nEquiv ){
  90976. iCur = pScan->aEquiv[pScan->iEquiv-2];
  90977. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  90978. while( (pWC = pScan->pWC)!=0 ){
  90979. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  90980. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  90981. if( (pTerm->eOperator & WO_EQUIV)!=0
  90982. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  90983. ){
  90984. int j;
  90985. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  90986. assert( pX->op==TK_COLUMN );
  90987. for(j=0; j<pScan->nEquiv; j+=2){
  90988. if( pScan->aEquiv[j]==pX->iTable
  90989. && pScan->aEquiv[j+1]==pX->iColumn ){
  90990. break;
  90991. }
  90992. }
  90993. if( j==pScan->nEquiv ){
  90994. pScan->aEquiv[j] = pX->iTable;
  90995. pScan->aEquiv[j+1] = pX->iColumn;
  90996. pScan->nEquiv += 2;
  90997. }
  90998. }
  90999. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  91000. /* Verify the affinity and collating sequence match */
  91001. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  91002. CollSeq *pColl;
  91003. Parse *pParse = pWC->pWInfo->pParse;
  91004. pX = pTerm->pExpr;
  91005. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  91006. continue;
  91007. }
  91008. assert(pX->pLeft);
  91009. pColl = sqlite3BinaryCompareCollSeq(pParse,
  91010. pX->pLeft, pX->pRight);
  91011. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  91012. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  91013. continue;
  91014. }
  91015. }
  91016. if( (pTerm->eOperator & WO_EQ)!=0
  91017. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  91018. && pX->iTable==pScan->aEquiv[0]
  91019. && pX->iColumn==pScan->aEquiv[1]
  91020. ){
  91021. continue;
  91022. }
  91023. pScan->k = k+1;
  91024. return pTerm;
  91025. }
  91026. }
  91027. }
  91028. pScan->pWC = pScan->pWC->pOuter;
  91029. k = 0;
  91030. }
  91031. pScan->pWC = pScan->pOrigWC;
  91032. k = 0;
  91033. pScan->iEquiv += 2;
  91034. }
  91035. return 0;
  91036. }
  91037. /*
  91038. ** Initialize a WHERE clause scanner object. Return a pointer to the
  91039. ** first match. Return NULL if there are no matches.
  91040. **
  91041. ** The scanner will be searching the WHERE clause pWC. It will look
  91042. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  91043. ** iCur. The <op> must be one of the operators described by opMask.
  91044. **
  91045. ** If the search is for X and the WHERE clause contains terms of the
  91046. ** form X=Y then this routine might also return terms of the form
  91047. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  91048. ** but is enough to handle most commonly occurring SQL statements.
  91049. **
  91050. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  91051. ** index pIdx.
  91052. */
  91053. static WhereTerm *whereScanInit(
  91054. WhereScan *pScan, /* The WhereScan object being initialized */
  91055. WhereClause *pWC, /* The WHERE clause to be scanned */
  91056. int iCur, /* Cursor to scan for */
  91057. int iColumn, /* Column to scan for */
  91058. u32 opMask, /* Operator(s) to scan for */
  91059. Index *pIdx /* Must be compatible with this index */
  91060. ){
  91061. int j;
  91062. /* memset(pScan, 0, sizeof(*pScan)); */
  91063. pScan->pOrigWC = pWC;
  91064. pScan->pWC = pWC;
  91065. if( pIdx && iColumn>=0 ){
  91066. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  91067. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  91068. if( NEVER(j>=pIdx->nColumn) ) return 0;
  91069. }
  91070. pScan->zCollName = pIdx->azColl[j];
  91071. }else{
  91072. pScan->idxaff = 0;
  91073. pScan->zCollName = 0;
  91074. }
  91075. pScan->opMask = opMask;
  91076. pScan->k = 0;
  91077. pScan->aEquiv[0] = iCur;
  91078. pScan->aEquiv[1] = iColumn;
  91079. pScan->nEquiv = 2;
  91080. pScan->iEquiv = 2;
  91081. return whereScanNext(pScan);
  91082. }
  91083. /*
  91084. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  91085. ** where X is a reference to the iColumn of table iCur and <op> is one of
  91086. ** the WO_xx operator codes specified by the op parameter.
  91087. ** Return a pointer to the term. Return 0 if not found.
  91088. **
  91089. ** The term returned might by Y=<expr> if there is another constraint in
  91090. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  91091. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  91092. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  91093. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  91094. ** and the second is for the column number. There are 22 slots in aEquiv[]
  91095. ** so that means we can look for X plus up to 10 other equivalent values.
  91096. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  91097. ** and ... and A9=A10 and A10=<expr>.
  91098. **
  91099. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  91100. ** then try for the one with no dependencies on <expr> - in other words where
  91101. ** <expr> is a constant expression of some kind. Only return entries of
  91102. ** the form "X <op> Y" where Y is a column in another table if no terms of
  91103. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  91104. ** exist, try to return a term that does not use WO_EQUIV.
  91105. */
  91106. static WhereTerm *findTerm(
  91107. WhereClause *pWC, /* The WHERE clause to be searched */
  91108. int iCur, /* Cursor number of LHS */
  91109. int iColumn, /* Column number of LHS */
  91110. Bitmask notReady, /* RHS must not overlap with this mask */
  91111. u32 op, /* Mask of WO_xx values describing operator */
  91112. Index *pIdx /* Must be compatible with this index, if not NULL */
  91113. ){
  91114. WhereTerm *pResult = 0;
  91115. WhereTerm *p;
  91116. WhereScan scan;
  91117. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  91118. while( p ){
  91119. if( (p->prereqRight & notReady)==0 ){
  91120. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  91121. return p;
  91122. }
  91123. if( pResult==0 ) pResult = p;
  91124. }
  91125. p = whereScanNext(&scan);
  91126. }
  91127. return pResult;
  91128. }
  91129. /* Forward reference */
  91130. static void exprAnalyze(SrcList*, WhereClause*, int);
  91131. /*
  91132. ** Call exprAnalyze on all terms in a WHERE clause.
  91133. */
  91134. static void exprAnalyzeAll(
  91135. SrcList *pTabList, /* the FROM clause */
  91136. WhereClause *pWC /* the WHERE clause to be analyzed */
  91137. ){
  91138. int i;
  91139. for(i=pWC->nTerm-1; i>=0; i--){
  91140. exprAnalyze(pTabList, pWC, i);
  91141. }
  91142. }
  91143. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  91144. /*
  91145. ** Check to see if the given expression is a LIKE or GLOB operator that
  91146. ** can be optimized using inequality constraints. Return TRUE if it is
  91147. ** so and false if not.
  91148. **
  91149. ** In order for the operator to be optimizible, the RHS must be a string
  91150. ** literal that does not begin with a wildcard.
  91151. */
  91152. static int isLikeOrGlob(
  91153. Parse *pParse, /* Parsing and code generating context */
  91154. Expr *pExpr, /* Test this expression */
  91155. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  91156. int *pisComplete, /* True if the only wildcard is % in the last character */
  91157. int *pnoCase /* True if uppercase is equivalent to lowercase */
  91158. ){
  91159. const char *z = 0; /* String on RHS of LIKE operator */
  91160. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  91161. ExprList *pList; /* List of operands to the LIKE operator */
  91162. int c; /* One character in z[] */
  91163. int cnt; /* Number of non-wildcard prefix characters */
  91164. char wc[3]; /* Wildcard characters */
  91165. sqlite3 *db = pParse->db; /* Database connection */
  91166. sqlite3_value *pVal = 0;
  91167. int op; /* Opcode of pRight */
  91168. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  91169. return 0;
  91170. }
  91171. #ifdef SQLITE_EBCDIC
  91172. if( *pnoCase ) return 0;
  91173. #endif
  91174. pList = pExpr->x.pList;
  91175. pLeft = pList->a[1].pExpr;
  91176. if( pLeft->op!=TK_COLUMN
  91177. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  91178. || IsVirtual(pLeft->pTab)
  91179. ){
  91180. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  91181. ** be the name of an indexed column with TEXT affinity. */
  91182. return 0;
  91183. }
  91184. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  91185. pRight = pList->a[0].pExpr;
  91186. op = pRight->op;
  91187. if( op==TK_REGISTER ){
  91188. op = pRight->op2;
  91189. }
  91190. if( op==TK_VARIABLE ){
  91191. Vdbe *pReprepare = pParse->pReprepare;
  91192. int iCol = pRight->iColumn;
  91193. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  91194. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  91195. z = (char *)sqlite3_value_text(pVal);
  91196. }
  91197. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  91198. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  91199. }else if( op==TK_STRING ){
  91200. z = pRight->u.zToken;
  91201. }
  91202. if( z ){
  91203. cnt = 0;
  91204. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  91205. cnt++;
  91206. }
  91207. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  91208. Expr *pPrefix;
  91209. *pisComplete = c==wc[0] && z[cnt+1]==0;
  91210. pPrefix = sqlite3Expr(db, TK_STRING, z);
  91211. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  91212. *ppPrefix = pPrefix;
  91213. if( op==TK_VARIABLE ){
  91214. Vdbe *v = pParse->pVdbe;
  91215. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  91216. if( *pisComplete && pRight->u.zToken[1] ){
  91217. /* If the rhs of the LIKE expression is a variable, and the current
  91218. ** value of the variable means there is no need to invoke the LIKE
  91219. ** function, then no OP_Variable will be added to the program.
  91220. ** This causes problems for the sqlite3_bind_parameter_name()
  91221. ** API. To workaround them, add a dummy OP_Variable here.
  91222. */
  91223. int r1 = sqlite3GetTempReg(pParse);
  91224. sqlite3ExprCodeTarget(pParse, pRight, r1);
  91225. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  91226. sqlite3ReleaseTempReg(pParse, r1);
  91227. }
  91228. }
  91229. }else{
  91230. z = 0;
  91231. }
  91232. }
  91233. sqlite3ValueFree(pVal);
  91234. return (z!=0);
  91235. }
  91236. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  91237. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91238. /*
  91239. ** Check to see if the given expression is of the form
  91240. **
  91241. ** column MATCH expr
  91242. **
  91243. ** If it is then return TRUE. If not, return FALSE.
  91244. */
  91245. static int isMatchOfColumn(
  91246. Expr *pExpr /* Test this expression */
  91247. ){
  91248. ExprList *pList;
  91249. if( pExpr->op!=TK_FUNCTION ){
  91250. return 0;
  91251. }
  91252. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  91253. return 0;
  91254. }
  91255. pList = pExpr->x.pList;
  91256. if( pList->nExpr!=2 ){
  91257. return 0;
  91258. }
  91259. if( pList->a[1].pExpr->op != TK_COLUMN ){
  91260. return 0;
  91261. }
  91262. return 1;
  91263. }
  91264. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91265. /*
  91266. ** If the pBase expression originated in the ON or USING clause of
  91267. ** a join, then transfer the appropriate markings over to derived.
  91268. */
  91269. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  91270. if( pDerived ){
  91271. pDerived->flags |= pBase->flags & EP_FromJoin;
  91272. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  91273. }
  91274. }
  91275. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  91276. /*
  91277. ** Analyze a term that consists of two or more OR-connected
  91278. ** subterms. So in:
  91279. **
  91280. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  91281. ** ^^^^^^^^^^^^^^^^^^^^
  91282. **
  91283. ** This routine analyzes terms such as the middle term in the above example.
  91284. ** A WhereOrTerm object is computed and attached to the term under
  91285. ** analysis, regardless of the outcome of the analysis. Hence:
  91286. **
  91287. ** WhereTerm.wtFlags |= TERM_ORINFO
  91288. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  91289. **
  91290. ** The term being analyzed must have two or more of OR-connected subterms.
  91291. ** A single subterm might be a set of AND-connected sub-subterms.
  91292. ** Examples of terms under analysis:
  91293. **
  91294. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  91295. ** (B) x=expr1 OR expr2=x OR x=expr3
  91296. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  91297. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  91298. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  91299. **
  91300. ** CASE 1:
  91301. **
  91302. ** If all subterms are of the form T.C=expr for some single column of C and
  91303. ** a single table T (as shown in example B above) then create a new virtual
  91304. ** term that is an equivalent IN expression. In other words, if the term
  91305. ** being analyzed is:
  91306. **
  91307. ** x = expr1 OR expr2 = x OR x = expr3
  91308. **
  91309. ** then create a new virtual term like this:
  91310. **
  91311. ** x IN (expr1,expr2,expr3)
  91312. **
  91313. ** CASE 2:
  91314. **
  91315. ** If all subterms are indexable by a single table T, then set
  91316. **
  91317. ** WhereTerm.eOperator = WO_OR
  91318. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  91319. **
  91320. ** A subterm is "indexable" if it is of the form
  91321. ** "T.C <op> <expr>" where C is any column of table T and
  91322. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  91323. ** A subterm is also indexable if it is an AND of two or more
  91324. ** subsubterms at least one of which is indexable. Indexable AND
  91325. ** subterms have their eOperator set to WO_AND and they have
  91326. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  91327. **
  91328. ** From another point of view, "indexable" means that the subterm could
  91329. ** potentially be used with an index if an appropriate index exists.
  91330. ** This analysis does not consider whether or not the index exists; that
  91331. ** is decided elsewhere. This analysis only looks at whether subterms
  91332. ** appropriate for indexing exist.
  91333. **
  91334. ** All examples A through E above satisfy case 2. But if a term
  91335. ** also statisfies case 1 (such as B) we know that the optimizer will
  91336. ** always prefer case 1, so in that case we pretend that case 2 is not
  91337. ** satisfied.
  91338. **
  91339. ** It might be the case that multiple tables are indexable. For example,
  91340. ** (E) above is indexable on tables P, Q, and R.
  91341. **
  91342. ** Terms that satisfy case 2 are candidates for lookup by using
  91343. ** separate indices to find rowids for each subterm and composing
  91344. ** the union of all rowids using a RowSet object. This is similar
  91345. ** to "bitmap indices" in other database engines.
  91346. **
  91347. ** OTHERWISE:
  91348. **
  91349. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  91350. ** zero. This term is not useful for search.
  91351. */
  91352. static void exprAnalyzeOrTerm(
  91353. SrcList *pSrc, /* the FROM clause */
  91354. WhereClause *pWC, /* the complete WHERE clause */
  91355. int idxTerm /* Index of the OR-term to be analyzed */
  91356. ){
  91357. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  91358. Parse *pParse = pWInfo->pParse; /* Parser context */
  91359. sqlite3 *db = pParse->db; /* Database connection */
  91360. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  91361. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  91362. int i; /* Loop counters */
  91363. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  91364. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  91365. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  91366. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  91367. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  91368. /*
  91369. ** Break the OR clause into its separate subterms. The subterms are
  91370. ** stored in a WhereClause structure containing within the WhereOrInfo
  91371. ** object that is attached to the original OR clause term.
  91372. */
  91373. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  91374. assert( pExpr->op==TK_OR );
  91375. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  91376. if( pOrInfo==0 ) return;
  91377. pTerm->wtFlags |= TERM_ORINFO;
  91378. pOrWc = &pOrInfo->wc;
  91379. whereClauseInit(pOrWc, pWInfo);
  91380. whereSplit(pOrWc, pExpr, TK_OR);
  91381. exprAnalyzeAll(pSrc, pOrWc);
  91382. if( db->mallocFailed ) return;
  91383. assert( pOrWc->nTerm>=2 );
  91384. /*
  91385. ** Compute the set of tables that might satisfy cases 1 or 2.
  91386. */
  91387. indexable = ~(Bitmask)0;
  91388. chngToIN = ~(Bitmask)0;
  91389. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  91390. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  91391. WhereAndInfo *pAndInfo;
  91392. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  91393. chngToIN = 0;
  91394. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  91395. if( pAndInfo ){
  91396. WhereClause *pAndWC;
  91397. WhereTerm *pAndTerm;
  91398. int j;
  91399. Bitmask b = 0;
  91400. pOrTerm->u.pAndInfo = pAndInfo;
  91401. pOrTerm->wtFlags |= TERM_ANDINFO;
  91402. pOrTerm->eOperator = WO_AND;
  91403. pAndWC = &pAndInfo->wc;
  91404. whereClauseInit(pAndWC, pWC->pWInfo);
  91405. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  91406. exprAnalyzeAll(pSrc, pAndWC);
  91407. pAndWC->pOuter = pWC;
  91408. testcase( db->mallocFailed );
  91409. if( !db->mallocFailed ){
  91410. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  91411. assert( pAndTerm->pExpr );
  91412. if( allowedOp(pAndTerm->pExpr->op) ){
  91413. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  91414. }
  91415. }
  91416. }
  91417. indexable &= b;
  91418. }
  91419. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  91420. /* Skip this term for now. We revisit it when we process the
  91421. ** corresponding TERM_VIRTUAL term */
  91422. }else{
  91423. Bitmask b;
  91424. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  91425. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  91426. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  91427. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  91428. }
  91429. indexable &= b;
  91430. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  91431. chngToIN = 0;
  91432. }else{
  91433. chngToIN &= b;
  91434. }
  91435. }
  91436. }
  91437. /*
  91438. ** Record the set of tables that satisfy case 2. The set might be
  91439. ** empty.
  91440. */
  91441. pOrInfo->indexable = indexable;
  91442. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  91443. /*
  91444. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  91445. ** we have to do some additional checking to see if case 1 really
  91446. ** is satisfied.
  91447. **
  91448. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  91449. ** that there is no possibility of transforming the OR clause into an
  91450. ** IN operator because one or more terms in the OR clause contain
  91451. ** something other than == on a column in the single table. The 1-bit
  91452. ** case means that every term of the OR clause is of the form
  91453. ** "table.column=expr" for some single table. The one bit that is set
  91454. ** will correspond to the common table. We still need to check to make
  91455. ** sure the same column is used on all terms. The 2-bit case is when
  91456. ** the all terms are of the form "table1.column=table2.column". It
  91457. ** might be possible to form an IN operator with either table1.column
  91458. ** or table2.column as the LHS if either is common to every term of
  91459. ** the OR clause.
  91460. **
  91461. ** Note that terms of the form "table.column1=table.column2" (the
  91462. ** same table on both sizes of the ==) cannot be optimized.
  91463. */
  91464. if( chngToIN ){
  91465. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  91466. int iColumn = -1; /* Column index on lhs of IN operator */
  91467. int iCursor = -1; /* Table cursor common to all terms */
  91468. int j = 0; /* Loop counter */
  91469. /* Search for a table and column that appears on one side or the
  91470. ** other of the == operator in every subterm. That table and column
  91471. ** will be recorded in iCursor and iColumn. There might not be any
  91472. ** such table and column. Set okToChngToIN if an appropriate table
  91473. ** and column is found but leave okToChngToIN false if not found.
  91474. */
  91475. for(j=0; j<2 && !okToChngToIN; j++){
  91476. pOrTerm = pOrWc->a;
  91477. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  91478. assert( pOrTerm->eOperator & WO_EQ );
  91479. pOrTerm->wtFlags &= ~TERM_OR_OK;
  91480. if( pOrTerm->leftCursor==iCursor ){
  91481. /* This is the 2-bit case and we are on the second iteration and
  91482. ** current term is from the first iteration. So skip this term. */
  91483. assert( j==1 );
  91484. continue;
  91485. }
  91486. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  91487. /* This term must be of the form t1.a==t2.b where t2 is in the
  91488. ** chngToIN set but t1 is not. This term will be either preceeded
  91489. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  91490. ** and use its inversion. */
  91491. testcase( pOrTerm->wtFlags & TERM_COPIED );
  91492. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  91493. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  91494. continue;
  91495. }
  91496. iColumn = pOrTerm->u.leftColumn;
  91497. iCursor = pOrTerm->leftCursor;
  91498. break;
  91499. }
  91500. if( i<0 ){
  91501. /* No candidate table+column was found. This can only occur
  91502. ** on the second iteration */
  91503. assert( j==1 );
  91504. assert( IsPowerOfTwo(chngToIN) );
  91505. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  91506. break;
  91507. }
  91508. testcase( j==1 );
  91509. /* We have found a candidate table and column. Check to see if that
  91510. ** table and column is common to every term in the OR clause */
  91511. okToChngToIN = 1;
  91512. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  91513. assert( pOrTerm->eOperator & WO_EQ );
  91514. if( pOrTerm->leftCursor!=iCursor ){
  91515. pOrTerm->wtFlags &= ~TERM_OR_OK;
  91516. }else if( pOrTerm->u.leftColumn!=iColumn ){
  91517. okToChngToIN = 0;
  91518. }else{
  91519. int affLeft, affRight;
  91520. /* If the right-hand side is also a column, then the affinities
  91521. ** of both right and left sides must be such that no type
  91522. ** conversions are required on the right. (Ticket #2249)
  91523. */
  91524. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  91525. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  91526. if( affRight!=0 && affRight!=affLeft ){
  91527. okToChngToIN = 0;
  91528. }else{
  91529. pOrTerm->wtFlags |= TERM_OR_OK;
  91530. }
  91531. }
  91532. }
  91533. }
  91534. /* At this point, okToChngToIN is true if original pTerm satisfies
  91535. ** case 1. In that case, construct a new virtual term that is
  91536. ** pTerm converted into an IN operator.
  91537. */
  91538. if( okToChngToIN ){
  91539. Expr *pDup; /* A transient duplicate expression */
  91540. ExprList *pList = 0; /* The RHS of the IN operator */
  91541. Expr *pLeft = 0; /* The LHS of the IN operator */
  91542. Expr *pNew; /* The complete IN operator */
  91543. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  91544. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  91545. assert( pOrTerm->eOperator & WO_EQ );
  91546. assert( pOrTerm->leftCursor==iCursor );
  91547. assert( pOrTerm->u.leftColumn==iColumn );
  91548. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  91549. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  91550. pLeft = pOrTerm->pExpr->pLeft;
  91551. }
  91552. assert( pLeft!=0 );
  91553. pDup = sqlite3ExprDup(db, pLeft, 0);
  91554. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  91555. if( pNew ){
  91556. int idxNew;
  91557. transferJoinMarkings(pNew, pExpr);
  91558. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  91559. pNew->x.pList = pList;
  91560. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  91561. testcase( idxNew==0 );
  91562. exprAnalyze(pSrc, pWC, idxNew);
  91563. pTerm = &pWC->a[idxTerm];
  91564. pWC->a[idxNew].iParent = idxTerm;
  91565. pTerm->nChild = 1;
  91566. }else{
  91567. sqlite3ExprListDelete(db, pList);
  91568. }
  91569. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  91570. }
  91571. }
  91572. }
  91573. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  91574. /*
  91575. ** The input to this routine is an WhereTerm structure with only the
  91576. ** "pExpr" field filled in. The job of this routine is to analyze the
  91577. ** subexpression and populate all the other fields of the WhereTerm
  91578. ** structure.
  91579. **
  91580. ** If the expression is of the form "<expr> <op> X" it gets commuted
  91581. ** to the standard form of "X <op> <expr>".
  91582. **
  91583. ** If the expression is of the form "X <op> Y" where both X and Y are
  91584. ** columns, then the original expression is unchanged and a new virtual
  91585. ** term of the form "Y <op> X" is added to the WHERE clause and
  91586. ** analyzed separately. The original term is marked with TERM_COPIED
  91587. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  91588. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  91589. ** is a commuted copy of a prior term.) The original term has nChild=1
  91590. ** and the copy has idxParent set to the index of the original term.
  91591. */
  91592. static void exprAnalyze(
  91593. SrcList *pSrc, /* the FROM clause */
  91594. WhereClause *pWC, /* the WHERE clause */
  91595. int idxTerm /* Index of the term to be analyzed */
  91596. ){
  91597. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  91598. WhereTerm *pTerm; /* The term to be analyzed */
  91599. WhereMaskSet *pMaskSet; /* Set of table index masks */
  91600. Expr *pExpr; /* The expression to be analyzed */
  91601. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  91602. Bitmask prereqAll; /* Prerequesites of pExpr */
  91603. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  91604. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  91605. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  91606. int noCase = 0; /* LIKE/GLOB distinguishes case */
  91607. int op; /* Top-level operator. pExpr->op */
  91608. Parse *pParse = pWInfo->pParse; /* Parsing context */
  91609. sqlite3 *db = pParse->db; /* Database connection */
  91610. if( db->mallocFailed ){
  91611. return;
  91612. }
  91613. pTerm = &pWC->a[idxTerm];
  91614. pMaskSet = &pWInfo->sMaskSet;
  91615. pExpr = pTerm->pExpr;
  91616. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  91617. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  91618. op = pExpr->op;
  91619. if( op==TK_IN ){
  91620. assert( pExpr->pRight==0 );
  91621. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91622. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  91623. }else{
  91624. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  91625. }
  91626. }else if( op==TK_ISNULL ){
  91627. pTerm->prereqRight = 0;
  91628. }else{
  91629. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  91630. }
  91631. prereqAll = exprTableUsage(pMaskSet, pExpr);
  91632. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  91633. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  91634. prereqAll |= x;
  91635. extraRight = x-1; /* ON clause terms may not be used with an index
  91636. ** on left table of a LEFT JOIN. Ticket #3015 */
  91637. }
  91638. pTerm->prereqAll = prereqAll;
  91639. pTerm->leftCursor = -1;
  91640. pTerm->iParent = -1;
  91641. pTerm->eOperator = 0;
  91642. if( allowedOp(op) ){
  91643. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  91644. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  91645. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  91646. if( pLeft->op==TK_COLUMN ){
  91647. pTerm->leftCursor = pLeft->iTable;
  91648. pTerm->u.leftColumn = pLeft->iColumn;
  91649. pTerm->eOperator = operatorMask(op) & opMask;
  91650. }
  91651. if( pRight && pRight->op==TK_COLUMN ){
  91652. WhereTerm *pNew;
  91653. Expr *pDup;
  91654. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  91655. if( pTerm->leftCursor>=0 ){
  91656. int idxNew;
  91657. pDup = sqlite3ExprDup(db, pExpr, 0);
  91658. if( db->mallocFailed ){
  91659. sqlite3ExprDelete(db, pDup);
  91660. return;
  91661. }
  91662. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  91663. if( idxNew==0 ) return;
  91664. pNew = &pWC->a[idxNew];
  91665. pNew->iParent = idxTerm;
  91666. pTerm = &pWC->a[idxTerm];
  91667. pTerm->nChild = 1;
  91668. pTerm->wtFlags |= TERM_COPIED;
  91669. if( pExpr->op==TK_EQ
  91670. && !ExprHasProperty(pExpr, EP_FromJoin)
  91671. && OptimizationEnabled(db, SQLITE_Transitive)
  91672. ){
  91673. pTerm->eOperator |= WO_EQUIV;
  91674. eExtraOp = WO_EQUIV;
  91675. }
  91676. }else{
  91677. pDup = pExpr;
  91678. pNew = pTerm;
  91679. }
  91680. exprCommute(pParse, pDup);
  91681. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  91682. pNew->leftCursor = pLeft->iTable;
  91683. pNew->u.leftColumn = pLeft->iColumn;
  91684. testcase( (prereqLeft | extraRight) != prereqLeft );
  91685. pNew->prereqRight = prereqLeft | extraRight;
  91686. pNew->prereqAll = prereqAll;
  91687. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  91688. }
  91689. }
  91690. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  91691. /* If a term is the BETWEEN operator, create two new virtual terms
  91692. ** that define the range that the BETWEEN implements. For example:
  91693. **
  91694. ** a BETWEEN b AND c
  91695. **
  91696. ** is converted into:
  91697. **
  91698. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  91699. **
  91700. ** The two new terms are added onto the end of the WhereClause object.
  91701. ** The new terms are "dynamic" and are children of the original BETWEEN
  91702. ** term. That means that if the BETWEEN term is coded, the children are
  91703. ** skipped. Or, if the children are satisfied by an index, the original
  91704. ** BETWEEN term is skipped.
  91705. */
  91706. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  91707. ExprList *pList = pExpr->x.pList;
  91708. int i;
  91709. static const u8 ops[] = {TK_GE, TK_LE};
  91710. assert( pList!=0 );
  91711. assert( pList->nExpr==2 );
  91712. for(i=0; i<2; i++){
  91713. Expr *pNewExpr;
  91714. int idxNew;
  91715. pNewExpr = sqlite3PExpr(pParse, ops[i],
  91716. sqlite3ExprDup(db, pExpr->pLeft, 0),
  91717. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  91718. transferJoinMarkings(pNewExpr, pExpr);
  91719. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  91720. testcase( idxNew==0 );
  91721. exprAnalyze(pSrc, pWC, idxNew);
  91722. pTerm = &pWC->a[idxTerm];
  91723. pWC->a[idxNew].iParent = idxTerm;
  91724. }
  91725. pTerm->nChild = 2;
  91726. }
  91727. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  91728. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  91729. /* Analyze a term that is composed of two or more subterms connected by
  91730. ** an OR operator.
  91731. */
  91732. else if( pExpr->op==TK_OR ){
  91733. assert( pWC->op==TK_AND );
  91734. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  91735. pTerm = &pWC->a[idxTerm];
  91736. }
  91737. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  91738. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  91739. /* Add constraints to reduce the search space on a LIKE or GLOB
  91740. ** operator.
  91741. **
  91742. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  91743. **
  91744. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  91745. **
  91746. ** The last character of the prefix "abc" is incremented to form the
  91747. ** termination condition "abd".
  91748. */
  91749. if( pWC->op==TK_AND
  91750. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  91751. ){
  91752. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  91753. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  91754. Expr *pNewExpr1;
  91755. Expr *pNewExpr2;
  91756. int idxNew1;
  91757. int idxNew2;
  91758. Token sCollSeqName; /* Name of collating sequence */
  91759. pLeft = pExpr->x.pList->a[1].pExpr;
  91760. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  91761. if( !db->mallocFailed ){
  91762. u8 c, *pC; /* Last character before the first wildcard */
  91763. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  91764. c = *pC;
  91765. if( noCase ){
  91766. /* The point is to increment the last character before the first
  91767. ** wildcard. But if we increment '@', that will push it into the
  91768. ** alphabetic range where case conversions will mess up the
  91769. ** inequality. To avoid this, make sure to also run the full
  91770. ** LIKE on all candidate expressions by clearing the isComplete flag
  91771. */
  91772. if( c=='A'-1 ) isComplete = 0;
  91773. c = sqlite3UpperToLower[c];
  91774. }
  91775. *pC = c + 1;
  91776. }
  91777. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  91778. sCollSeqName.n = 6;
  91779. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  91780. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  91781. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  91782. pStr1, 0);
  91783. transferJoinMarkings(pNewExpr1, pExpr);
  91784. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  91785. testcase( idxNew1==0 );
  91786. exprAnalyze(pSrc, pWC, idxNew1);
  91787. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  91788. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  91789. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  91790. pStr2, 0);
  91791. transferJoinMarkings(pNewExpr2, pExpr);
  91792. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  91793. testcase( idxNew2==0 );
  91794. exprAnalyze(pSrc, pWC, idxNew2);
  91795. pTerm = &pWC->a[idxTerm];
  91796. if( isComplete ){
  91797. pWC->a[idxNew1].iParent = idxTerm;
  91798. pWC->a[idxNew2].iParent = idxTerm;
  91799. pTerm->nChild = 2;
  91800. }
  91801. }
  91802. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  91803. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91804. /* Add a WO_MATCH auxiliary term to the constraint set if the
  91805. ** current expression is of the form: column MATCH expr.
  91806. ** This information is used by the xBestIndex methods of
  91807. ** virtual tables. The native query optimizer does not attempt
  91808. ** to do anything with MATCH functions.
  91809. */
  91810. if( isMatchOfColumn(pExpr) ){
  91811. int idxNew;
  91812. Expr *pRight, *pLeft;
  91813. WhereTerm *pNewTerm;
  91814. Bitmask prereqColumn, prereqExpr;
  91815. pRight = pExpr->x.pList->a[0].pExpr;
  91816. pLeft = pExpr->x.pList->a[1].pExpr;
  91817. prereqExpr = exprTableUsage(pMaskSet, pRight);
  91818. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  91819. if( (prereqExpr & prereqColumn)==0 ){
  91820. Expr *pNewExpr;
  91821. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  91822. 0, sqlite3ExprDup(db, pRight, 0), 0);
  91823. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  91824. testcase( idxNew==0 );
  91825. pNewTerm = &pWC->a[idxNew];
  91826. pNewTerm->prereqRight = prereqExpr;
  91827. pNewTerm->leftCursor = pLeft->iTable;
  91828. pNewTerm->u.leftColumn = pLeft->iColumn;
  91829. pNewTerm->eOperator = WO_MATCH;
  91830. pNewTerm->iParent = idxTerm;
  91831. pTerm = &pWC->a[idxTerm];
  91832. pTerm->nChild = 1;
  91833. pTerm->wtFlags |= TERM_COPIED;
  91834. pNewTerm->prereqAll = pTerm->prereqAll;
  91835. }
  91836. }
  91837. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91838. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91839. /* When sqlite_stat3 histogram data is available an operator of the
  91840. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  91841. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  91842. ** virtual term of that form.
  91843. **
  91844. ** Note that the virtual term must be tagged with TERM_VNULL. This
  91845. ** TERM_VNULL tag will suppress the not-null check at the beginning
  91846. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  91847. ** the start of the loop will prevent any results from being returned.
  91848. */
  91849. if( pExpr->op==TK_NOTNULL
  91850. && pExpr->pLeft->op==TK_COLUMN
  91851. && pExpr->pLeft->iColumn>=0
  91852. && OptimizationEnabled(db, SQLITE_Stat3)
  91853. ){
  91854. Expr *pNewExpr;
  91855. Expr *pLeft = pExpr->pLeft;
  91856. int idxNew;
  91857. WhereTerm *pNewTerm;
  91858. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  91859. sqlite3ExprDup(db, pLeft, 0),
  91860. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  91861. idxNew = whereClauseInsert(pWC, pNewExpr,
  91862. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  91863. if( idxNew ){
  91864. pNewTerm = &pWC->a[idxNew];
  91865. pNewTerm->prereqRight = 0;
  91866. pNewTerm->leftCursor = pLeft->iTable;
  91867. pNewTerm->u.leftColumn = pLeft->iColumn;
  91868. pNewTerm->eOperator = WO_GT;
  91869. pNewTerm->iParent = idxTerm;
  91870. pTerm = &pWC->a[idxTerm];
  91871. pTerm->nChild = 1;
  91872. pTerm->wtFlags |= TERM_COPIED;
  91873. pNewTerm->prereqAll = pTerm->prereqAll;
  91874. }
  91875. }
  91876. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91877. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  91878. ** an index for tables to the left of the join.
  91879. */
  91880. pTerm->prereqRight |= extraRight;
  91881. }
  91882. /*
  91883. ** This function searches pList for a entry that matches the iCol-th column
  91884. ** of index pIdx.
  91885. **
  91886. ** If such an expression is found, its index in pList->a[] is returned. If
  91887. ** no expression is found, -1 is returned.
  91888. */
  91889. static int findIndexCol(
  91890. Parse *pParse, /* Parse context */
  91891. ExprList *pList, /* Expression list to search */
  91892. int iBase, /* Cursor for table associated with pIdx */
  91893. Index *pIdx, /* Index to match column of */
  91894. int iCol /* Column of index to match */
  91895. ){
  91896. int i;
  91897. const char *zColl = pIdx->azColl[iCol];
  91898. for(i=0; i<pList->nExpr; i++){
  91899. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  91900. if( p->op==TK_COLUMN
  91901. && p->iColumn==pIdx->aiColumn[iCol]
  91902. && p->iTable==iBase
  91903. ){
  91904. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  91905. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  91906. return i;
  91907. }
  91908. }
  91909. }
  91910. return -1;
  91911. }
  91912. /*
  91913. ** Return true if the DISTINCT expression-list passed as the third argument
  91914. ** is redundant.
  91915. **
  91916. ** A DISTINCT list is redundant if the database contains some subset of
  91917. ** columns that are unique and non-null.
  91918. */
  91919. static int isDistinctRedundant(
  91920. Parse *pParse, /* Parsing context */
  91921. SrcList *pTabList, /* The FROM clause */
  91922. WhereClause *pWC, /* The WHERE clause */
  91923. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  91924. ){
  91925. Table *pTab;
  91926. Index *pIdx;
  91927. int i;
  91928. int iBase;
  91929. /* If there is more than one table or sub-select in the FROM clause of
  91930. ** this query, then it will not be possible to show that the DISTINCT
  91931. ** clause is redundant. */
  91932. if( pTabList->nSrc!=1 ) return 0;
  91933. iBase = pTabList->a[0].iCursor;
  91934. pTab = pTabList->a[0].pTab;
  91935. /* If any of the expressions is an IPK column on table iBase, then return
  91936. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  91937. ** current SELECT is a correlated sub-query.
  91938. */
  91939. for(i=0; i<pDistinct->nExpr; i++){
  91940. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  91941. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  91942. }
  91943. /* Loop through all indices on the table, checking each to see if it makes
  91944. ** the DISTINCT qualifier redundant. It does so if:
  91945. **
  91946. ** 1. The index is itself UNIQUE, and
  91947. **
  91948. ** 2. All of the columns in the index are either part of the pDistinct
  91949. ** list, or else the WHERE clause contains a term of the form "col=X",
  91950. ** where X is a constant value. The collation sequences of the
  91951. ** comparison and select-list expressions must match those of the index.
  91952. **
  91953. ** 3. All of those index columns for which the WHERE clause does not
  91954. ** contain a "col=X" term are subject to a NOT NULL constraint.
  91955. */
  91956. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91957. if( pIdx->onError==OE_None ) continue;
  91958. for(i=0; i<pIdx->nColumn; i++){
  91959. int iCol = pIdx->aiColumn[i];
  91960. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  91961. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  91962. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  91963. break;
  91964. }
  91965. }
  91966. }
  91967. if( i==pIdx->nColumn ){
  91968. /* This index implies that the DISTINCT qualifier is redundant. */
  91969. return 1;
  91970. }
  91971. }
  91972. return 0;
  91973. }
  91974. /*
  91975. ** Estimate the logarithm of the input value to base 2.
  91976. */
  91977. static LogEst estLog(LogEst N){
  91978. LogEst x = sqlite3LogEst(N);
  91979. return x>33 ? x - 33 : 0;
  91980. }
  91981. /*
  91982. ** Two routines for printing the content of an sqlite3_index_info
  91983. ** structure. Used for testing and debugging only. If neither
  91984. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  91985. ** are no-ops.
  91986. */
  91987. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  91988. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  91989. int i;
  91990. if( !sqlite3WhereTrace ) return;
  91991. for(i=0; i<p->nConstraint; i++){
  91992. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  91993. i,
  91994. p->aConstraint[i].iColumn,
  91995. p->aConstraint[i].iTermOffset,
  91996. p->aConstraint[i].op,
  91997. p->aConstraint[i].usable);
  91998. }
  91999. for(i=0; i<p->nOrderBy; i++){
  92000. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  92001. i,
  92002. p->aOrderBy[i].iColumn,
  92003. p->aOrderBy[i].desc);
  92004. }
  92005. }
  92006. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  92007. int i;
  92008. if( !sqlite3WhereTrace ) return;
  92009. for(i=0; i<p->nConstraint; i++){
  92010. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  92011. i,
  92012. p->aConstraintUsage[i].argvIndex,
  92013. p->aConstraintUsage[i].omit);
  92014. }
  92015. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  92016. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  92017. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  92018. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  92019. }
  92020. #else
  92021. #define TRACE_IDX_INPUTS(A)
  92022. #define TRACE_IDX_OUTPUTS(A)
  92023. #endif
  92024. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92025. /*
  92026. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  92027. ** could be used with an index to access pSrc, assuming an appropriate
  92028. ** index existed.
  92029. */
  92030. static int termCanDriveIndex(
  92031. WhereTerm *pTerm, /* WHERE clause term to check */
  92032. struct SrcList_item *pSrc, /* Table we are trying to access */
  92033. Bitmask notReady /* Tables in outer loops of the join */
  92034. ){
  92035. char aff;
  92036. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  92037. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  92038. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  92039. if( pTerm->u.leftColumn<0 ) return 0;
  92040. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  92041. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  92042. return 1;
  92043. }
  92044. #endif
  92045. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92046. /*
  92047. ** Generate code to construct the Index object for an automatic index
  92048. ** and to set up the WhereLevel object pLevel so that the code generator
  92049. ** makes use of the automatic index.
  92050. */
  92051. static void constructAutomaticIndex(
  92052. Parse *pParse, /* The parsing context */
  92053. WhereClause *pWC, /* The WHERE clause */
  92054. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  92055. Bitmask notReady, /* Mask of cursors that are not available */
  92056. WhereLevel *pLevel /* Write new index here */
  92057. ){
  92058. int nColumn; /* Number of columns in the constructed index */
  92059. WhereTerm *pTerm; /* A single term of the WHERE clause */
  92060. WhereTerm *pWCEnd; /* End of pWC->a[] */
  92061. int nByte; /* Byte of memory needed for pIdx */
  92062. Index *pIdx; /* Object describing the transient index */
  92063. Vdbe *v; /* Prepared statement under construction */
  92064. int addrInit; /* Address of the initialization bypass jump */
  92065. Table *pTable; /* The table being indexed */
  92066. KeyInfo *pKeyinfo; /* Key information for the index */
  92067. int addrTop; /* Top of the index fill loop */
  92068. int regRecord; /* Register holding an index record */
  92069. int n; /* Column counter */
  92070. int i; /* Loop counter */
  92071. int mxBitCol; /* Maximum column in pSrc->colUsed */
  92072. CollSeq *pColl; /* Collating sequence to on a column */
  92073. WhereLoop *pLoop; /* The Loop object */
  92074. Bitmask idxCols; /* Bitmap of columns used for indexing */
  92075. Bitmask extraCols; /* Bitmap of additional columns */
  92076. u8 sentWarning = 0; /* True if a warnning has been issued */
  92077. /* Generate code to skip over the creation and initialization of the
  92078. ** transient index on 2nd and subsequent iterations of the loop. */
  92079. v = pParse->pVdbe;
  92080. assert( v!=0 );
  92081. addrInit = sqlite3CodeOnce(pParse);
  92082. /* Count the number of columns that will be added to the index
  92083. ** and used to match WHERE clause constraints */
  92084. nColumn = 0;
  92085. pTable = pSrc->pTab;
  92086. pWCEnd = &pWC->a[pWC->nTerm];
  92087. pLoop = pLevel->pWLoop;
  92088. idxCols = 0;
  92089. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92090. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92091. int iCol = pTerm->u.leftColumn;
  92092. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  92093. testcase( iCol==BMS );
  92094. testcase( iCol==BMS-1 );
  92095. if( !sentWarning ){
  92096. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  92097. "automatic index on %s(%s)", pTable->zName,
  92098. pTable->aCol[iCol].zName);
  92099. sentWarning = 1;
  92100. }
  92101. if( (idxCols & cMask)==0 ){
  92102. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  92103. pLoop->aLTerm[nColumn++] = pTerm;
  92104. idxCols |= cMask;
  92105. }
  92106. }
  92107. }
  92108. assert( nColumn>0 );
  92109. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  92110. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  92111. | WHERE_AUTO_INDEX;
  92112. /* Count the number of additional columns needed to create a
  92113. ** covering index. A "covering index" is an index that contains all
  92114. ** columns that are needed by the query. With a covering index, the
  92115. ** original table never needs to be accessed. Automatic indices must
  92116. ** be a covering index because the index will not be updated if the
  92117. ** original table changes and the index and table cannot both be used
  92118. ** if they go out of sync.
  92119. */
  92120. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  92121. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  92122. testcase( pTable->nCol==BMS-1 );
  92123. testcase( pTable->nCol==BMS-2 );
  92124. for(i=0; i<mxBitCol; i++){
  92125. if( extraCols & MASKBIT(i) ) nColumn++;
  92126. }
  92127. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  92128. nColumn += pTable->nCol - BMS + 1;
  92129. }
  92130. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  92131. /* Construct the Index object to describe this index */
  92132. nByte = sizeof(Index);
  92133. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  92134. nByte += nColumn*sizeof(char*); /* Index.azColl */
  92135. nByte += nColumn; /* Index.aSortOrder */
  92136. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  92137. if( pIdx==0 ) return;
  92138. pLoop->u.btree.pIndex = pIdx;
  92139. pIdx->azColl = (char**)&pIdx[1];
  92140. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  92141. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  92142. pIdx->zName = "auto-index";
  92143. pIdx->nColumn = nColumn;
  92144. pIdx->pTable = pTable;
  92145. n = 0;
  92146. idxCols = 0;
  92147. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92148. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92149. int iCol = pTerm->u.leftColumn;
  92150. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  92151. testcase( iCol==BMS-1 );
  92152. testcase( iCol==BMS );
  92153. if( (idxCols & cMask)==0 ){
  92154. Expr *pX = pTerm->pExpr;
  92155. idxCols |= cMask;
  92156. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  92157. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  92158. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  92159. n++;
  92160. }
  92161. }
  92162. }
  92163. assert( (u32)n==pLoop->u.btree.nEq );
  92164. /* Add additional columns needed to make the automatic index into
  92165. ** a covering index */
  92166. for(i=0; i<mxBitCol; i++){
  92167. if( extraCols & MASKBIT(i) ){
  92168. pIdx->aiColumn[n] = i;
  92169. pIdx->azColl[n] = "BINARY";
  92170. n++;
  92171. }
  92172. }
  92173. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  92174. for(i=BMS-1; i<pTable->nCol; i++){
  92175. pIdx->aiColumn[n] = i;
  92176. pIdx->azColl[n] = "BINARY";
  92177. n++;
  92178. }
  92179. }
  92180. assert( n==nColumn );
  92181. /* Create the automatic index */
  92182. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  92183. assert( pLevel->iIdxCur>=0 );
  92184. pLevel->iIdxCur = pParse->nTab++;
  92185. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  92186. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  92187. VdbeComment((v, "for %s", pTable->zName));
  92188. /* Fill the automatic index with content */
  92189. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  92190. regRecord = sqlite3GetTempReg(pParse);
  92191. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  92192. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  92193. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  92194. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  92195. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  92196. sqlite3VdbeJumpHere(v, addrTop);
  92197. sqlite3ReleaseTempReg(pParse, regRecord);
  92198. /* Jump here when skipping the initialization */
  92199. sqlite3VdbeJumpHere(v, addrInit);
  92200. }
  92201. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  92202. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92203. /*
  92204. ** Allocate and populate an sqlite3_index_info structure. It is the
  92205. ** responsibility of the caller to eventually release the structure
  92206. ** by passing the pointer returned by this function to sqlite3_free().
  92207. */
  92208. static sqlite3_index_info *allocateIndexInfo(
  92209. Parse *pParse,
  92210. WhereClause *pWC,
  92211. struct SrcList_item *pSrc,
  92212. ExprList *pOrderBy
  92213. ){
  92214. int i, j;
  92215. int nTerm;
  92216. struct sqlite3_index_constraint *pIdxCons;
  92217. struct sqlite3_index_orderby *pIdxOrderBy;
  92218. struct sqlite3_index_constraint_usage *pUsage;
  92219. WhereTerm *pTerm;
  92220. int nOrderBy;
  92221. sqlite3_index_info *pIdxInfo;
  92222. /* Count the number of possible WHERE clause constraints referring
  92223. ** to this virtual table */
  92224. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  92225. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  92226. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  92227. testcase( pTerm->eOperator & WO_IN );
  92228. testcase( pTerm->eOperator & WO_ISNULL );
  92229. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  92230. if( pTerm->wtFlags & TERM_VNULL ) continue;
  92231. nTerm++;
  92232. }
  92233. /* If the ORDER BY clause contains only columns in the current
  92234. ** virtual table then allocate space for the aOrderBy part of
  92235. ** the sqlite3_index_info structure.
  92236. */
  92237. nOrderBy = 0;
  92238. if( pOrderBy ){
  92239. int n = pOrderBy->nExpr;
  92240. for(i=0; i<n; i++){
  92241. Expr *pExpr = pOrderBy->a[i].pExpr;
  92242. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  92243. }
  92244. if( i==n){
  92245. nOrderBy = n;
  92246. }
  92247. }
  92248. /* Allocate the sqlite3_index_info structure
  92249. */
  92250. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  92251. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  92252. + sizeof(*pIdxOrderBy)*nOrderBy );
  92253. if( pIdxInfo==0 ){
  92254. sqlite3ErrorMsg(pParse, "out of memory");
  92255. return 0;
  92256. }
  92257. /* Initialize the structure. The sqlite3_index_info structure contains
  92258. ** many fields that are declared "const" to prevent xBestIndex from
  92259. ** changing them. We have to do some funky casting in order to
  92260. ** initialize those fields.
  92261. */
  92262. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  92263. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  92264. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  92265. *(int*)&pIdxInfo->nConstraint = nTerm;
  92266. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  92267. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  92268. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  92269. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  92270. pUsage;
  92271. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  92272. u8 op;
  92273. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  92274. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  92275. testcase( pTerm->eOperator & WO_IN );
  92276. testcase( pTerm->eOperator & WO_ISNULL );
  92277. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  92278. if( pTerm->wtFlags & TERM_VNULL ) continue;
  92279. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  92280. pIdxCons[j].iTermOffset = i;
  92281. op = (u8)pTerm->eOperator & WO_ALL;
  92282. if( op==WO_IN ) op = WO_EQ;
  92283. pIdxCons[j].op = op;
  92284. /* The direct assignment in the previous line is possible only because
  92285. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  92286. ** following asserts verify this fact. */
  92287. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  92288. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  92289. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  92290. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  92291. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  92292. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  92293. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  92294. j++;
  92295. }
  92296. for(i=0; i<nOrderBy; i++){
  92297. Expr *pExpr = pOrderBy->a[i].pExpr;
  92298. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  92299. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  92300. }
  92301. return pIdxInfo;
  92302. }
  92303. /*
  92304. ** The table object reference passed as the second argument to this function
  92305. ** must represent a virtual table. This function invokes the xBestIndex()
  92306. ** method of the virtual table with the sqlite3_index_info object that
  92307. ** comes in as the 3rd argument to this function.
  92308. **
  92309. ** If an error occurs, pParse is populated with an error message and a
  92310. ** non-zero value is returned. Otherwise, 0 is returned and the output
  92311. ** part of the sqlite3_index_info structure is left populated.
  92312. **
  92313. ** Whether or not an error is returned, it is the responsibility of the
  92314. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  92315. ** that this is required.
  92316. */
  92317. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  92318. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  92319. int i;
  92320. int rc;
  92321. TRACE_IDX_INPUTS(p);
  92322. rc = pVtab->pModule->xBestIndex(pVtab, p);
  92323. TRACE_IDX_OUTPUTS(p);
  92324. if( rc!=SQLITE_OK ){
  92325. if( rc==SQLITE_NOMEM ){
  92326. pParse->db->mallocFailed = 1;
  92327. }else if( !pVtab->zErrMsg ){
  92328. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  92329. }else{
  92330. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  92331. }
  92332. }
  92333. sqlite3_free(pVtab->zErrMsg);
  92334. pVtab->zErrMsg = 0;
  92335. for(i=0; i<p->nConstraint; i++){
  92336. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  92337. sqlite3ErrorMsg(pParse,
  92338. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  92339. }
  92340. }
  92341. return pParse->nErr;
  92342. }
  92343. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  92344. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92345. /*
  92346. ** Estimate the location of a particular key among all keys in an
  92347. ** index. Store the results in aStat as follows:
  92348. **
  92349. ** aStat[0] Est. number of rows less than pVal
  92350. ** aStat[1] Est. number of rows equal to pVal
  92351. **
  92352. ** Return SQLITE_OK on success.
  92353. */
  92354. static void whereKeyStats(
  92355. Parse *pParse, /* Database connection */
  92356. Index *pIdx, /* Index to consider domain of */
  92357. UnpackedRecord *pRec, /* Vector of values to consider */
  92358. int roundUp, /* Round up if true. Round down if false */
  92359. tRowcnt *aStat /* OUT: stats written here */
  92360. ){
  92361. IndexSample *aSample = pIdx->aSample;
  92362. int iCol; /* Index of required stats in anEq[] etc. */
  92363. int iMin = 0; /* Smallest sample not yet tested */
  92364. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  92365. int iTest; /* Next sample to test */
  92366. int res; /* Result of comparison operation */
  92367. #ifndef SQLITE_DEBUG
  92368. UNUSED_PARAMETER( pParse );
  92369. #endif
  92370. assert( pRec!=0 || pParse->db->mallocFailed );
  92371. if( pRec==0 ) return;
  92372. iCol = pRec->nField - 1;
  92373. assert( pIdx->nSample>0 );
  92374. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  92375. do{
  92376. iTest = (iMin+i)/2;
  92377. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  92378. if( res<0 ){
  92379. iMin = iTest+1;
  92380. }else{
  92381. i = iTest;
  92382. }
  92383. }while( res && iMin<i );
  92384. #ifdef SQLITE_DEBUG
  92385. /* The following assert statements check that the binary search code
  92386. ** above found the right answer. This block serves no purpose other
  92387. ** than to invoke the asserts. */
  92388. if( res==0 ){
  92389. /* If (res==0) is true, then sample $i must be equal to pRec */
  92390. assert( i<pIdx->nSample );
  92391. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  92392. || pParse->db->mallocFailed );
  92393. }else{
  92394. /* Otherwise, pRec must be smaller than sample $i and larger than
  92395. ** sample ($i-1). */
  92396. assert( i==pIdx->nSample
  92397. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  92398. || pParse->db->mallocFailed );
  92399. assert( i==0
  92400. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  92401. || pParse->db->mallocFailed );
  92402. }
  92403. #endif /* ifdef SQLITE_DEBUG */
  92404. /* At this point, aSample[i] is the first sample that is greater than
  92405. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  92406. ** than pVal. If aSample[i]==pVal, then res==0.
  92407. */
  92408. if( res==0 ){
  92409. aStat[0] = aSample[i].anLt[iCol];
  92410. aStat[1] = aSample[i].anEq[iCol];
  92411. }else{
  92412. tRowcnt iLower, iUpper, iGap;
  92413. if( i==0 ){
  92414. iLower = 0;
  92415. iUpper = aSample[0].anLt[iCol];
  92416. }else{
  92417. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  92418. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  92419. }
  92420. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  92421. if( iLower>=iUpper ){
  92422. iGap = 0;
  92423. }else{
  92424. iGap = iUpper - iLower;
  92425. }
  92426. if( roundUp ){
  92427. iGap = (iGap*2)/3;
  92428. }else{
  92429. iGap = iGap/3;
  92430. }
  92431. aStat[0] = iLower + iGap;
  92432. }
  92433. }
  92434. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92435. /*
  92436. ** This function is used to estimate the number of rows that will be visited
  92437. ** by scanning an index for a range of values. The range may have an upper
  92438. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  92439. ** and lower bounds are represented by pLower and pUpper respectively. For
  92440. ** example, assuming that index p is on t1(a):
  92441. **
  92442. ** ... FROM t1 WHERE a > ? AND a < ? ...
  92443. ** |_____| |_____|
  92444. ** | |
  92445. ** pLower pUpper
  92446. **
  92447. ** If either of the upper or lower bound is not present, then NULL is passed in
  92448. ** place of the corresponding WhereTerm.
  92449. **
  92450. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  92451. ** column subject to the range constraint. Or, equivalently, the number of
  92452. ** equality constraints optimized by the proposed index scan. For example,
  92453. ** assuming index p is on t1(a, b), and the SQL query is:
  92454. **
  92455. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  92456. **
  92457. ** then nEq is set to 1 (as the range restricted column, b, is the second
  92458. ** left-most column of the index). Or, if the query is:
  92459. **
  92460. ** ... FROM t1 WHERE a > ? AND a < ? ...
  92461. **
  92462. ** then nEq is set to 0.
  92463. **
  92464. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  92465. ** number of rows that the index scan is expected to visit without
  92466. ** considering the range constraints. If nEq is 0, this is the number of
  92467. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  92468. ** to account for the range contraints pLower and pUpper.
  92469. **
  92470. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  92471. ** used, each range inequality reduces the search space by a factor of 4.
  92472. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  92473. ** rows visited by a factor of 16.
  92474. */
  92475. static int whereRangeScanEst(
  92476. Parse *pParse, /* Parsing & code generating context */
  92477. WhereLoopBuilder *pBuilder,
  92478. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  92479. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  92480. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  92481. ){
  92482. int rc = SQLITE_OK;
  92483. int nOut = pLoop->nOut;
  92484. LogEst nNew;
  92485. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92486. Index *p = pLoop->u.btree.pIndex;
  92487. int nEq = pLoop->u.btree.nEq;
  92488. if( p->nSample>0
  92489. && nEq==pBuilder->nRecValid
  92490. && nEq<p->nSampleCol
  92491. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  92492. ){
  92493. UnpackedRecord *pRec = pBuilder->pRec;
  92494. tRowcnt a[2];
  92495. u8 aff;
  92496. /* Variable iLower will be set to the estimate of the number of rows in
  92497. ** the index that are less than the lower bound of the range query. The
  92498. ** lower bound being the concatenation of $P and $L, where $P is the
  92499. ** key-prefix formed by the nEq values matched against the nEq left-most
  92500. ** columns of the index, and $L is the value in pLower.
  92501. **
  92502. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  92503. ** is not a simple variable or literal value), the lower bound of the
  92504. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  92505. ** if $L is available, whereKeyStats() is called for both ($P) and
  92506. ** ($P:$L) and the larger of the two returned values used.
  92507. **
  92508. ** Similarly, iUpper is to be set to the estimate of the number of rows
  92509. ** less than the upper bound of the range query. Where the upper bound
  92510. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  92511. ** of iUpper are requested of whereKeyStats() and the smaller used.
  92512. */
  92513. tRowcnt iLower;
  92514. tRowcnt iUpper;
  92515. if( nEq==p->nColumn ){
  92516. aff = SQLITE_AFF_INTEGER;
  92517. }else{
  92518. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  92519. }
  92520. /* Determine iLower and iUpper using ($P) only. */
  92521. if( nEq==0 ){
  92522. iLower = 0;
  92523. iUpper = p->aiRowEst[0];
  92524. }else{
  92525. /* Note: this call could be optimized away - since the same values must
  92526. ** have been requested when testing key $P in whereEqualScanEst(). */
  92527. whereKeyStats(pParse, p, pRec, 0, a);
  92528. iLower = a[0];
  92529. iUpper = a[0] + a[1];
  92530. }
  92531. /* If possible, improve on the iLower estimate using ($P:$L). */
  92532. if( pLower ){
  92533. int bOk; /* True if value is extracted from pExpr */
  92534. Expr *pExpr = pLower->pExpr->pRight;
  92535. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  92536. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  92537. if( rc==SQLITE_OK && bOk ){
  92538. tRowcnt iNew;
  92539. whereKeyStats(pParse, p, pRec, 0, a);
  92540. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  92541. if( iNew>iLower ) iLower = iNew;
  92542. nOut--;
  92543. }
  92544. }
  92545. /* If possible, improve on the iUpper estimate using ($P:$U). */
  92546. if( pUpper ){
  92547. int bOk; /* True if value is extracted from pExpr */
  92548. Expr *pExpr = pUpper->pExpr->pRight;
  92549. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  92550. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  92551. if( rc==SQLITE_OK && bOk ){
  92552. tRowcnt iNew;
  92553. whereKeyStats(pParse, p, pRec, 1, a);
  92554. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  92555. if( iNew<iUpper ) iUpper = iNew;
  92556. nOut--;
  92557. }
  92558. }
  92559. pBuilder->pRec = pRec;
  92560. if( rc==SQLITE_OK ){
  92561. if( iUpper>iLower ){
  92562. nNew = sqlite3LogEst(iUpper - iLower);
  92563. }else{
  92564. nNew = 10; assert( 10==sqlite3LogEst(2) );
  92565. }
  92566. if( nNew<nOut ){
  92567. nOut = nNew;
  92568. }
  92569. pLoop->nOut = (LogEst)nOut;
  92570. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  92571. (u32)iLower, (u32)iUpper, nOut));
  92572. return SQLITE_OK;
  92573. }
  92574. }
  92575. #else
  92576. UNUSED_PARAMETER(pParse);
  92577. UNUSED_PARAMETER(pBuilder);
  92578. #endif
  92579. assert( pLower || pUpper );
  92580. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  92581. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  92582. nNew = nOut;
  92583. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  92584. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  92585. nOut--;
  92586. }
  92587. if( pUpper ){
  92588. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  92589. nOut--;
  92590. }
  92591. if( nNew<10 ) nNew = 10;
  92592. if( nNew<nOut ) nOut = nNew;
  92593. pLoop->nOut = (LogEst)nOut;
  92594. return rc;
  92595. }
  92596. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92597. /*
  92598. ** Estimate the number of rows that will be returned based on
  92599. ** an equality constraint x=VALUE and where that VALUE occurs in
  92600. ** the histogram data. This only works when x is the left-most
  92601. ** column of an index and sqlite_stat3 histogram data is available
  92602. ** for that index. When pExpr==NULL that means the constraint is
  92603. ** "x IS NULL" instead of "x=VALUE".
  92604. **
  92605. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  92606. ** If unable to make an estimate, leave *pnRow unchanged and return
  92607. ** non-zero.
  92608. **
  92609. ** This routine can fail if it is unable to load a collating sequence
  92610. ** required for string comparison, or if unable to allocate memory
  92611. ** for a UTF conversion required for comparison. The error is stored
  92612. ** in the pParse structure.
  92613. */
  92614. static int whereEqualScanEst(
  92615. Parse *pParse, /* Parsing & code generating context */
  92616. WhereLoopBuilder *pBuilder,
  92617. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  92618. tRowcnt *pnRow /* Write the revised row estimate here */
  92619. ){
  92620. Index *p = pBuilder->pNew->u.btree.pIndex;
  92621. int nEq = pBuilder->pNew->u.btree.nEq;
  92622. UnpackedRecord *pRec = pBuilder->pRec;
  92623. u8 aff; /* Column affinity */
  92624. int rc; /* Subfunction return code */
  92625. tRowcnt a[2]; /* Statistics */
  92626. int bOk;
  92627. assert( nEq>=1 );
  92628. assert( nEq<=(p->nColumn+1) );
  92629. assert( p->aSample!=0 );
  92630. assert( p->nSample>0 );
  92631. assert( pBuilder->nRecValid<nEq );
  92632. /* If values are not available for all fields of the index to the left
  92633. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  92634. if( pBuilder->nRecValid<(nEq-1) ){
  92635. return SQLITE_NOTFOUND;
  92636. }
  92637. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  92638. ** below would return the same value. */
  92639. if( nEq>p->nColumn ){
  92640. *pnRow = 1;
  92641. return SQLITE_OK;
  92642. }
  92643. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  92644. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  92645. pBuilder->pRec = pRec;
  92646. if( rc!=SQLITE_OK ) return rc;
  92647. if( bOk==0 ) return SQLITE_NOTFOUND;
  92648. pBuilder->nRecValid = nEq;
  92649. whereKeyStats(pParse, p, pRec, 0, a);
  92650. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  92651. *pnRow = a[1];
  92652. return rc;
  92653. }
  92654. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92655. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92656. /*
  92657. ** Estimate the number of rows that will be returned based on
  92658. ** an IN constraint where the right-hand side of the IN operator
  92659. ** is a list of values. Example:
  92660. **
  92661. ** WHERE x IN (1,2,3,4)
  92662. **
  92663. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  92664. ** If unable to make an estimate, leave *pnRow unchanged and return
  92665. ** non-zero.
  92666. **
  92667. ** This routine can fail if it is unable to load a collating sequence
  92668. ** required for string comparison, or if unable to allocate memory
  92669. ** for a UTF conversion required for comparison. The error is stored
  92670. ** in the pParse structure.
  92671. */
  92672. static int whereInScanEst(
  92673. Parse *pParse, /* Parsing & code generating context */
  92674. WhereLoopBuilder *pBuilder,
  92675. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  92676. tRowcnt *pnRow /* Write the revised row estimate here */
  92677. ){
  92678. Index *p = pBuilder->pNew->u.btree.pIndex;
  92679. int nRecValid = pBuilder->nRecValid;
  92680. int rc = SQLITE_OK; /* Subfunction return code */
  92681. tRowcnt nEst; /* Number of rows for a single term */
  92682. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  92683. int i; /* Loop counter */
  92684. assert( p->aSample!=0 );
  92685. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  92686. nEst = p->aiRowEst[0];
  92687. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  92688. nRowEst += nEst;
  92689. pBuilder->nRecValid = nRecValid;
  92690. }
  92691. if( rc==SQLITE_OK ){
  92692. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  92693. *pnRow = nRowEst;
  92694. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  92695. }
  92696. assert( pBuilder->nRecValid==nRecValid );
  92697. return rc;
  92698. }
  92699. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92700. /*
  92701. ** Disable a term in the WHERE clause. Except, do not disable the term
  92702. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  92703. ** or USING clause of that join.
  92704. **
  92705. ** Consider the term t2.z='ok' in the following queries:
  92706. **
  92707. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  92708. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  92709. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  92710. **
  92711. ** The t2.z='ok' is disabled in the in (2) because it originates
  92712. ** in the ON clause. The term is disabled in (3) because it is not part
  92713. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  92714. **
  92715. ** Disabling a term causes that term to not be tested in the inner loop
  92716. ** of the join. Disabling is an optimization. When terms are satisfied
  92717. ** by indices, we disable them to prevent redundant tests in the inner
  92718. ** loop. We would get the correct results if nothing were ever disabled,
  92719. ** but joins might run a little slower. The trick is to disable as much
  92720. ** as we can without disabling too much. If we disabled in (1), we'd get
  92721. ** the wrong answer. See ticket #813.
  92722. */
  92723. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  92724. if( pTerm
  92725. && (pTerm->wtFlags & TERM_CODED)==0
  92726. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  92727. && (pLevel->notReady & pTerm->prereqAll)==0
  92728. ){
  92729. pTerm->wtFlags |= TERM_CODED;
  92730. if( pTerm->iParent>=0 ){
  92731. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  92732. if( (--pOther->nChild)==0 ){
  92733. disableTerm(pLevel, pOther);
  92734. }
  92735. }
  92736. }
  92737. }
  92738. /*
  92739. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  92740. ** to the n registers starting at base.
  92741. **
  92742. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  92743. ** beginning and end of zAff are ignored. If all entries in zAff are
  92744. ** SQLITE_AFF_NONE, then no code gets generated.
  92745. **
  92746. ** This routine makes its own copy of zAff so that the caller is free
  92747. ** to modify zAff after this routine returns.
  92748. */
  92749. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  92750. Vdbe *v = pParse->pVdbe;
  92751. if( zAff==0 ){
  92752. assert( pParse->db->mallocFailed );
  92753. return;
  92754. }
  92755. assert( v!=0 );
  92756. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  92757. ** and end of the affinity string.
  92758. */
  92759. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  92760. n--;
  92761. base++;
  92762. zAff++;
  92763. }
  92764. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  92765. n--;
  92766. }
  92767. /* Code the OP_Affinity opcode if there is anything left to do. */
  92768. if( n>0 ){
  92769. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  92770. sqlite3VdbeChangeP4(v, -1, zAff, n);
  92771. sqlite3ExprCacheAffinityChange(pParse, base, n);
  92772. }
  92773. }
  92774. /*
  92775. ** Generate code for a single equality term of the WHERE clause. An equality
  92776. ** term can be either X=expr or X IN (...). pTerm is the term to be
  92777. ** coded.
  92778. **
  92779. ** The current value for the constraint is left in register iReg.
  92780. **
  92781. ** For a constraint of the form X=expr, the expression is evaluated and its
  92782. ** result is left on the stack. For constraints of the form X IN (...)
  92783. ** this routine sets up a loop that will iterate over all values of X.
  92784. */
  92785. static int codeEqualityTerm(
  92786. Parse *pParse, /* The parsing context */
  92787. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  92788. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  92789. int iEq, /* Index of the equality term within this level */
  92790. int bRev, /* True for reverse-order IN operations */
  92791. int iTarget /* Attempt to leave results in this register */
  92792. ){
  92793. Expr *pX = pTerm->pExpr;
  92794. Vdbe *v = pParse->pVdbe;
  92795. int iReg; /* Register holding results */
  92796. assert( iTarget>0 );
  92797. if( pX->op==TK_EQ ){
  92798. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  92799. }else if( pX->op==TK_ISNULL ){
  92800. iReg = iTarget;
  92801. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  92802. #ifndef SQLITE_OMIT_SUBQUERY
  92803. }else{
  92804. int eType;
  92805. int iTab;
  92806. struct InLoop *pIn;
  92807. WhereLoop *pLoop = pLevel->pWLoop;
  92808. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  92809. && pLoop->u.btree.pIndex!=0
  92810. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  92811. ){
  92812. testcase( iEq==0 );
  92813. testcase( bRev );
  92814. bRev = !bRev;
  92815. }
  92816. assert( pX->op==TK_IN );
  92817. iReg = iTarget;
  92818. eType = sqlite3FindInIndex(pParse, pX, 0);
  92819. if( eType==IN_INDEX_INDEX_DESC ){
  92820. testcase( bRev );
  92821. bRev = !bRev;
  92822. }
  92823. iTab = pX->iTable;
  92824. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  92825. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  92826. pLoop->wsFlags |= WHERE_IN_ABLE;
  92827. if( pLevel->u.in.nIn==0 ){
  92828. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  92829. }
  92830. pLevel->u.in.nIn++;
  92831. pLevel->u.in.aInLoop =
  92832. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  92833. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  92834. pIn = pLevel->u.in.aInLoop;
  92835. if( pIn ){
  92836. pIn += pLevel->u.in.nIn - 1;
  92837. pIn->iCur = iTab;
  92838. if( eType==IN_INDEX_ROWID ){
  92839. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  92840. }else{
  92841. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  92842. }
  92843. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  92844. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  92845. }else{
  92846. pLevel->u.in.nIn = 0;
  92847. }
  92848. #endif
  92849. }
  92850. disableTerm(pLevel, pTerm);
  92851. return iReg;
  92852. }
  92853. /*
  92854. ** Generate code that will evaluate all == and IN constraints for an
  92855. ** index.
  92856. **
  92857. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  92858. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  92859. ** The index has as many as three equality constraints, but in this
  92860. ** example, the third "c" value is an inequality. So only two
  92861. ** constraints are coded. This routine will generate code to evaluate
  92862. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  92863. ** in consecutive registers and the index of the first register is returned.
  92864. **
  92865. ** In the example above nEq==2. But this subroutine works for any value
  92866. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  92867. ** The only thing it does is allocate the pLevel->iMem memory cell and
  92868. ** compute the affinity string.
  92869. **
  92870. ** This routine always allocates at least one memory cell and returns
  92871. ** the index of that memory cell. The code that
  92872. ** calls this routine will use that memory cell to store the termination
  92873. ** key value of the loop. If one or more IN operators appear, then
  92874. ** this routine allocates an additional nEq memory cells for internal
  92875. ** use.
  92876. **
  92877. ** Before returning, *pzAff is set to point to a buffer containing a
  92878. ** copy of the column affinity string of the index allocated using
  92879. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  92880. ** with equality constraints that use NONE affinity are set to
  92881. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  92882. **
  92883. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  92884. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  92885. **
  92886. ** In the example above, the index on t1(a) has TEXT affinity. But since
  92887. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  92888. ** no conversion should be attempted before using a t2.b value as part of
  92889. ** a key to search the index. Hence the first byte in the returned affinity
  92890. ** string in this example would be set to SQLITE_AFF_NONE.
  92891. */
  92892. static int codeAllEqualityTerms(
  92893. Parse *pParse, /* Parsing context */
  92894. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  92895. int bRev, /* Reverse the order of IN operators */
  92896. int nExtraReg, /* Number of extra registers to allocate */
  92897. char **pzAff /* OUT: Set to point to affinity string */
  92898. ){
  92899. int nEq; /* The number of == or IN constraints to code */
  92900. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  92901. Index *pIdx; /* The index being used for this loop */
  92902. WhereTerm *pTerm; /* A single constraint term */
  92903. WhereLoop *pLoop; /* The WhereLoop object */
  92904. int j; /* Loop counter */
  92905. int regBase; /* Base register */
  92906. int nReg; /* Number of registers to allocate */
  92907. char *zAff; /* Affinity string to return */
  92908. /* This module is only called on query plans that use an index. */
  92909. pLoop = pLevel->pWLoop;
  92910. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  92911. nEq = pLoop->u.btree.nEq;
  92912. pIdx = pLoop->u.btree.pIndex;
  92913. assert( pIdx!=0 );
  92914. /* Figure out how many memory cells we will need then allocate them.
  92915. */
  92916. regBase = pParse->nMem + 1;
  92917. nReg = pLoop->u.btree.nEq + nExtraReg;
  92918. pParse->nMem += nReg;
  92919. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  92920. if( !zAff ){
  92921. pParse->db->mallocFailed = 1;
  92922. }
  92923. /* Evaluate the equality constraints
  92924. */
  92925. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  92926. for(j=0; j<nEq; j++){
  92927. int r1;
  92928. pTerm = pLoop->aLTerm[j];
  92929. assert( pTerm!=0 );
  92930. /* The following true for indices with redundant columns.
  92931. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  92932. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  92933. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  92934. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  92935. if( r1!=regBase+j ){
  92936. if( nReg==1 ){
  92937. sqlite3ReleaseTempReg(pParse, regBase);
  92938. regBase = r1;
  92939. }else{
  92940. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  92941. }
  92942. }
  92943. testcase( pTerm->eOperator & WO_ISNULL );
  92944. testcase( pTerm->eOperator & WO_IN );
  92945. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  92946. Expr *pRight = pTerm->pExpr->pRight;
  92947. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  92948. if( zAff ){
  92949. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  92950. zAff[j] = SQLITE_AFF_NONE;
  92951. }
  92952. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  92953. zAff[j] = SQLITE_AFF_NONE;
  92954. }
  92955. }
  92956. }
  92957. }
  92958. *pzAff = zAff;
  92959. return regBase;
  92960. }
  92961. #ifndef SQLITE_OMIT_EXPLAIN
  92962. /*
  92963. ** This routine is a helper for explainIndexRange() below
  92964. **
  92965. ** pStr holds the text of an expression that we are building up one term
  92966. ** at a time. This routine adds a new term to the end of the expression.
  92967. ** Terms are separated by AND so add the "AND" text for second and subsequent
  92968. ** terms only.
  92969. */
  92970. static void explainAppendTerm(
  92971. StrAccum *pStr, /* The text expression being built */
  92972. int iTerm, /* Index of this term. First is zero */
  92973. const char *zColumn, /* Name of the column */
  92974. const char *zOp /* Name of the operator */
  92975. ){
  92976. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  92977. sqlite3StrAccumAppend(pStr, zColumn, -1);
  92978. sqlite3StrAccumAppend(pStr, zOp, 1);
  92979. sqlite3StrAccumAppend(pStr, "?", 1);
  92980. }
  92981. /*
  92982. ** Argument pLevel describes a strategy for scanning table pTab. This
  92983. ** function returns a pointer to a string buffer containing a description
  92984. ** of the subset of table rows scanned by the strategy in the form of an
  92985. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  92986. **
  92987. ** For example, if the query:
  92988. **
  92989. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  92990. **
  92991. ** is run and there is an index on (a, b), then this function returns a
  92992. ** string similar to:
  92993. **
  92994. ** "a=? AND b>?"
  92995. **
  92996. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  92997. ** It is the responsibility of the caller to free the buffer when it is
  92998. ** no longer required.
  92999. */
  93000. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  93001. Index *pIndex = pLoop->u.btree.pIndex;
  93002. int nEq = pLoop->u.btree.nEq;
  93003. int i, j;
  93004. Column *aCol = pTab->aCol;
  93005. int *aiColumn = pIndex->aiColumn;
  93006. StrAccum txt;
  93007. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  93008. return 0;
  93009. }
  93010. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  93011. txt.db = db;
  93012. sqlite3StrAccumAppend(&txt, " (", 2);
  93013. for(i=0; i<nEq; i++){
  93014. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  93015. explainAppendTerm(&txt, i, z, "=");
  93016. }
  93017. j = i;
  93018. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  93019. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  93020. explainAppendTerm(&txt, i++, z, ">");
  93021. }
  93022. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  93023. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  93024. explainAppendTerm(&txt, i, z, "<");
  93025. }
  93026. sqlite3StrAccumAppend(&txt, ")", 1);
  93027. return sqlite3StrAccumFinish(&txt);
  93028. }
  93029. /*
  93030. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  93031. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  93032. ** record is added to the output to describe the table scan strategy in
  93033. ** pLevel.
  93034. */
  93035. static void explainOneScan(
  93036. Parse *pParse, /* Parse context */
  93037. SrcList *pTabList, /* Table list this loop refers to */
  93038. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  93039. int iLevel, /* Value for "level" column of output */
  93040. int iFrom, /* Value for "from" column of output */
  93041. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  93042. ){
  93043. if( pParse->explain==2 ){
  93044. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  93045. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  93046. sqlite3 *db = pParse->db; /* Database handle */
  93047. char *zMsg; /* Text to add to EQP output */
  93048. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  93049. int isSearch; /* True for a SEARCH. False for SCAN. */
  93050. WhereLoop *pLoop; /* The controlling WhereLoop object */
  93051. u32 flags; /* Flags that describe this loop */
  93052. pLoop = pLevel->pWLoop;
  93053. flags = pLoop->wsFlags;
  93054. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  93055. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  93056. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  93057. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  93058. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  93059. if( pItem->pSelect ){
  93060. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  93061. }else{
  93062. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  93063. }
  93064. if( pItem->zAlias ){
  93065. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  93066. }
  93067. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  93068. && ALWAYS(pLoop->u.btree.pIndex!=0)
  93069. ){
  93070. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  93071. zMsg = sqlite3MAppendf(db, zMsg,
  93072. ((flags & WHERE_AUTO_INDEX) ?
  93073. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  93074. "%s USING %sINDEX %s%s"),
  93075. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  93076. pLoop->u.btree.pIndex->zName, zWhere);
  93077. sqlite3DbFree(db, zWhere);
  93078. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  93079. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  93080. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  93081. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  93082. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  93083. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  93084. }else if( flags&WHERE_BTM_LIMIT ){
  93085. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  93086. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  93087. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  93088. }
  93089. }
  93090. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93091. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  93092. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  93093. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  93094. }
  93095. #endif
  93096. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  93097. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  93098. }
  93099. }
  93100. #else
  93101. # define explainOneScan(u,v,w,x,y,z)
  93102. #endif /* SQLITE_OMIT_EXPLAIN */
  93103. /*
  93104. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  93105. ** implementation described by pWInfo.
  93106. */
  93107. static Bitmask codeOneLoopStart(
  93108. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  93109. int iLevel, /* Which level of pWInfo->a[] should be coded */
  93110. Bitmask notReady /* Which tables are currently available */
  93111. ){
  93112. int j, k; /* Loop counters */
  93113. int iCur; /* The VDBE cursor for the table */
  93114. int addrNxt; /* Where to jump to continue with the next IN case */
  93115. int omitTable; /* True if we use the index only */
  93116. int bRev; /* True if we need to scan in reverse order */
  93117. WhereLevel *pLevel; /* The where level to be coded */
  93118. WhereLoop *pLoop; /* The WhereLoop object being coded */
  93119. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  93120. WhereTerm *pTerm; /* A WHERE clause term */
  93121. Parse *pParse; /* Parsing context */
  93122. sqlite3 *db; /* Database connection */
  93123. Vdbe *v; /* The prepared stmt under constructions */
  93124. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  93125. int addrBrk; /* Jump here to break out of the loop */
  93126. int addrCont; /* Jump here to continue with next cycle */
  93127. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  93128. int iReleaseReg = 0; /* Temp register to free before returning */
  93129. pParse = pWInfo->pParse;
  93130. v = pParse->pVdbe;
  93131. pWC = &pWInfo->sWC;
  93132. db = pParse->db;
  93133. pLevel = &pWInfo->a[iLevel];
  93134. pLoop = pLevel->pWLoop;
  93135. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  93136. iCur = pTabItem->iCursor;
  93137. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  93138. bRev = (pWInfo->revMask>>iLevel)&1;
  93139. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  93140. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  93141. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  93142. /* Create labels for the "break" and "continue" instructions
  93143. ** for the current loop. Jump to addrBrk to break out of a loop.
  93144. ** Jump to cont to go immediately to the next iteration of the
  93145. ** loop.
  93146. **
  93147. ** When there is an IN operator, we also have a "addrNxt" label that
  93148. ** means to continue with the next IN value combination. When
  93149. ** there are no IN operators in the constraints, the "addrNxt" label
  93150. ** is the same as "addrBrk".
  93151. */
  93152. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  93153. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  93154. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  93155. ** initialize a memory cell that records if this table matches any
  93156. ** row of the left table of the join.
  93157. */
  93158. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  93159. pLevel->iLeftJoin = ++pParse->nMem;
  93160. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  93161. VdbeComment((v, "init LEFT JOIN no-match flag"));
  93162. }
  93163. /* Special case of a FROM clause subquery implemented as a co-routine */
  93164. if( pTabItem->viaCoroutine ){
  93165. int regYield = pTabItem->regReturn;
  93166. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  93167. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  93168. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  93169. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  93170. pLevel->op = OP_Goto;
  93171. }else
  93172. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93173. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  93174. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  93175. ** to access the data.
  93176. */
  93177. int iReg; /* P3 Value for OP_VFilter */
  93178. int addrNotFound;
  93179. int nConstraint = pLoop->nLTerm;
  93180. sqlite3ExprCachePush(pParse);
  93181. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  93182. addrNotFound = pLevel->addrBrk;
  93183. for(j=0; j<nConstraint; j++){
  93184. int iTarget = iReg+j+2;
  93185. pTerm = pLoop->aLTerm[j];
  93186. if( pTerm==0 ) continue;
  93187. if( pTerm->eOperator & WO_IN ){
  93188. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  93189. addrNotFound = pLevel->addrNxt;
  93190. }else{
  93191. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  93192. }
  93193. }
  93194. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  93195. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  93196. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  93197. pLoop->u.vtab.idxStr,
  93198. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  93199. pLoop->u.vtab.needFree = 0;
  93200. for(j=0; j<nConstraint && j<16; j++){
  93201. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  93202. disableTerm(pLevel, pLoop->aLTerm[j]);
  93203. }
  93204. }
  93205. pLevel->op = OP_VNext;
  93206. pLevel->p1 = iCur;
  93207. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  93208. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  93209. sqlite3ExprCachePop(pParse, 1);
  93210. }else
  93211. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  93212. if( (pLoop->wsFlags & WHERE_IPK)!=0
  93213. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  93214. ){
  93215. /* Case 2: We can directly reference a single row using an
  93216. ** equality comparison against the ROWID field. Or
  93217. ** we reference multiple rows using a "rowid IN (...)"
  93218. ** construct.
  93219. */
  93220. assert( pLoop->u.btree.nEq==1 );
  93221. iReleaseReg = sqlite3GetTempReg(pParse);
  93222. pTerm = pLoop->aLTerm[0];
  93223. assert( pTerm!=0 );
  93224. assert( pTerm->pExpr!=0 );
  93225. assert( omitTable==0 );
  93226. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93227. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  93228. addrNxt = pLevel->addrNxt;
  93229. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  93230. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  93231. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  93232. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93233. VdbeComment((v, "pk"));
  93234. pLevel->op = OP_Noop;
  93235. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  93236. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  93237. ){
  93238. /* Case 3: We have an inequality comparison against the ROWID field.
  93239. */
  93240. int testOp = OP_Noop;
  93241. int start;
  93242. int memEndValue = 0;
  93243. WhereTerm *pStart, *pEnd;
  93244. assert( omitTable==0 );
  93245. j = 0;
  93246. pStart = pEnd = 0;
  93247. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  93248. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  93249. assert( pStart!=0 || pEnd!=0 );
  93250. if( bRev ){
  93251. pTerm = pStart;
  93252. pStart = pEnd;
  93253. pEnd = pTerm;
  93254. }
  93255. if( pStart ){
  93256. Expr *pX; /* The expression that defines the start bound */
  93257. int r1, rTemp; /* Registers for holding the start boundary */
  93258. /* The following constant maps TK_xx codes into corresponding
  93259. ** seek opcodes. It depends on a particular ordering of TK_xx
  93260. */
  93261. const u8 aMoveOp[] = {
  93262. /* TK_GT */ OP_SeekGt,
  93263. /* TK_LE */ OP_SeekLe,
  93264. /* TK_LT */ OP_SeekLt,
  93265. /* TK_GE */ OP_SeekGe
  93266. };
  93267. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  93268. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  93269. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  93270. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  93271. testcase( pStart->wtFlags & TERM_VIRTUAL );
  93272. pX = pStart->pExpr;
  93273. assert( pX!=0 );
  93274. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  93275. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  93276. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  93277. VdbeComment((v, "pk"));
  93278. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  93279. sqlite3ReleaseTempReg(pParse, rTemp);
  93280. disableTerm(pLevel, pStart);
  93281. }else{
  93282. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  93283. }
  93284. if( pEnd ){
  93285. Expr *pX;
  93286. pX = pEnd->pExpr;
  93287. assert( pX!=0 );
  93288. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  93289. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  93290. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  93291. memEndValue = ++pParse->nMem;
  93292. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  93293. if( pX->op==TK_LT || pX->op==TK_GT ){
  93294. testOp = bRev ? OP_Le : OP_Ge;
  93295. }else{
  93296. testOp = bRev ? OP_Lt : OP_Gt;
  93297. }
  93298. disableTerm(pLevel, pEnd);
  93299. }
  93300. start = sqlite3VdbeCurrentAddr(v);
  93301. pLevel->op = bRev ? OP_Prev : OP_Next;
  93302. pLevel->p1 = iCur;
  93303. pLevel->p2 = start;
  93304. assert( pLevel->p5==0 );
  93305. if( testOp!=OP_Noop ){
  93306. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  93307. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  93308. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93309. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  93310. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  93311. }
  93312. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  93313. /* Case 4: A scan using an index.
  93314. **
  93315. ** The WHERE clause may contain zero or more equality
  93316. ** terms ("==" or "IN" operators) that refer to the N
  93317. ** left-most columns of the index. It may also contain
  93318. ** inequality constraints (>, <, >= or <=) on the indexed
  93319. ** column that immediately follows the N equalities. Only
  93320. ** the right-most column can be an inequality - the rest must
  93321. ** use the "==" and "IN" operators. For example, if the
  93322. ** index is on (x,y,z), then the following clauses are all
  93323. ** optimized:
  93324. **
  93325. ** x=5
  93326. ** x=5 AND y=10
  93327. ** x=5 AND y<10
  93328. ** x=5 AND y>5 AND y<10
  93329. ** x=5 AND y=5 AND z<=10
  93330. **
  93331. ** The z<10 term of the following cannot be used, only
  93332. ** the x=5 term:
  93333. **
  93334. ** x=5 AND z<10
  93335. **
  93336. ** N may be zero if there are inequality constraints.
  93337. ** If there are no inequality constraints, then N is at
  93338. ** least one.
  93339. **
  93340. ** This case is also used when there are no WHERE clause
  93341. ** constraints but an index is selected anyway, in order
  93342. ** to force the output order to conform to an ORDER BY.
  93343. */
  93344. static const u8 aStartOp[] = {
  93345. 0,
  93346. 0,
  93347. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  93348. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  93349. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  93350. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  93351. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  93352. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  93353. };
  93354. static const u8 aEndOp[] = {
  93355. OP_Noop, /* 0: (!end_constraints) */
  93356. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  93357. OP_IdxLT /* 2: (end_constraints && bRev) */
  93358. };
  93359. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  93360. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  93361. int regBase; /* Base register holding constraint values */
  93362. int r1; /* Temp register */
  93363. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  93364. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  93365. int startEq; /* True if range start uses ==, >= or <= */
  93366. int endEq; /* True if range end uses ==, >= or <= */
  93367. int start_constraints; /* Start of range is constrained */
  93368. int nConstraint; /* Number of constraint terms */
  93369. Index *pIdx; /* The index we will be using */
  93370. int iIdxCur; /* The VDBE cursor for the index */
  93371. int nExtraReg = 0; /* Number of extra registers needed */
  93372. int op; /* Instruction opcode */
  93373. char *zStartAff; /* Affinity for start of range constraint */
  93374. char *zEndAff; /* Affinity for end of range constraint */
  93375. pIdx = pLoop->u.btree.pIndex;
  93376. iIdxCur = pLevel->iIdxCur;
  93377. /* If this loop satisfies a sort order (pOrderBy) request that
  93378. ** was passed to this function to implement a "SELECT min(x) ..."
  93379. ** query, then the caller will only allow the loop to run for
  93380. ** a single iteration. This means that the first row returned
  93381. ** should not have a NULL value stored in 'x'. If column 'x' is
  93382. ** the first one after the nEq equality constraints in the index,
  93383. ** this requires some special handling.
  93384. */
  93385. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  93386. && (pWInfo->bOBSat!=0)
  93387. && (pIdx->nColumn>nEq)
  93388. ){
  93389. /* assert( pOrderBy->nExpr==1 ); */
  93390. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  93391. isMinQuery = 1;
  93392. nExtraReg = 1;
  93393. }
  93394. /* Find any inequality constraint terms for the start and end
  93395. ** of the range.
  93396. */
  93397. j = nEq;
  93398. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  93399. pRangeStart = pLoop->aLTerm[j++];
  93400. nExtraReg = 1;
  93401. }
  93402. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  93403. pRangeEnd = pLoop->aLTerm[j++];
  93404. nExtraReg = 1;
  93405. }
  93406. /* Generate code to evaluate all constraint terms using == or IN
  93407. ** and store the values of those terms in an array of registers
  93408. ** starting at regBase.
  93409. */
  93410. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  93411. zEndAff = sqlite3DbStrDup(db, zStartAff);
  93412. addrNxt = pLevel->addrNxt;
  93413. /* If we are doing a reverse order scan on an ascending index, or
  93414. ** a forward order scan on a descending index, interchange the
  93415. ** start and end terms (pRangeStart and pRangeEnd).
  93416. */
  93417. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  93418. || (bRev && pIdx->nColumn==nEq)
  93419. ){
  93420. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  93421. }
  93422. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  93423. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  93424. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  93425. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  93426. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  93427. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  93428. start_constraints = pRangeStart || nEq>0;
  93429. /* Seek the index cursor to the start of the range. */
  93430. nConstraint = nEq;
  93431. if( pRangeStart ){
  93432. Expr *pRight = pRangeStart->pExpr->pRight;
  93433. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  93434. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  93435. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  93436. }
  93437. if( zStartAff ){
  93438. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  93439. /* Since the comparison is to be performed with no conversions
  93440. ** applied to the operands, set the affinity to apply to pRight to
  93441. ** SQLITE_AFF_NONE. */
  93442. zStartAff[nEq] = SQLITE_AFF_NONE;
  93443. }
  93444. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  93445. zStartAff[nEq] = SQLITE_AFF_NONE;
  93446. }
  93447. }
  93448. nConstraint++;
  93449. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  93450. }else if( isMinQuery ){
  93451. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  93452. nConstraint++;
  93453. startEq = 0;
  93454. start_constraints = 1;
  93455. }
  93456. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  93457. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  93458. assert( op!=0 );
  93459. testcase( op==OP_Rewind );
  93460. testcase( op==OP_Last );
  93461. testcase( op==OP_SeekGt );
  93462. testcase( op==OP_SeekGe );
  93463. testcase( op==OP_SeekLe );
  93464. testcase( op==OP_SeekLt );
  93465. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  93466. /* Load the value for the inequality constraint at the end of the
  93467. ** range (if any).
  93468. */
  93469. nConstraint = nEq;
  93470. if( pRangeEnd ){
  93471. Expr *pRight = pRangeEnd->pExpr->pRight;
  93472. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  93473. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  93474. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  93475. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  93476. }
  93477. if( zEndAff ){
  93478. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  93479. /* Since the comparison is to be performed with no conversions
  93480. ** applied to the operands, set the affinity to apply to pRight to
  93481. ** SQLITE_AFF_NONE. */
  93482. zEndAff[nEq] = SQLITE_AFF_NONE;
  93483. }
  93484. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  93485. zEndAff[nEq] = SQLITE_AFF_NONE;
  93486. }
  93487. }
  93488. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  93489. nConstraint++;
  93490. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  93491. }
  93492. sqlite3DbFree(db, zStartAff);
  93493. sqlite3DbFree(db, zEndAff);
  93494. /* Top of the loop body */
  93495. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  93496. /* Check if the index cursor is past the end of the range. */
  93497. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  93498. testcase( op==OP_Noop );
  93499. testcase( op==OP_IdxGE );
  93500. testcase( op==OP_IdxLT );
  93501. if( op!=OP_Noop ){
  93502. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  93503. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  93504. }
  93505. /* If there are inequality constraints, check that the value
  93506. ** of the table column that the inequality contrains is not NULL.
  93507. ** If it is, jump to the next iteration of the loop.
  93508. */
  93509. r1 = sqlite3GetTempReg(pParse);
  93510. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  93511. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  93512. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  93513. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  93514. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  93515. }
  93516. sqlite3ReleaseTempReg(pParse, r1);
  93517. /* Seek the table cursor, if required */
  93518. disableTerm(pLevel, pRangeStart);
  93519. disableTerm(pLevel, pRangeEnd);
  93520. if( !omitTable ){
  93521. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  93522. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  93523. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93524. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  93525. }
  93526. /* Record the instruction used to terminate the loop. Disable
  93527. ** WHERE clause terms made redundant by the index range scan.
  93528. */
  93529. if( pLoop->wsFlags & WHERE_ONEROW ){
  93530. pLevel->op = OP_Noop;
  93531. }else if( bRev ){
  93532. pLevel->op = OP_Prev;
  93533. }else{
  93534. pLevel->op = OP_Next;
  93535. }
  93536. pLevel->p1 = iIdxCur;
  93537. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  93538. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  93539. }else{
  93540. assert( pLevel->p5==0 );
  93541. }
  93542. }else
  93543. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  93544. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  93545. /* Case 5: Two or more separately indexed terms connected by OR
  93546. **
  93547. ** Example:
  93548. **
  93549. ** CREATE TABLE t1(a,b,c,d);
  93550. ** CREATE INDEX i1 ON t1(a);
  93551. ** CREATE INDEX i2 ON t1(b);
  93552. ** CREATE INDEX i3 ON t1(c);
  93553. **
  93554. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  93555. **
  93556. ** In the example, there are three indexed terms connected by OR.
  93557. ** The top of the loop looks like this:
  93558. **
  93559. ** Null 1 # Zero the rowset in reg 1
  93560. **
  93561. ** Then, for each indexed term, the following. The arguments to
  93562. ** RowSetTest are such that the rowid of the current row is inserted
  93563. ** into the RowSet. If it is already present, control skips the
  93564. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  93565. **
  93566. ** sqlite3WhereBegin(<term>)
  93567. ** RowSetTest # Insert rowid into rowset
  93568. ** Gosub 2 A
  93569. ** sqlite3WhereEnd()
  93570. **
  93571. ** Following the above, code to terminate the loop. Label A, the target
  93572. ** of the Gosub above, jumps to the instruction right after the Goto.
  93573. **
  93574. ** Null 1 # Zero the rowset in reg 1
  93575. ** Goto B # The loop is finished.
  93576. **
  93577. ** A: <loop body> # Return data, whatever.
  93578. **
  93579. ** Return 2 # Jump back to the Gosub
  93580. **
  93581. ** B: <after the loop>
  93582. **
  93583. */
  93584. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  93585. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  93586. Index *pCov = 0; /* Potential covering index (or NULL) */
  93587. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  93588. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  93589. int regRowset = 0; /* Register for RowSet object */
  93590. int regRowid = 0; /* Register holding rowid */
  93591. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  93592. int iRetInit; /* Address of regReturn init */
  93593. int untestedTerms = 0; /* Some terms not completely tested */
  93594. int ii; /* Loop counter */
  93595. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  93596. pTerm = pLoop->aLTerm[0];
  93597. assert( pTerm!=0 );
  93598. assert( pTerm->eOperator & WO_OR );
  93599. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  93600. pOrWc = &pTerm->u.pOrInfo->wc;
  93601. pLevel->op = OP_Return;
  93602. pLevel->p1 = regReturn;
  93603. /* Set up a new SrcList in pOrTab containing the table being scanned
  93604. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  93605. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  93606. */
  93607. if( pWInfo->nLevel>1 ){
  93608. int nNotReady; /* The number of notReady tables */
  93609. struct SrcList_item *origSrc; /* Original list of tables */
  93610. nNotReady = pWInfo->nLevel - iLevel - 1;
  93611. pOrTab = sqlite3StackAllocRaw(db,
  93612. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  93613. if( pOrTab==0 ) return notReady;
  93614. pOrTab->nAlloc = (u8)(nNotReady + 1);
  93615. pOrTab->nSrc = pOrTab->nAlloc;
  93616. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  93617. origSrc = pWInfo->pTabList->a;
  93618. for(k=1; k<=nNotReady; k++){
  93619. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  93620. }
  93621. }else{
  93622. pOrTab = pWInfo->pTabList;
  93623. }
  93624. /* Initialize the rowset register to contain NULL. An SQL NULL is
  93625. ** equivalent to an empty rowset.
  93626. **
  93627. ** Also initialize regReturn to contain the address of the instruction
  93628. ** immediately following the OP_Return at the bottom of the loop. This
  93629. ** is required in a few obscure LEFT JOIN cases where control jumps
  93630. ** over the top of the loop into the body of it. In this case the
  93631. ** correct response for the end-of-loop code (the OP_Return) is to
  93632. ** fall through to the next instruction, just as an OP_Next does if
  93633. ** called on an uninitialized cursor.
  93634. */
  93635. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  93636. regRowset = ++pParse->nMem;
  93637. regRowid = ++pParse->nMem;
  93638. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  93639. }
  93640. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  93641. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  93642. ** Then for every term xN, evaluate as the subexpression: xN AND z
  93643. ** That way, terms in y that are factored into the disjunction will
  93644. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  93645. **
  93646. ** Actually, each subexpression is converted to "xN AND w" where w is
  93647. ** the "interesting" terms of z - terms that did not originate in the
  93648. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  93649. ** indices.
  93650. **
  93651. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  93652. ** is not contained in the ON clause of a LEFT JOIN.
  93653. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  93654. */
  93655. if( pWC->nTerm>1 ){
  93656. int iTerm;
  93657. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  93658. Expr *pExpr = pWC->a[iTerm].pExpr;
  93659. if( &pWC->a[iTerm] == pTerm ) continue;
  93660. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  93661. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  93662. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  93663. pExpr = sqlite3ExprDup(db, pExpr, 0);
  93664. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  93665. }
  93666. if( pAndExpr ){
  93667. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  93668. }
  93669. }
  93670. for(ii=0; ii<pOrWc->nTerm; ii++){
  93671. WhereTerm *pOrTerm = &pOrWc->a[ii];
  93672. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  93673. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  93674. Expr *pOrExpr = pOrTerm->pExpr;
  93675. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  93676. pAndExpr->pLeft = pOrExpr;
  93677. pOrExpr = pAndExpr;
  93678. }
  93679. /* Loop through table entries that match term pOrTerm. */
  93680. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  93681. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  93682. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  93683. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  93684. if( pSubWInfo ){
  93685. WhereLoop *pSubLoop;
  93686. explainOneScan(
  93687. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  93688. );
  93689. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  93690. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  93691. int r;
  93692. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  93693. regRowid, 0);
  93694. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  93695. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  93696. }
  93697. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  93698. /* The pSubWInfo->untestedTerms flag means that this OR term
  93699. ** contained one or more AND term from a notReady table. The
  93700. ** terms from the notReady table could not be tested and will
  93701. ** need to be tested later.
  93702. */
  93703. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  93704. /* If all of the OR-connected terms are optimized using the same
  93705. ** index, and the index is opened using the same cursor number
  93706. ** by each call to sqlite3WhereBegin() made by this loop, it may
  93707. ** be possible to use that index as a covering index.
  93708. **
  93709. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  93710. ** uses an index, and this is either the first OR-connected term
  93711. ** processed or the index is the same as that used by all previous
  93712. ** terms, set pCov to the candidate covering index. Otherwise, set
  93713. ** pCov to NULL to indicate that no candidate covering index will
  93714. ** be available.
  93715. */
  93716. pSubLoop = pSubWInfo->a[0].pWLoop;
  93717. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  93718. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  93719. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  93720. ){
  93721. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  93722. pCov = pSubLoop->u.btree.pIndex;
  93723. }else{
  93724. pCov = 0;
  93725. }
  93726. /* Finish the loop through table entries that match term pOrTerm. */
  93727. sqlite3WhereEnd(pSubWInfo);
  93728. }
  93729. }
  93730. }
  93731. pLevel->u.pCovidx = pCov;
  93732. if( pCov ) pLevel->iIdxCur = iCovCur;
  93733. if( pAndExpr ){
  93734. pAndExpr->pLeft = 0;
  93735. sqlite3ExprDelete(db, pAndExpr);
  93736. }
  93737. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  93738. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  93739. sqlite3VdbeResolveLabel(v, iLoopBody);
  93740. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  93741. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  93742. }else
  93743. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  93744. {
  93745. /* Case 6: There is no usable index. We must do a complete
  93746. ** scan of the entire table.
  93747. */
  93748. static const u8 aStep[] = { OP_Next, OP_Prev };
  93749. static const u8 aStart[] = { OP_Rewind, OP_Last };
  93750. assert( bRev==0 || bRev==1 );
  93751. pLevel->op = aStep[bRev];
  93752. pLevel->p1 = iCur;
  93753. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  93754. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  93755. }
  93756. /* Insert code to test every subexpression that can be completely
  93757. ** computed using the current set of tables.
  93758. */
  93759. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  93760. Expr *pE;
  93761. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93762. testcase( pTerm->wtFlags & TERM_CODED );
  93763. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93764. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  93765. testcase( pWInfo->untestedTerms==0
  93766. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  93767. pWInfo->untestedTerms = 1;
  93768. continue;
  93769. }
  93770. pE = pTerm->pExpr;
  93771. assert( pE!=0 );
  93772. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  93773. continue;
  93774. }
  93775. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  93776. pTerm->wtFlags |= TERM_CODED;
  93777. }
  93778. /* Insert code to test for implied constraints based on transitivity
  93779. ** of the "==" operator.
  93780. **
  93781. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  93782. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  93783. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  93784. ** the implied "t1.a=123" constraint.
  93785. */
  93786. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  93787. Expr *pE, *pEAlt;
  93788. WhereTerm *pAlt;
  93789. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93790. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  93791. if( pTerm->leftCursor!=iCur ) continue;
  93792. if( pLevel->iLeftJoin ) continue;
  93793. pE = pTerm->pExpr;
  93794. assert( !ExprHasProperty(pE, EP_FromJoin) );
  93795. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  93796. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  93797. if( pAlt==0 ) continue;
  93798. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  93799. testcase( pAlt->eOperator & WO_EQ );
  93800. testcase( pAlt->eOperator & WO_IN );
  93801. VdbeNoopComment((v, "begin transitive constraint"));
  93802. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  93803. if( pEAlt ){
  93804. *pEAlt = *pAlt->pExpr;
  93805. pEAlt->pLeft = pE->pLeft;
  93806. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  93807. sqlite3StackFree(db, pEAlt);
  93808. }
  93809. }
  93810. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  93811. ** at least one row of the right table has matched the left table.
  93812. */
  93813. if( pLevel->iLeftJoin ){
  93814. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  93815. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  93816. VdbeComment((v, "record LEFT JOIN hit"));
  93817. sqlite3ExprCacheClear(pParse);
  93818. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  93819. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93820. testcase( pTerm->wtFlags & TERM_CODED );
  93821. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93822. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  93823. assert( pWInfo->untestedTerms );
  93824. continue;
  93825. }
  93826. assert( pTerm->pExpr );
  93827. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  93828. pTerm->wtFlags |= TERM_CODED;
  93829. }
  93830. }
  93831. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  93832. return pLevel->notReady;
  93833. }
  93834. #ifdef WHERETRACE_ENABLED
  93835. /*
  93836. ** Print a WhereLoop object for debugging purposes
  93837. */
  93838. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  93839. int nb = 1+(pTabList->nSrc+7)/8;
  93840. struct SrcList_item *pItem = pTabList->a + p->iTab;
  93841. Table *pTab = pItem->pTab;
  93842. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  93843. p->iTab, nb, p->maskSelf, nb, p->prereq);
  93844. sqlite3DebugPrintf(" %12s",
  93845. pItem->zAlias ? pItem->zAlias : pTab->zName);
  93846. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  93847. if( p->u.btree.pIndex ){
  93848. const char *zName = p->u.btree.pIndex->zName;
  93849. if( zName==0 ) zName = "ipk";
  93850. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  93851. int i = sqlite3Strlen30(zName) - 1;
  93852. while( zName[i]!='_' ) i--;
  93853. zName += i;
  93854. }
  93855. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  93856. }else{
  93857. sqlite3DebugPrintf("%20s","");
  93858. }
  93859. }else{
  93860. char *z;
  93861. if( p->u.vtab.idxStr ){
  93862. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  93863. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  93864. }else{
  93865. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  93866. }
  93867. sqlite3DebugPrintf(" %-19s", z);
  93868. sqlite3_free(z);
  93869. }
  93870. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  93871. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  93872. }
  93873. #endif
  93874. /*
  93875. ** Convert bulk memory into a valid WhereLoop that can be passed
  93876. ** to whereLoopClear harmlessly.
  93877. */
  93878. static void whereLoopInit(WhereLoop *p){
  93879. p->aLTerm = p->aLTermSpace;
  93880. p->nLTerm = 0;
  93881. p->nLSlot = ArraySize(p->aLTermSpace);
  93882. p->wsFlags = 0;
  93883. }
  93884. /*
  93885. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  93886. */
  93887. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  93888. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  93889. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  93890. sqlite3_free(p->u.vtab.idxStr);
  93891. p->u.vtab.needFree = 0;
  93892. p->u.vtab.idxStr = 0;
  93893. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  93894. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  93895. sqlite3DbFree(db, p->u.btree.pIndex);
  93896. p->u.btree.pIndex = 0;
  93897. }
  93898. }
  93899. }
  93900. /*
  93901. ** Deallocate internal memory used by a WhereLoop object
  93902. */
  93903. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  93904. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  93905. whereLoopClearUnion(db, p);
  93906. whereLoopInit(p);
  93907. }
  93908. /*
  93909. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  93910. */
  93911. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  93912. WhereTerm **paNew;
  93913. if( p->nLSlot>=n ) return SQLITE_OK;
  93914. n = (n+7)&~7;
  93915. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  93916. if( paNew==0 ) return SQLITE_NOMEM;
  93917. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  93918. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  93919. p->aLTerm = paNew;
  93920. p->nLSlot = n;
  93921. return SQLITE_OK;
  93922. }
  93923. /*
  93924. ** Transfer content from the second pLoop into the first.
  93925. */
  93926. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  93927. whereLoopClearUnion(db, pTo);
  93928. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  93929. memset(&pTo->u, 0, sizeof(pTo->u));
  93930. return SQLITE_NOMEM;
  93931. }
  93932. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  93933. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  93934. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  93935. pFrom->u.vtab.needFree = 0;
  93936. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  93937. pFrom->u.btree.pIndex = 0;
  93938. }
  93939. return SQLITE_OK;
  93940. }
  93941. /*
  93942. ** Delete a WhereLoop object
  93943. */
  93944. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  93945. whereLoopClear(db, p);
  93946. sqlite3DbFree(db, p);
  93947. }
  93948. /*
  93949. ** Free a WhereInfo structure
  93950. */
  93951. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  93952. if( ALWAYS(pWInfo) ){
  93953. whereClauseClear(&pWInfo->sWC);
  93954. while( pWInfo->pLoops ){
  93955. WhereLoop *p = pWInfo->pLoops;
  93956. pWInfo->pLoops = p->pNextLoop;
  93957. whereLoopDelete(db, p);
  93958. }
  93959. sqlite3DbFree(db, pWInfo);
  93960. }
  93961. }
  93962. /*
  93963. ** Insert or replace a WhereLoop entry using the template supplied.
  93964. **
  93965. ** An existing WhereLoop entry might be overwritten if the new template
  93966. ** is better and has fewer dependencies. Or the template will be ignored
  93967. ** and no insert will occur if an existing WhereLoop is faster and has
  93968. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  93969. ** added based on the template.
  93970. **
  93971. ** If pBuilder->pOrSet is not NULL then we only care about only the
  93972. ** prerequisites and rRun and nOut costs of the N best loops. That
  93973. ** information is gathered in the pBuilder->pOrSet object. This special
  93974. ** processing mode is used only for OR clause processing.
  93975. **
  93976. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  93977. ** still might overwrite similar loops with the new template if the
  93978. ** template is better. Loops may be overwritten if the following
  93979. ** conditions are met:
  93980. **
  93981. ** (1) They have the same iTab.
  93982. ** (2) They have the same iSortIdx.
  93983. ** (3) The template has same or fewer dependencies than the current loop
  93984. ** (4) The template has the same or lower cost than the current loop
  93985. ** (5) The template uses more terms of the same index but has no additional
  93986. ** dependencies
  93987. */
  93988. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  93989. WhereLoop **ppPrev, *p, *pNext = 0;
  93990. WhereInfo *pWInfo = pBuilder->pWInfo;
  93991. sqlite3 *db = pWInfo->pParse->db;
  93992. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  93993. ** and prereqs.
  93994. */
  93995. if( pBuilder->pOrSet!=0 ){
  93996. #if WHERETRACE_ENABLED
  93997. u16 n = pBuilder->pOrSet->n;
  93998. int x =
  93999. #endif
  94000. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  94001. pTemplate->nOut);
  94002. #if WHERETRACE_ENABLED
  94003. if( sqlite3WhereTrace & 0x8 ){
  94004. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  94005. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94006. }
  94007. #endif
  94008. return SQLITE_OK;
  94009. }
  94010. /* Search for an existing WhereLoop to overwrite, or which takes
  94011. ** priority over pTemplate.
  94012. */
  94013. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  94014. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  94015. /* If either the iTab or iSortIdx values for two WhereLoop are different
  94016. ** then those WhereLoops need to be considered separately. Neither is
  94017. ** a candidate to replace the other. */
  94018. continue;
  94019. }
  94020. /* In the current implementation, the rSetup value is either zero
  94021. ** or the cost of building an automatic index (NlogN) and the NlogN
  94022. ** is the same for compatible WhereLoops. */
  94023. assert( p->rSetup==0 || pTemplate->rSetup==0
  94024. || p->rSetup==pTemplate->rSetup );
  94025. /* whereLoopAddBtree() always generates and inserts the automatic index
  94026. ** case first. Hence compatible candidate WhereLoops never have a larger
  94027. ** rSetup. Call this SETUP-INVARIANT */
  94028. assert( p->rSetup>=pTemplate->rSetup );
  94029. if( (p->prereq & pTemplate->prereq)==p->prereq
  94030. && p->rSetup<=pTemplate->rSetup
  94031. && p->rRun<=pTemplate->rRun
  94032. && p->nOut<=pTemplate->nOut
  94033. ){
  94034. /* This branch taken when p is equal or better than pTemplate in
  94035. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  94036. ** (4) number of output rows. */
  94037. assert( p->rSetup==pTemplate->rSetup );
  94038. if( p->prereq==pTemplate->prereq
  94039. && p->nLTerm<pTemplate->nLTerm
  94040. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  94041. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  94042. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  94043. ){
  94044. /* Overwrite an existing WhereLoop with an similar one that uses
  94045. ** more terms of the index */
  94046. pNext = p->pNextLoop;
  94047. break;
  94048. }else{
  94049. /* pTemplate is not helpful.
  94050. ** Return without changing or adding anything */
  94051. goto whereLoopInsert_noop;
  94052. }
  94053. }
  94054. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  94055. && p->rRun>=pTemplate->rRun
  94056. && p->nOut>=pTemplate->nOut
  94057. ){
  94058. /* Overwrite an existing WhereLoop with a better one: one that is
  94059. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  94060. ** or (4) number of output rows, and is no worse in any of those
  94061. ** categories. */
  94062. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  94063. pNext = p->pNextLoop;
  94064. break;
  94065. }
  94066. }
  94067. /* If we reach this point it means that either p[] should be overwritten
  94068. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  94069. ** WhereLoop and insert it.
  94070. */
  94071. #if WHERETRACE_ENABLED
  94072. if( sqlite3WhereTrace & 0x8 ){
  94073. if( p!=0 ){
  94074. sqlite3DebugPrintf("ins-del: ");
  94075. whereLoopPrint(p, pWInfo->pTabList);
  94076. }
  94077. sqlite3DebugPrintf("ins-new: ");
  94078. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94079. }
  94080. #endif
  94081. if( p==0 ){
  94082. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  94083. if( p==0 ) return SQLITE_NOMEM;
  94084. whereLoopInit(p);
  94085. }
  94086. whereLoopXfer(db, p, pTemplate);
  94087. p->pNextLoop = pNext;
  94088. *ppPrev = p;
  94089. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  94090. Index *pIndex = p->u.btree.pIndex;
  94091. if( pIndex && pIndex->tnum==0 ){
  94092. p->u.btree.pIndex = 0;
  94093. }
  94094. }
  94095. return SQLITE_OK;
  94096. /* Jump here if the insert is a no-op */
  94097. whereLoopInsert_noop:
  94098. #if WHERETRACE_ENABLED
  94099. if( sqlite3WhereTrace & 0x8 ){
  94100. sqlite3DebugPrintf("ins-noop: ");
  94101. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94102. }
  94103. #endif
  94104. return SQLITE_OK;
  94105. }
  94106. /*
  94107. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  94108. ** WHERE clause that reference the loop but which are not used by an
  94109. ** index.
  94110. **
  94111. ** In the current implementation, the first extra WHERE clause term reduces
  94112. ** the number of output rows by a factor of 10 and each additional term
  94113. ** reduces the number of output rows by sqrt(2).
  94114. */
  94115. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  94116. WhereTerm *pTerm, *pX;
  94117. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  94118. int i, j;
  94119. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  94120. return;
  94121. }
  94122. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  94123. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  94124. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  94125. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  94126. for(j=pLoop->nLTerm-1; j>=0; j--){
  94127. pX = pLoop->aLTerm[j];
  94128. if( pX==pTerm ) break;
  94129. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  94130. }
  94131. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  94132. }
  94133. }
  94134. /*
  94135. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  94136. ** Try to match one more.
  94137. **
  94138. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  94139. ** INTEGER PRIMARY KEY.
  94140. */
  94141. static int whereLoopAddBtreeIndex(
  94142. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  94143. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  94144. Index *pProbe, /* An index on pSrc */
  94145. LogEst nInMul /* log(Number of iterations due to IN) */
  94146. ){
  94147. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  94148. Parse *pParse = pWInfo->pParse; /* Parsing context */
  94149. sqlite3 *db = pParse->db; /* Database connection malloc context */
  94150. WhereLoop *pNew; /* Template WhereLoop under construction */
  94151. WhereTerm *pTerm; /* A WhereTerm under consideration */
  94152. int opMask; /* Valid operators for constraints */
  94153. WhereScan scan; /* Iterator for WHERE terms */
  94154. Bitmask saved_prereq; /* Original value of pNew->prereq */
  94155. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  94156. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  94157. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  94158. LogEst saved_nOut; /* Original value of pNew->nOut */
  94159. int iCol; /* Index of the column in the table */
  94160. int rc = SQLITE_OK; /* Return code */
  94161. LogEst nRowEst; /* Estimated index selectivity */
  94162. LogEst rLogSize; /* Logarithm of table size */
  94163. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  94164. pNew = pBuilder->pNew;
  94165. if( db->mallocFailed ) return SQLITE_NOMEM;
  94166. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  94167. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  94168. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  94169. opMask = WO_LT|WO_LE;
  94170. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  94171. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  94172. }else{
  94173. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  94174. }
  94175. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  94176. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  94177. if( pNew->u.btree.nEq < pProbe->nColumn ){
  94178. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  94179. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  94180. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  94181. }else{
  94182. iCol = -1;
  94183. nRowEst = 0;
  94184. }
  94185. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  94186. opMask, pProbe);
  94187. saved_nEq = pNew->u.btree.nEq;
  94188. saved_nLTerm = pNew->nLTerm;
  94189. saved_wsFlags = pNew->wsFlags;
  94190. saved_prereq = pNew->prereq;
  94191. saved_nOut = pNew->nOut;
  94192. pNew->rSetup = 0;
  94193. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  94194. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  94195. int nIn = 0;
  94196. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94197. int nRecValid = pBuilder->nRecValid;
  94198. #endif
  94199. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  94200. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  94201. ){
  94202. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  94203. }
  94204. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  94205. assert( pNew->nOut==saved_nOut );
  94206. pNew->wsFlags = saved_wsFlags;
  94207. pNew->u.btree.nEq = saved_nEq;
  94208. pNew->nLTerm = saved_nLTerm;
  94209. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  94210. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  94211. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  94212. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  94213. if( pTerm->eOperator & WO_IN ){
  94214. Expr *pExpr = pTerm->pExpr;
  94215. pNew->wsFlags |= WHERE_COLUMN_IN;
  94216. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  94217. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  94218. nIn = 46; assert( 46==sqlite3LogEst(25) );
  94219. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  94220. /* "x IN (value, value, ...)" */
  94221. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  94222. }
  94223. pNew->rRun += nIn;
  94224. pNew->u.btree.nEq++;
  94225. pNew->nOut = nRowEst + nInMul + nIn;
  94226. }else if( pTerm->eOperator & (WO_EQ) ){
  94227. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  94228. || nInMul==0 );
  94229. pNew->wsFlags |= WHERE_COLUMN_EQ;
  94230. if( iCol<0
  94231. || (pProbe->onError!=OE_None && nInMul==0
  94232. && pNew->u.btree.nEq==pProbe->nColumn-1)
  94233. ){
  94234. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  94235. pNew->wsFlags |= WHERE_ONEROW;
  94236. }
  94237. pNew->u.btree.nEq++;
  94238. pNew->nOut = nRowEst + nInMul;
  94239. }else if( pTerm->eOperator & (WO_ISNULL) ){
  94240. pNew->wsFlags |= WHERE_COLUMN_NULL;
  94241. pNew->u.btree.nEq++;
  94242. /* TUNING: IS NULL selects 2 rows */
  94243. nIn = 10; assert( 10==sqlite3LogEst(2) );
  94244. pNew->nOut = nRowEst + nInMul + nIn;
  94245. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  94246. testcase( pTerm->eOperator & WO_GT );
  94247. testcase( pTerm->eOperator & WO_GE );
  94248. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  94249. pBtm = pTerm;
  94250. pTop = 0;
  94251. }else{
  94252. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  94253. testcase( pTerm->eOperator & WO_LT );
  94254. testcase( pTerm->eOperator & WO_LE );
  94255. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  94256. pTop = pTerm;
  94257. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  94258. pNew->aLTerm[pNew->nLTerm-2] : 0;
  94259. }
  94260. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  94261. /* Adjust nOut and rRun for STAT3 range values */
  94262. assert( pNew->nOut==saved_nOut );
  94263. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  94264. }
  94265. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94266. if( nInMul==0
  94267. && pProbe->nSample
  94268. && pNew->u.btree.nEq<=pProbe->nSampleCol
  94269. && OptimizationEnabled(db, SQLITE_Stat3)
  94270. ){
  94271. Expr *pExpr = pTerm->pExpr;
  94272. tRowcnt nOut = 0;
  94273. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  94274. testcase( pTerm->eOperator & WO_EQ );
  94275. testcase( pTerm->eOperator & WO_ISNULL );
  94276. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  94277. }else if( (pTerm->eOperator & WO_IN)
  94278. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  94279. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  94280. }
  94281. assert( nOut==0 || rc==SQLITE_OK );
  94282. if( nOut ){
  94283. pNew->nOut = sqlite3LogEst(nOut);
  94284. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  94285. }
  94286. }
  94287. #endif
  94288. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  94289. /* Each row involves a step of the index, then a binary search of
  94290. ** the main table */
  94291. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  94292. }
  94293. /* Step cost for each output row */
  94294. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  94295. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  94296. rc = whereLoopInsert(pBuilder, pNew);
  94297. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  94298. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  94299. ){
  94300. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  94301. }
  94302. pNew->nOut = saved_nOut;
  94303. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94304. pBuilder->nRecValid = nRecValid;
  94305. #endif
  94306. }
  94307. pNew->prereq = saved_prereq;
  94308. pNew->u.btree.nEq = saved_nEq;
  94309. pNew->wsFlags = saved_wsFlags;
  94310. pNew->nOut = saved_nOut;
  94311. pNew->nLTerm = saved_nLTerm;
  94312. return rc;
  94313. }
  94314. /*
  94315. ** Return True if it is possible that pIndex might be useful in
  94316. ** implementing the ORDER BY clause in pBuilder.
  94317. **
  94318. ** Return False if pBuilder does not contain an ORDER BY clause or
  94319. ** if there is no way for pIndex to be useful in implementing that
  94320. ** ORDER BY clause.
  94321. */
  94322. static int indexMightHelpWithOrderBy(
  94323. WhereLoopBuilder *pBuilder,
  94324. Index *pIndex,
  94325. int iCursor
  94326. ){
  94327. ExprList *pOB;
  94328. int ii, jj;
  94329. if( pIndex->bUnordered ) return 0;
  94330. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  94331. for(ii=0; ii<pOB->nExpr; ii++){
  94332. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  94333. if( pExpr->op!=TK_COLUMN ) return 0;
  94334. if( pExpr->iTable==iCursor ){
  94335. for(jj=0; jj<pIndex->nColumn; jj++){
  94336. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  94337. }
  94338. }
  94339. }
  94340. return 0;
  94341. }
  94342. /*
  94343. ** Return a bitmask where 1s indicate that the corresponding column of
  94344. ** the table is used by an index. Only the first 63 columns are considered.
  94345. */
  94346. static Bitmask columnsInIndex(Index *pIdx){
  94347. Bitmask m = 0;
  94348. int j;
  94349. for(j=pIdx->nColumn-1; j>=0; j--){
  94350. int x = pIdx->aiColumn[j];
  94351. assert( x>=0 );
  94352. testcase( x==BMS-1 );
  94353. testcase( x==BMS-2 );
  94354. if( x<BMS-1 ) m |= MASKBIT(x);
  94355. }
  94356. return m;
  94357. }
  94358. /* Check to see if a partial index with pPartIndexWhere can be used
  94359. ** in the current query. Return true if it can be and false if not.
  94360. */
  94361. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  94362. int i;
  94363. WhereTerm *pTerm;
  94364. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  94365. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  94366. }
  94367. return 0;
  94368. }
  94369. /*
  94370. ** Add all WhereLoop objects for a single table of the join where the table
  94371. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  94372. ** a b-tree table, not a virtual table.
  94373. */
  94374. static int whereLoopAddBtree(
  94375. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  94376. Bitmask mExtra /* Extra prerequesites for using this table */
  94377. ){
  94378. WhereInfo *pWInfo; /* WHERE analysis context */
  94379. Index *pProbe; /* An index we are evaluating */
  94380. Index sPk; /* A fake index object for the primary key */
  94381. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  94382. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  94383. SrcList *pTabList; /* The FROM clause */
  94384. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  94385. WhereLoop *pNew; /* Template WhereLoop object */
  94386. int rc = SQLITE_OK; /* Return code */
  94387. int iSortIdx = 1; /* Index number */
  94388. int b; /* A boolean value */
  94389. LogEst rSize; /* number of rows in the table */
  94390. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  94391. WhereClause *pWC; /* The parsed WHERE clause */
  94392. Table *pTab; /* Table being queried */
  94393. pNew = pBuilder->pNew;
  94394. pWInfo = pBuilder->pWInfo;
  94395. pTabList = pWInfo->pTabList;
  94396. pSrc = pTabList->a + pNew->iTab;
  94397. pTab = pSrc->pTab;
  94398. pWC = pBuilder->pWC;
  94399. assert( !IsVirtual(pSrc->pTab) );
  94400. if( pSrc->pIndex ){
  94401. /* An INDEXED BY clause specifies a particular index to use */
  94402. pProbe = pSrc->pIndex;
  94403. }else{
  94404. /* There is no INDEXED BY clause. Create a fake Index object in local
  94405. ** variable sPk to represent the rowid primary key index. Make this
  94406. ** fake index the first in a chain of Index objects with all of the real
  94407. ** indices to follow */
  94408. Index *pFirst; /* First of real indices on the table */
  94409. memset(&sPk, 0, sizeof(Index));
  94410. sPk.nColumn = 1;
  94411. sPk.aiColumn = &aiColumnPk;
  94412. sPk.aiRowEst = aiRowEstPk;
  94413. sPk.onError = OE_Replace;
  94414. sPk.pTable = pTab;
  94415. aiRowEstPk[0] = pTab->nRowEst;
  94416. aiRowEstPk[1] = 1;
  94417. pFirst = pSrc->pTab->pIndex;
  94418. if( pSrc->notIndexed==0 ){
  94419. /* The real indices of the table are only considered if the
  94420. ** NOT INDEXED qualifier is omitted from the FROM clause */
  94421. sPk.pNext = pFirst;
  94422. }
  94423. pProbe = &sPk;
  94424. }
  94425. rSize = sqlite3LogEst(pTab->nRowEst);
  94426. rLogSize = estLog(rSize);
  94427. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  94428. /* Automatic indexes */
  94429. if( !pBuilder->pOrSet
  94430. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  94431. && pSrc->pIndex==0
  94432. && !pSrc->viaCoroutine
  94433. && !pSrc->notIndexed
  94434. && !pSrc->isCorrelated
  94435. ){
  94436. /* Generate auto-index WhereLoops */
  94437. WhereTerm *pTerm;
  94438. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  94439. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  94440. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  94441. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  94442. pNew->u.btree.nEq = 1;
  94443. pNew->u.btree.pIndex = 0;
  94444. pNew->nLTerm = 1;
  94445. pNew->aLTerm[0] = pTerm;
  94446. /* TUNING: One-time cost for computing the automatic index is
  94447. ** approximately 7*N*log2(N) where N is the number of rows in
  94448. ** the table being indexed. */
  94449. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  94450. /* TUNING: Each index lookup yields 20 rows in the table. This
  94451. ** is more than the usual guess of 10 rows, since we have no way
  94452. ** of knowning how selective the index will ultimately be. It would
  94453. ** not be unreasonable to make this value much larger. */
  94454. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  94455. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  94456. pNew->wsFlags = WHERE_AUTO_INDEX;
  94457. pNew->prereq = mExtra | pTerm->prereqRight;
  94458. rc = whereLoopInsert(pBuilder, pNew);
  94459. }
  94460. }
  94461. }
  94462. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  94463. /* Loop over all indices
  94464. */
  94465. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  94466. if( pProbe->pPartIdxWhere!=0
  94467. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  94468. continue; /* Partial index inappropriate for this query */
  94469. }
  94470. pNew->u.btree.nEq = 0;
  94471. pNew->nLTerm = 0;
  94472. pNew->iSortIdx = 0;
  94473. pNew->rSetup = 0;
  94474. pNew->prereq = mExtra;
  94475. pNew->nOut = rSize;
  94476. pNew->u.btree.pIndex = pProbe;
  94477. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  94478. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  94479. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  94480. if( pProbe->tnum<=0 ){
  94481. /* Integer primary key index */
  94482. pNew->wsFlags = WHERE_IPK;
  94483. /* Full table scan */
  94484. pNew->iSortIdx = b ? iSortIdx : 0;
  94485. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  94486. ** + The extra 3 factor is to encourage the use of indexed lookups
  94487. ** over full scans. FIXME */
  94488. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  94489. whereLoopOutputAdjust(pWC, pNew);
  94490. rc = whereLoopInsert(pBuilder, pNew);
  94491. pNew->nOut = rSize;
  94492. if( rc ) break;
  94493. }else{
  94494. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  94495. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  94496. /* Full scan via index */
  94497. if( b
  94498. || ( m==0
  94499. && pProbe->bUnordered==0
  94500. && pProbe->szIdxRow<pTab->szTabRow
  94501. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  94502. && sqlite3GlobalConfig.bUseCis
  94503. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  94504. )
  94505. ){
  94506. pNew->iSortIdx = b ? iSortIdx : 0;
  94507. if( m==0 ){
  94508. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  94509. ** + The extra factor K of between 1.1 and 3.0 that depends
  94510. ** on the relative sizes of the table and the index. K
  94511. ** is smaller for smaller indices, thus favoring them.
  94512. */
  94513. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  94514. (15*pProbe->szIdxRow)/pTab->szTabRow;
  94515. }else{
  94516. assert( b!=0 );
  94517. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  94518. ** which we will simplify to just N*log2(N) */
  94519. pNew->rRun = rSize + rLogSize;
  94520. }
  94521. whereLoopOutputAdjust(pWC, pNew);
  94522. rc = whereLoopInsert(pBuilder, pNew);
  94523. pNew->nOut = rSize;
  94524. if( rc ) break;
  94525. }
  94526. }
  94527. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  94528. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94529. sqlite3Stat4ProbeFree(pBuilder->pRec);
  94530. pBuilder->nRecValid = 0;
  94531. pBuilder->pRec = 0;
  94532. #endif
  94533. /* If there was an INDEXED BY clause, then only that one index is
  94534. ** considered. */
  94535. if( pSrc->pIndex ) break;
  94536. }
  94537. return rc;
  94538. }
  94539. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94540. /*
  94541. ** Add all WhereLoop objects for a table of the join identified by
  94542. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  94543. */
  94544. static int whereLoopAddVirtual(
  94545. WhereLoopBuilder *pBuilder /* WHERE clause information */
  94546. ){
  94547. WhereInfo *pWInfo; /* WHERE analysis context */
  94548. Parse *pParse; /* The parsing context */
  94549. WhereClause *pWC; /* The WHERE clause */
  94550. struct SrcList_item *pSrc; /* The FROM clause term to search */
  94551. Table *pTab;
  94552. sqlite3 *db;
  94553. sqlite3_index_info *pIdxInfo;
  94554. struct sqlite3_index_constraint *pIdxCons;
  94555. struct sqlite3_index_constraint_usage *pUsage;
  94556. WhereTerm *pTerm;
  94557. int i, j;
  94558. int iTerm, mxTerm;
  94559. int nConstraint;
  94560. int seenIn = 0; /* True if an IN operator is seen */
  94561. int seenVar = 0; /* True if a non-constant constraint is seen */
  94562. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  94563. WhereLoop *pNew;
  94564. int rc = SQLITE_OK;
  94565. pWInfo = pBuilder->pWInfo;
  94566. pParse = pWInfo->pParse;
  94567. db = pParse->db;
  94568. pWC = pBuilder->pWC;
  94569. pNew = pBuilder->pNew;
  94570. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  94571. pTab = pSrc->pTab;
  94572. assert( IsVirtual(pTab) );
  94573. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  94574. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  94575. pNew->prereq = 0;
  94576. pNew->rSetup = 0;
  94577. pNew->wsFlags = WHERE_VIRTUALTABLE;
  94578. pNew->nLTerm = 0;
  94579. pNew->u.vtab.needFree = 0;
  94580. pUsage = pIdxInfo->aConstraintUsage;
  94581. nConstraint = pIdxInfo->nConstraint;
  94582. if( whereLoopResize(db, pNew, nConstraint) ){
  94583. sqlite3DbFree(db, pIdxInfo);
  94584. return SQLITE_NOMEM;
  94585. }
  94586. for(iPhase=0; iPhase<=3; iPhase++){
  94587. if( !seenIn && (iPhase&1)!=0 ){
  94588. iPhase++;
  94589. if( iPhase>3 ) break;
  94590. }
  94591. if( !seenVar && iPhase>1 ) break;
  94592. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  94593. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  94594. j = pIdxCons->iTermOffset;
  94595. pTerm = &pWC->a[j];
  94596. switch( iPhase ){
  94597. case 0: /* Constants without IN operator */
  94598. pIdxCons->usable = 0;
  94599. if( (pTerm->eOperator & WO_IN)!=0 ){
  94600. seenIn = 1;
  94601. }
  94602. if( pTerm->prereqRight!=0 ){
  94603. seenVar = 1;
  94604. }else if( (pTerm->eOperator & WO_IN)==0 ){
  94605. pIdxCons->usable = 1;
  94606. }
  94607. break;
  94608. case 1: /* Constants with IN operators */
  94609. assert( seenIn );
  94610. pIdxCons->usable = (pTerm->prereqRight==0);
  94611. break;
  94612. case 2: /* Variables without IN */
  94613. assert( seenVar );
  94614. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  94615. break;
  94616. default: /* Variables with IN */
  94617. assert( seenVar && seenIn );
  94618. pIdxCons->usable = 1;
  94619. break;
  94620. }
  94621. }
  94622. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  94623. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  94624. pIdxInfo->idxStr = 0;
  94625. pIdxInfo->idxNum = 0;
  94626. pIdxInfo->needToFreeIdxStr = 0;
  94627. pIdxInfo->orderByConsumed = 0;
  94628. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  94629. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  94630. if( rc ) goto whereLoopAddVtab_exit;
  94631. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  94632. pNew->prereq = 0;
  94633. mxTerm = -1;
  94634. assert( pNew->nLSlot>=nConstraint );
  94635. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  94636. pNew->u.vtab.omitMask = 0;
  94637. for(i=0; i<nConstraint; i++, pIdxCons++){
  94638. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  94639. j = pIdxCons->iTermOffset;
  94640. if( iTerm>=nConstraint
  94641. || j<0
  94642. || j>=pWC->nTerm
  94643. || pNew->aLTerm[iTerm]!=0
  94644. ){
  94645. rc = SQLITE_ERROR;
  94646. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  94647. goto whereLoopAddVtab_exit;
  94648. }
  94649. testcase( iTerm==nConstraint-1 );
  94650. testcase( j==0 );
  94651. testcase( j==pWC->nTerm-1 );
  94652. pTerm = &pWC->a[j];
  94653. pNew->prereq |= pTerm->prereqRight;
  94654. assert( iTerm<pNew->nLSlot );
  94655. pNew->aLTerm[iTerm] = pTerm;
  94656. if( iTerm>mxTerm ) mxTerm = iTerm;
  94657. testcase( iTerm==15 );
  94658. testcase( iTerm==16 );
  94659. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  94660. if( (pTerm->eOperator & WO_IN)!=0 ){
  94661. if( pUsage[i].omit==0 ){
  94662. /* Do not attempt to use an IN constraint if the virtual table
  94663. ** says that the equivalent EQ constraint cannot be safely omitted.
  94664. ** If we do attempt to use such a constraint, some rows might be
  94665. ** repeated in the output. */
  94666. break;
  94667. }
  94668. /* A virtual table that is constrained by an IN clause may not
  94669. ** consume the ORDER BY clause because (1) the order of IN terms
  94670. ** is not necessarily related to the order of output terms and
  94671. ** (2) Multiple outputs from a single IN value will not merge
  94672. ** together. */
  94673. pIdxInfo->orderByConsumed = 0;
  94674. }
  94675. }
  94676. }
  94677. if( i>=nConstraint ){
  94678. pNew->nLTerm = mxTerm+1;
  94679. assert( pNew->nLTerm<=pNew->nLSlot );
  94680. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  94681. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  94682. pIdxInfo->needToFreeIdxStr = 0;
  94683. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  94684. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  94685. && pIdxInfo->orderByConsumed);
  94686. pNew->rSetup = 0;
  94687. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  94688. /* TUNING: Every virtual table query returns 25 rows */
  94689. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  94690. whereLoopInsert(pBuilder, pNew);
  94691. if( pNew->u.vtab.needFree ){
  94692. sqlite3_free(pNew->u.vtab.idxStr);
  94693. pNew->u.vtab.needFree = 0;
  94694. }
  94695. }
  94696. }
  94697. whereLoopAddVtab_exit:
  94698. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  94699. sqlite3DbFree(db, pIdxInfo);
  94700. return rc;
  94701. }
  94702. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  94703. /*
  94704. ** Add WhereLoop entries to handle OR terms. This works for either
  94705. ** btrees or virtual tables.
  94706. */
  94707. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  94708. WhereInfo *pWInfo = pBuilder->pWInfo;
  94709. WhereClause *pWC;
  94710. WhereLoop *pNew;
  94711. WhereTerm *pTerm, *pWCEnd;
  94712. int rc = SQLITE_OK;
  94713. int iCur;
  94714. WhereClause tempWC;
  94715. WhereLoopBuilder sSubBuild;
  94716. WhereOrSet sSum, sCur, sPrev;
  94717. struct SrcList_item *pItem;
  94718. pWC = pBuilder->pWC;
  94719. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  94720. pWCEnd = pWC->a + pWC->nTerm;
  94721. pNew = pBuilder->pNew;
  94722. memset(&sSum, 0, sizeof(sSum));
  94723. pItem = pWInfo->pTabList->a + pNew->iTab;
  94724. iCur = pItem->iCursor;
  94725. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  94726. if( (pTerm->eOperator & WO_OR)!=0
  94727. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  94728. ){
  94729. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  94730. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  94731. WhereTerm *pOrTerm;
  94732. int once = 1;
  94733. int i, j;
  94734. sSubBuild = *pBuilder;
  94735. sSubBuild.pOrderBy = 0;
  94736. sSubBuild.pOrSet = &sCur;
  94737. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  94738. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  94739. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  94740. }else if( pOrTerm->leftCursor==iCur ){
  94741. tempWC.pWInfo = pWC->pWInfo;
  94742. tempWC.pOuter = pWC;
  94743. tempWC.op = TK_AND;
  94744. tempWC.nTerm = 1;
  94745. tempWC.a = pOrTerm;
  94746. sSubBuild.pWC = &tempWC;
  94747. }else{
  94748. continue;
  94749. }
  94750. sCur.n = 0;
  94751. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94752. if( IsVirtual(pItem->pTab) ){
  94753. rc = whereLoopAddVirtual(&sSubBuild);
  94754. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  94755. }else
  94756. #endif
  94757. {
  94758. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  94759. }
  94760. assert( rc==SQLITE_OK || sCur.n==0 );
  94761. if( sCur.n==0 ){
  94762. sSum.n = 0;
  94763. break;
  94764. }else if( once ){
  94765. whereOrMove(&sSum, &sCur);
  94766. once = 0;
  94767. }else{
  94768. whereOrMove(&sPrev, &sSum);
  94769. sSum.n = 0;
  94770. for(i=0; i<sPrev.n; i++){
  94771. for(j=0; j<sCur.n; j++){
  94772. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  94773. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  94774. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  94775. }
  94776. }
  94777. }
  94778. }
  94779. pNew->nLTerm = 1;
  94780. pNew->aLTerm[0] = pTerm;
  94781. pNew->wsFlags = WHERE_MULTI_OR;
  94782. pNew->rSetup = 0;
  94783. pNew->iSortIdx = 0;
  94784. memset(&pNew->u, 0, sizeof(pNew->u));
  94785. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  94786. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  94787. pNew->rRun = sSum.a[i].rRun + 18;
  94788. pNew->nOut = sSum.a[i].nOut;
  94789. pNew->prereq = sSum.a[i].prereq;
  94790. rc = whereLoopInsert(pBuilder, pNew);
  94791. }
  94792. }
  94793. }
  94794. return rc;
  94795. }
  94796. /*
  94797. ** Add all WhereLoop objects for all tables
  94798. */
  94799. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  94800. WhereInfo *pWInfo = pBuilder->pWInfo;
  94801. Bitmask mExtra = 0;
  94802. Bitmask mPrior = 0;
  94803. int iTab;
  94804. SrcList *pTabList = pWInfo->pTabList;
  94805. struct SrcList_item *pItem;
  94806. sqlite3 *db = pWInfo->pParse->db;
  94807. int nTabList = pWInfo->nLevel;
  94808. int rc = SQLITE_OK;
  94809. u8 priorJoinType = 0;
  94810. WhereLoop *pNew;
  94811. /* Loop over the tables in the join, from left to right */
  94812. pNew = pBuilder->pNew;
  94813. whereLoopInit(pNew);
  94814. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  94815. pNew->iTab = iTab;
  94816. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  94817. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  94818. mExtra = mPrior;
  94819. }
  94820. priorJoinType = pItem->jointype;
  94821. if( IsVirtual(pItem->pTab) ){
  94822. rc = whereLoopAddVirtual(pBuilder);
  94823. }else{
  94824. rc = whereLoopAddBtree(pBuilder, mExtra);
  94825. }
  94826. if( rc==SQLITE_OK ){
  94827. rc = whereLoopAddOr(pBuilder, mExtra);
  94828. }
  94829. mPrior |= pNew->maskSelf;
  94830. if( rc || db->mallocFailed ) break;
  94831. }
  94832. whereLoopClear(db, pNew);
  94833. return rc;
  94834. }
  94835. /*
  94836. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  94837. ** parameters) to see if it outputs rows in the requested ORDER BY
  94838. ** (or GROUP BY) without requiring a separate sort operation. Return:
  94839. **
  94840. ** 0: ORDER BY is not satisfied. Sorting required
  94841. ** 1: ORDER BY is satisfied. Omit sorting
  94842. ** -1: Unknown at this time
  94843. **
  94844. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  94845. ** strict. With GROUP BY and DISTINCT the only requirement is that
  94846. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  94847. ** and DISTINT do not require rows to appear in any particular order as long
  94848. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  94849. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  94850. ** pOrderBy terms must be matched in strict left-to-right order.
  94851. */
  94852. static int wherePathSatisfiesOrderBy(
  94853. WhereInfo *pWInfo, /* The WHERE clause */
  94854. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  94855. WherePath *pPath, /* The WherePath to check */
  94856. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  94857. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  94858. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  94859. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  94860. ){
  94861. u8 revSet; /* True if rev is known */
  94862. u8 rev; /* Composite sort order */
  94863. u8 revIdx; /* Index sort order */
  94864. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  94865. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  94866. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  94867. u16 nColumn; /* Number of columns in pIndex */
  94868. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  94869. int iLoop; /* Index of WhereLoop in pPath being processed */
  94870. int i, j; /* Loop counters */
  94871. int iCur; /* Cursor number for current WhereLoop */
  94872. int iColumn; /* A column number within table iCur */
  94873. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  94874. WhereTerm *pTerm; /* A single term of the WHERE clause */
  94875. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  94876. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  94877. Index *pIndex; /* The index associated with pLoop */
  94878. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  94879. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  94880. Bitmask obDone; /* Mask of all ORDER BY terms */
  94881. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  94882. Bitmask ready; /* Mask of inner loops */
  94883. /*
  94884. ** We say the WhereLoop is "one-row" if it generates no more than one
  94885. ** row of output. A WhereLoop is one-row if all of the following are true:
  94886. ** (a) All index columns match with WHERE_COLUMN_EQ.
  94887. ** (b) The index is unique
  94888. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  94889. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  94890. **
  94891. ** We say the WhereLoop is "order-distinct" if the set of columns from
  94892. ** that WhereLoop that are in the ORDER BY clause are different for every
  94893. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  94894. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  94895. ** is not order-distinct. To be order-distinct is not quite the same as being
  94896. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  94897. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  94898. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  94899. **
  94900. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  94901. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  94902. ** automatically order-distinct.
  94903. */
  94904. assert( pOrderBy!=0 );
  94905. /* Sortability of virtual tables is determined by the xBestIndex method
  94906. ** of the virtual table itself */
  94907. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  94908. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  94909. ** no ORDER BY terms */
  94910. return pLast->u.vtab.isOrdered;
  94911. }
  94912. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  94913. nOrderBy = pOrderBy->nExpr;
  94914. testcase( nOrderBy==BMS-1 );
  94915. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  94916. isOrderDistinct = 1;
  94917. obDone = MASKBIT(nOrderBy)-1;
  94918. orderDistinctMask = 0;
  94919. ready = 0;
  94920. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  94921. if( iLoop>0 ) ready |= pLoop->maskSelf;
  94922. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  94923. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  94924. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  94925. /* Mark off any ORDER BY term X that is a column in the table of
  94926. ** the current loop for which there is term in the WHERE
  94927. ** clause of the form X IS NULL or X=? that reference only outer
  94928. ** loops.
  94929. */
  94930. for(i=0; i<nOrderBy; i++){
  94931. if( MASKBIT(i) & obSat ) continue;
  94932. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  94933. if( pOBExpr->op!=TK_COLUMN ) continue;
  94934. if( pOBExpr->iTable!=iCur ) continue;
  94935. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  94936. ~ready, WO_EQ|WO_ISNULL, 0);
  94937. if( pTerm==0 ) continue;
  94938. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  94939. const char *z1, *z2;
  94940. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  94941. if( !pColl ) pColl = db->pDfltColl;
  94942. z1 = pColl->zName;
  94943. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  94944. if( !pColl ) pColl = db->pDfltColl;
  94945. z2 = pColl->zName;
  94946. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  94947. }
  94948. obSat |= MASKBIT(i);
  94949. }
  94950. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  94951. if( pLoop->wsFlags & WHERE_IPK ){
  94952. pIndex = 0;
  94953. nColumn = 0;
  94954. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  94955. return 0;
  94956. }else{
  94957. nColumn = pIndex->nColumn;
  94958. isOrderDistinct = pIndex->onError!=OE_None;
  94959. }
  94960. /* Loop through all columns of the index and deal with the ones
  94961. ** that are not constrained by == or IN.
  94962. */
  94963. rev = revSet = 0;
  94964. distinctColumns = 0;
  94965. for(j=0; j<=nColumn; j++){
  94966. u8 bOnce; /* True to run the ORDER BY search loop */
  94967. /* Skip over == and IS NULL terms */
  94968. if( j<pLoop->u.btree.nEq
  94969. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  94970. ){
  94971. if( i & WO_ISNULL ){
  94972. testcase( isOrderDistinct );
  94973. isOrderDistinct = 0;
  94974. }
  94975. continue;
  94976. }
  94977. /* Get the column number in the table (iColumn) and sort order
  94978. ** (revIdx) for the j-th column of the index.
  94979. */
  94980. if( j<nColumn ){
  94981. /* Normal index columns */
  94982. iColumn = pIndex->aiColumn[j];
  94983. revIdx = pIndex->aSortOrder[j];
  94984. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  94985. }else{
  94986. /* The ROWID column at the end */
  94987. assert( j==nColumn );
  94988. iColumn = -1;
  94989. revIdx = 0;
  94990. }
  94991. /* An unconstrained column that might be NULL means that this
  94992. ** WhereLoop is not well-ordered
  94993. */
  94994. if( isOrderDistinct
  94995. && iColumn>=0
  94996. && j>=pLoop->u.btree.nEq
  94997. && pIndex->pTable->aCol[iColumn].notNull==0
  94998. ){
  94999. isOrderDistinct = 0;
  95000. }
  95001. /* Find the ORDER BY term that corresponds to the j-th column
  95002. ** of the index and and mark that ORDER BY term off
  95003. */
  95004. bOnce = 1;
  95005. isMatch = 0;
  95006. for(i=0; bOnce && i<nOrderBy; i++){
  95007. if( MASKBIT(i) & obSat ) continue;
  95008. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  95009. testcase( wctrlFlags & WHERE_GROUPBY );
  95010. testcase( wctrlFlags & WHERE_DISTINCTBY );
  95011. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  95012. if( pOBExpr->op!=TK_COLUMN ) continue;
  95013. if( pOBExpr->iTable!=iCur ) continue;
  95014. if( pOBExpr->iColumn!=iColumn ) continue;
  95015. if( iColumn>=0 ){
  95016. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  95017. if( !pColl ) pColl = db->pDfltColl;
  95018. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  95019. }
  95020. isMatch = 1;
  95021. break;
  95022. }
  95023. if( isMatch ){
  95024. if( iColumn<0 ){
  95025. testcase( distinctColumns==0 );
  95026. distinctColumns = 1;
  95027. }
  95028. obSat |= MASKBIT(i);
  95029. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  95030. /* Make sure the sort order is compatible in an ORDER BY clause.
  95031. ** Sort order is irrelevant for a GROUP BY clause. */
  95032. if( revSet ){
  95033. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  95034. }else{
  95035. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  95036. if( rev ) *pRevMask |= MASKBIT(iLoop);
  95037. revSet = 1;
  95038. }
  95039. }
  95040. }else{
  95041. /* No match found */
  95042. if( j==0 || j<nColumn ){
  95043. testcase( isOrderDistinct!=0 );
  95044. isOrderDistinct = 0;
  95045. }
  95046. break;
  95047. }
  95048. } /* end Loop over all index columns */
  95049. if( distinctColumns ){
  95050. testcase( isOrderDistinct==0 );
  95051. isOrderDistinct = 1;
  95052. }
  95053. } /* end-if not one-row */
  95054. /* Mark off any other ORDER BY terms that reference pLoop */
  95055. if( isOrderDistinct ){
  95056. orderDistinctMask |= pLoop->maskSelf;
  95057. for(i=0; i<nOrderBy; i++){
  95058. Expr *p;
  95059. if( MASKBIT(i) & obSat ) continue;
  95060. p = pOrderBy->a[i].pExpr;
  95061. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  95062. obSat |= MASKBIT(i);
  95063. }
  95064. }
  95065. }
  95066. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  95067. if( obSat==obDone ) return 1;
  95068. if( !isOrderDistinct ) return 0;
  95069. return -1;
  95070. }
  95071. #ifdef WHERETRACE_ENABLED
  95072. /* For debugging use only: */
  95073. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  95074. static char zName[65];
  95075. int i;
  95076. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  95077. if( pLast ) zName[i++] = pLast->cId;
  95078. zName[i] = 0;
  95079. return zName;
  95080. }
  95081. #endif
  95082. /*
  95083. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  95084. ** attempts to find the lowest cost path that visits each WhereLoop
  95085. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  95086. **
  95087. ** Assume that the total number of output rows that will need to be sorted
  95088. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  95089. ** costs if nRowEst==0.
  95090. **
  95091. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  95092. ** error occurs.
  95093. */
  95094. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  95095. int mxChoice; /* Maximum number of simultaneous paths tracked */
  95096. int nLoop; /* Number of terms in the join */
  95097. Parse *pParse; /* Parsing context */
  95098. sqlite3 *db; /* The database connection */
  95099. int iLoop; /* Loop counter over the terms of the join */
  95100. int ii, jj; /* Loop counters */
  95101. int mxI = 0; /* Index of next entry to replace */
  95102. LogEst rCost; /* Cost of a path */
  95103. LogEst nOut; /* Number of outputs */
  95104. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  95105. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  95106. LogEst rSortCost; /* Cost to do a sort */
  95107. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  95108. WherePath *aFrom; /* All nFrom paths at the previous level */
  95109. WherePath *aTo; /* The nTo best paths at the current level */
  95110. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  95111. WherePath *pTo; /* An element of aTo[] that we are working on */
  95112. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  95113. WhereLoop **pX; /* Used to divy up the pSpace memory */
  95114. char *pSpace; /* Temporary memory used by this routine */
  95115. pParse = pWInfo->pParse;
  95116. db = pParse->db;
  95117. nLoop = pWInfo->nLevel;
  95118. /* TUNING: For simple queries, only the best path is tracked.
  95119. ** For 2-way joins, the 5 best paths are followed.
  95120. ** For joins of 3 or more tables, track the 10 best paths */
  95121. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  95122. assert( nLoop<=pWInfo->pTabList->nSrc );
  95123. WHERETRACE(0x002, ("---- begin solver\n"));
  95124. /* Allocate and initialize space for aTo and aFrom */
  95125. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  95126. pSpace = sqlite3DbMallocRaw(db, ii);
  95127. if( pSpace==0 ) return SQLITE_NOMEM;
  95128. aTo = (WherePath*)pSpace;
  95129. aFrom = aTo+mxChoice;
  95130. memset(aFrom, 0, sizeof(aFrom[0]));
  95131. pX = (WhereLoop**)(aFrom+mxChoice);
  95132. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  95133. pFrom->aLoop = pX;
  95134. }
  95135. /* Seed the search with a single WherePath containing zero WhereLoops.
  95136. **
  95137. ** TUNING: Do not let the number of iterations go above 25. If the cost
  95138. ** of computing an automatic index is not paid back within the first 25
  95139. ** rows, then do not use the automatic index. */
  95140. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  95141. nFrom = 1;
  95142. /* Precompute the cost of sorting the final result set, if the caller
  95143. ** to sqlite3WhereBegin() was concerned about sorting */
  95144. rSortCost = 0;
  95145. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  95146. aFrom[0].isOrderedValid = 1;
  95147. }else{
  95148. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  95149. ** number of output rows. The 48 is the expected size of a row to sort.
  95150. ** FIXME: compute a better estimate of the 48 multiplier based on the
  95151. ** result set expressions. */
  95152. rSortCost = nRowEst + estLog(nRowEst);
  95153. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  95154. }
  95155. /* Compute successively longer WherePaths using the previous generation
  95156. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  95157. ** best paths at each generation */
  95158. for(iLoop=0; iLoop<nLoop; iLoop++){
  95159. nTo = 0;
  95160. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  95161. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  95162. Bitmask maskNew;
  95163. Bitmask revMask = 0;
  95164. u8 isOrderedValid = pFrom->isOrderedValid;
  95165. u8 isOrdered = pFrom->isOrdered;
  95166. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  95167. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  95168. /* At this point, pWLoop is a candidate to be the next loop.
  95169. ** Compute its cost */
  95170. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  95171. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  95172. nOut = pFrom->nRow + pWLoop->nOut;
  95173. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  95174. if( !isOrderedValid ){
  95175. switch( wherePathSatisfiesOrderBy(pWInfo,
  95176. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  95177. iLoop, pWLoop, &revMask) ){
  95178. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  95179. isOrdered = 1;
  95180. isOrderedValid = 1;
  95181. break;
  95182. case 0: /* No. pFrom+pWLoop will require a separate sort */
  95183. isOrdered = 0;
  95184. isOrderedValid = 1;
  95185. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  95186. break;
  95187. default: /* Cannot tell yet. Try again on the next iteration */
  95188. break;
  95189. }
  95190. }else{
  95191. revMask = pFrom->revLoop;
  95192. }
  95193. /* Check to see if pWLoop should be added to the mxChoice best so far */
  95194. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  95195. if( pTo->maskLoop==maskNew
  95196. && pTo->isOrderedValid==isOrderedValid
  95197. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  95198. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  95199. ){
  95200. testcase( jj==nTo-1 );
  95201. break;
  95202. }
  95203. }
  95204. if( jj>=nTo ){
  95205. if( nTo>=mxChoice && rCost>=mxCost ){
  95206. #ifdef WHERETRACE_ENABLED
  95207. if( sqlite3WhereTrace&0x4 ){
  95208. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  95209. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95210. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95211. }
  95212. #endif
  95213. continue;
  95214. }
  95215. /* Add a new Path to the aTo[] set */
  95216. if( nTo<mxChoice ){
  95217. /* Increase the size of the aTo set by one */
  95218. jj = nTo++;
  95219. }else{
  95220. /* New path replaces the prior worst to keep count below mxChoice */
  95221. jj = mxI;
  95222. }
  95223. pTo = &aTo[jj];
  95224. #ifdef WHERETRACE_ENABLED
  95225. if( sqlite3WhereTrace&0x4 ){
  95226. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  95227. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95228. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95229. }
  95230. #endif
  95231. }else{
  95232. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  95233. #ifdef WHERETRACE_ENABLED
  95234. if( sqlite3WhereTrace&0x4 ){
  95235. sqlite3DebugPrintf(
  95236. "Skip %s cost=%-3d,%3d order=%c",
  95237. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95238. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95239. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  95240. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95241. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95242. }
  95243. #endif
  95244. testcase( pTo->rCost==rCost );
  95245. continue;
  95246. }
  95247. testcase( pTo->rCost==rCost+1 );
  95248. /* A new and better score for a previously created equivalent path */
  95249. #ifdef WHERETRACE_ENABLED
  95250. if( sqlite3WhereTrace&0x4 ){
  95251. sqlite3DebugPrintf(
  95252. "Update %s cost=%-3d,%3d order=%c",
  95253. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95254. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95255. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  95256. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95257. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95258. }
  95259. #endif
  95260. }
  95261. /* pWLoop is a winner. Add it to the set of best so far */
  95262. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  95263. pTo->revLoop = revMask;
  95264. pTo->nRow = nOut;
  95265. pTo->rCost = rCost;
  95266. pTo->isOrderedValid = isOrderedValid;
  95267. pTo->isOrdered = isOrdered;
  95268. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  95269. pTo->aLoop[iLoop] = pWLoop;
  95270. if( nTo>=mxChoice ){
  95271. mxI = 0;
  95272. mxCost = aTo[0].rCost;
  95273. mxOut = aTo[0].nRow;
  95274. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  95275. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  95276. mxCost = pTo->rCost;
  95277. mxOut = pTo->nRow;
  95278. mxI = jj;
  95279. }
  95280. }
  95281. }
  95282. }
  95283. }
  95284. #ifdef WHERETRACE_ENABLED
  95285. if( sqlite3WhereTrace>=2 ){
  95286. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  95287. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  95288. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  95289. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95290. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95291. if( pTo->isOrderedValid && pTo->isOrdered ){
  95292. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  95293. }else{
  95294. sqlite3DebugPrintf("\n");
  95295. }
  95296. }
  95297. }
  95298. #endif
  95299. /* Swap the roles of aFrom and aTo for the next generation */
  95300. pFrom = aTo;
  95301. aTo = aFrom;
  95302. aFrom = pFrom;
  95303. nFrom = nTo;
  95304. }
  95305. if( nFrom==0 ){
  95306. sqlite3ErrorMsg(pParse, "no query solution");
  95307. sqlite3DbFree(db, pSpace);
  95308. return SQLITE_ERROR;
  95309. }
  95310. /* Find the lowest cost path. pFrom will be left pointing to that path */
  95311. pFrom = aFrom;
  95312. for(ii=1; ii<nFrom; ii++){
  95313. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  95314. }
  95315. assert( pWInfo->nLevel==nLoop );
  95316. /* Load the lowest cost path into pWInfo */
  95317. for(iLoop=0; iLoop<nLoop; iLoop++){
  95318. WhereLevel *pLevel = pWInfo->a + iLoop;
  95319. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  95320. pLevel->iFrom = pWLoop->iTab;
  95321. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  95322. }
  95323. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  95324. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  95325. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  95326. && nRowEst
  95327. ){
  95328. Bitmask notUsed;
  95329. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  95330. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  95331. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  95332. }
  95333. if( pFrom->isOrdered ){
  95334. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  95335. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  95336. }else{
  95337. pWInfo->bOBSat = 1;
  95338. pWInfo->revMask = pFrom->revLoop;
  95339. }
  95340. }
  95341. pWInfo->nRowOut = pFrom->nRow;
  95342. /* Free temporary memory and return success */
  95343. sqlite3DbFree(db, pSpace);
  95344. return SQLITE_OK;
  95345. }
  95346. /*
  95347. ** Most queries use only a single table (they are not joins) and have
  95348. ** simple == constraints against indexed fields. This routine attempts
  95349. ** to plan those simple cases using much less ceremony than the
  95350. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  95351. ** times for the common case.
  95352. **
  95353. ** Return non-zero on success, if this query can be handled by this
  95354. ** no-frills query planner. Return zero if this query needs the
  95355. ** general-purpose query planner.
  95356. */
  95357. static int whereShortCut(WhereLoopBuilder *pBuilder){
  95358. WhereInfo *pWInfo;
  95359. struct SrcList_item *pItem;
  95360. WhereClause *pWC;
  95361. WhereTerm *pTerm;
  95362. WhereLoop *pLoop;
  95363. int iCur;
  95364. int j;
  95365. Table *pTab;
  95366. Index *pIdx;
  95367. pWInfo = pBuilder->pWInfo;
  95368. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  95369. assert( pWInfo->pTabList->nSrc>=1 );
  95370. pItem = pWInfo->pTabList->a;
  95371. pTab = pItem->pTab;
  95372. if( IsVirtual(pTab) ) return 0;
  95373. if( pItem->zIndex ) return 0;
  95374. iCur = pItem->iCursor;
  95375. pWC = &pWInfo->sWC;
  95376. pLoop = pBuilder->pNew;
  95377. pLoop->wsFlags = 0;
  95378. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  95379. if( pTerm ){
  95380. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  95381. pLoop->aLTerm[0] = pTerm;
  95382. pLoop->nLTerm = 1;
  95383. pLoop->u.btree.nEq = 1;
  95384. /* TUNING: Cost of a rowid lookup is 10 */
  95385. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  95386. }else{
  95387. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95388. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  95389. assert( ArraySize(pLoop->aLTermSpace)==4 );
  95390. if( pIdx->onError==OE_None
  95391. || pIdx->pPartIdxWhere!=0
  95392. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  95393. ) continue;
  95394. for(j=0; j<pIdx->nColumn; j++){
  95395. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  95396. if( pTerm==0 ) break;
  95397. pLoop->aLTerm[j] = pTerm;
  95398. }
  95399. if( j!=pIdx->nColumn ) continue;
  95400. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  95401. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  95402. pLoop->wsFlags |= WHERE_IDX_ONLY;
  95403. }
  95404. pLoop->nLTerm = j;
  95405. pLoop->u.btree.nEq = j;
  95406. pLoop->u.btree.pIndex = pIdx;
  95407. /* TUNING: Cost of a unique index lookup is 15 */
  95408. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  95409. break;
  95410. }
  95411. }
  95412. if( pLoop->wsFlags ){
  95413. pLoop->nOut = (LogEst)1;
  95414. pWInfo->a[0].pWLoop = pLoop;
  95415. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  95416. pWInfo->a[0].iTabCur = iCur;
  95417. pWInfo->nRowOut = 1;
  95418. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  95419. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  95420. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95421. }
  95422. #ifdef SQLITE_DEBUG
  95423. pLoop->cId = '0';
  95424. #endif
  95425. return 1;
  95426. }
  95427. return 0;
  95428. }
  95429. /*
  95430. ** Generate the beginning of the loop used for WHERE clause processing.
  95431. ** The return value is a pointer to an opaque structure that contains
  95432. ** information needed to terminate the loop. Later, the calling routine
  95433. ** should invoke sqlite3WhereEnd() with the return value of this function
  95434. ** in order to complete the WHERE clause processing.
  95435. **
  95436. ** If an error occurs, this routine returns NULL.
  95437. **
  95438. ** The basic idea is to do a nested loop, one loop for each table in
  95439. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  95440. ** same as a SELECT with only a single table in the FROM clause.) For
  95441. ** example, if the SQL is this:
  95442. **
  95443. ** SELECT * FROM t1, t2, t3 WHERE ...;
  95444. **
  95445. ** Then the code generated is conceptually like the following:
  95446. **
  95447. ** foreach row1 in t1 do \ Code generated
  95448. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  95449. ** foreach row3 in t3 do /
  95450. ** ...
  95451. ** end \ Code generated
  95452. ** end |-- by sqlite3WhereEnd()
  95453. ** end /
  95454. **
  95455. ** Note that the loops might not be nested in the order in which they
  95456. ** appear in the FROM clause if a different order is better able to make
  95457. ** use of indices. Note also that when the IN operator appears in
  95458. ** the WHERE clause, it might result in additional nested loops for
  95459. ** scanning through all values on the right-hand side of the IN.
  95460. **
  95461. ** There are Btree cursors associated with each table. t1 uses cursor
  95462. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  95463. ** And so forth. This routine generates code to open those VDBE cursors
  95464. ** and sqlite3WhereEnd() generates the code to close them.
  95465. **
  95466. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  95467. ** in pTabList pointing at their appropriate entries. The [...] code
  95468. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  95469. ** data from the various tables of the loop.
  95470. **
  95471. ** If the WHERE clause is empty, the foreach loops must each scan their
  95472. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  95473. ** the tables have indices and there are terms in the WHERE clause that
  95474. ** refer to those indices, a complete table scan can be avoided and the
  95475. ** code will run much faster. Most of the work of this routine is checking
  95476. ** to see if there are indices that can be used to speed up the loop.
  95477. **
  95478. ** Terms of the WHERE clause are also used to limit which rows actually
  95479. ** make it to the "..." in the middle of the loop. After each "foreach",
  95480. ** terms of the WHERE clause that use only terms in that loop and outer
  95481. ** loops are evaluated and if false a jump is made around all subsequent
  95482. ** inner loops (or around the "..." if the test occurs within the inner-
  95483. ** most loop)
  95484. **
  95485. ** OUTER JOINS
  95486. **
  95487. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  95488. **
  95489. ** foreach row1 in t1 do
  95490. ** flag = 0
  95491. ** foreach row2 in t2 do
  95492. ** start:
  95493. ** ...
  95494. ** flag = 1
  95495. ** end
  95496. ** if flag==0 then
  95497. ** move the row2 cursor to a null row
  95498. ** goto start
  95499. ** fi
  95500. ** end
  95501. **
  95502. ** ORDER BY CLAUSE PROCESSING
  95503. **
  95504. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  95505. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  95506. ** if there is one. If there is no ORDER BY clause or if this routine
  95507. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  95508. */
  95509. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  95510. Parse *pParse, /* The parser context */
  95511. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  95512. Expr *pWhere, /* The WHERE clause */
  95513. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  95514. ExprList *pResultSet, /* Result set of the query */
  95515. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  95516. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  95517. ){
  95518. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  95519. int nTabList; /* Number of elements in pTabList */
  95520. WhereInfo *pWInfo; /* Will become the return value of this function */
  95521. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  95522. Bitmask notReady; /* Cursors that are not yet positioned */
  95523. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  95524. WhereMaskSet *pMaskSet; /* The expression mask set */
  95525. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  95526. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  95527. int ii; /* Loop counter */
  95528. sqlite3 *db; /* Database connection */
  95529. int rc; /* Return code */
  95530. /* Variable initialization */
  95531. db = pParse->db;
  95532. memset(&sWLB, 0, sizeof(sWLB));
  95533. sWLB.pOrderBy = pOrderBy;
  95534. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  95535. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  95536. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  95537. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  95538. }
  95539. /* The number of tables in the FROM clause is limited by the number of
  95540. ** bits in a Bitmask
  95541. */
  95542. testcase( pTabList->nSrc==BMS );
  95543. if( pTabList->nSrc>BMS ){
  95544. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  95545. return 0;
  95546. }
  95547. /* This function normally generates a nested loop for all tables in
  95548. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  95549. ** only generate code for the first table in pTabList and assume that
  95550. ** any cursors associated with subsequent tables are uninitialized.
  95551. */
  95552. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  95553. /* Allocate and initialize the WhereInfo structure that will become the
  95554. ** return value. A single allocation is used to store the WhereInfo
  95555. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  95556. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  95557. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  95558. ** some architectures. Hence the ROUND8() below.
  95559. */
  95560. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  95561. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  95562. if( db->mallocFailed ){
  95563. sqlite3DbFree(db, pWInfo);
  95564. pWInfo = 0;
  95565. goto whereBeginError;
  95566. }
  95567. pWInfo->nLevel = nTabList;
  95568. pWInfo->pParse = pParse;
  95569. pWInfo->pTabList = pTabList;
  95570. pWInfo->pOrderBy = pOrderBy;
  95571. pWInfo->pResultSet = pResultSet;
  95572. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  95573. pWInfo->wctrlFlags = wctrlFlags;
  95574. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  95575. pMaskSet = &pWInfo->sMaskSet;
  95576. sWLB.pWInfo = pWInfo;
  95577. sWLB.pWC = &pWInfo->sWC;
  95578. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  95579. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  95580. whereLoopInit(sWLB.pNew);
  95581. #ifdef SQLITE_DEBUG
  95582. sWLB.pNew->cId = '*';
  95583. #endif
  95584. /* Split the WHERE clause into separate subexpressions where each
  95585. ** subexpression is separated by an AND operator.
  95586. */
  95587. initMaskSet(pMaskSet);
  95588. whereClauseInit(&pWInfo->sWC, pWInfo);
  95589. sqlite3ExprCodeConstants(pParse, pWhere);
  95590. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  95591. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  95592. /* Special case: a WHERE clause that is constant. Evaluate the
  95593. ** expression and either jump over all of the code or fall thru.
  95594. */
  95595. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  95596. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  95597. pWhere = 0;
  95598. }
  95599. /* Special case: No FROM clause
  95600. */
  95601. if( nTabList==0 ){
  95602. if( pOrderBy ) pWInfo->bOBSat = 1;
  95603. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  95604. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95605. }
  95606. }
  95607. /* Assign a bit from the bitmask to every term in the FROM clause.
  95608. **
  95609. ** When assigning bitmask values to FROM clause cursors, it must be
  95610. ** the case that if X is the bitmask for the N-th FROM clause term then
  95611. ** the bitmask for all FROM clause terms to the left of the N-th term
  95612. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  95613. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  95614. ** of the join. Subtracting one from the right table bitmask gives a
  95615. ** bitmask for all tables to the left of the join. Knowing the bitmask
  95616. ** for all tables to the left of a left join is important. Ticket #3015.
  95617. **
  95618. ** Note that bitmasks are created for all pTabList->nSrc tables in
  95619. ** pTabList, not just the first nTabList tables. nTabList is normally
  95620. ** equal to pTabList->nSrc but might be shortened to 1 if the
  95621. ** WHERE_ONETABLE_ONLY flag is set.
  95622. */
  95623. for(ii=0; ii<pTabList->nSrc; ii++){
  95624. createMask(pMaskSet, pTabList->a[ii].iCursor);
  95625. }
  95626. #ifndef NDEBUG
  95627. {
  95628. Bitmask toTheLeft = 0;
  95629. for(ii=0; ii<pTabList->nSrc; ii++){
  95630. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  95631. assert( (m-1)==toTheLeft );
  95632. toTheLeft |= m;
  95633. }
  95634. }
  95635. #endif
  95636. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  95637. ** add new virtual terms onto the end of the WHERE clause. We do not
  95638. ** want to analyze these virtual terms, so start analyzing at the end
  95639. ** and work forward so that the added virtual terms are never processed.
  95640. */
  95641. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  95642. if( db->mallocFailed ){
  95643. goto whereBeginError;
  95644. }
  95645. /* If the ORDER BY (or GROUP BY) clause contains references to general
  95646. ** expressions, then we won't be able to satisfy it using indices, so
  95647. ** go ahead and disable it now.
  95648. */
  95649. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  95650. for(ii=0; ii<pOrderBy->nExpr; ii++){
  95651. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  95652. if( pExpr->op!=TK_COLUMN ){
  95653. pWInfo->pOrderBy = pOrderBy = 0;
  95654. break;
  95655. }else if( pExpr->iColumn<0 ){
  95656. break;
  95657. }
  95658. }
  95659. }
  95660. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  95661. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  95662. /* The DISTINCT marking is pointless. Ignore it. */
  95663. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95664. }else if( pOrderBy==0 ){
  95665. /* Try to ORDER BY the result set to make distinct processing easier */
  95666. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  95667. pWInfo->pOrderBy = pResultSet;
  95668. }
  95669. }
  95670. /* Construct the WhereLoop objects */
  95671. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  95672. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  95673. rc = whereLoopAddAll(&sWLB);
  95674. if( rc ) goto whereBeginError;
  95675. /* Display all of the WhereLoop objects if wheretrace is enabled */
  95676. #ifdef WHERETRACE_ENABLED
  95677. if( sqlite3WhereTrace ){
  95678. WhereLoop *p;
  95679. int i;
  95680. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  95681. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  95682. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  95683. p->cId = zLabel[i%sizeof(zLabel)];
  95684. whereLoopPrint(p, pTabList);
  95685. }
  95686. }
  95687. #endif
  95688. wherePathSolver(pWInfo, 0);
  95689. if( db->mallocFailed ) goto whereBeginError;
  95690. if( pWInfo->pOrderBy ){
  95691. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  95692. if( db->mallocFailed ) goto whereBeginError;
  95693. }
  95694. }
  95695. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  95696. pWInfo->revMask = (Bitmask)(-1);
  95697. }
  95698. if( pParse->nErr || NEVER(db->mallocFailed) ){
  95699. goto whereBeginError;
  95700. }
  95701. #ifdef WHERETRACE_ENABLED
  95702. if( sqlite3WhereTrace ){
  95703. int ii;
  95704. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  95705. if( pWInfo->bOBSat ){
  95706. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  95707. }
  95708. switch( pWInfo->eDistinct ){
  95709. case WHERE_DISTINCT_UNIQUE: {
  95710. sqlite3DebugPrintf(" DISTINCT=unique");
  95711. break;
  95712. }
  95713. case WHERE_DISTINCT_ORDERED: {
  95714. sqlite3DebugPrintf(" DISTINCT=ordered");
  95715. break;
  95716. }
  95717. case WHERE_DISTINCT_UNORDERED: {
  95718. sqlite3DebugPrintf(" DISTINCT=unordered");
  95719. break;
  95720. }
  95721. }
  95722. sqlite3DebugPrintf("\n");
  95723. for(ii=0; ii<pWInfo->nLevel; ii++){
  95724. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  95725. }
  95726. }
  95727. #endif
  95728. /* Attempt to omit tables from the join that do not effect the result */
  95729. if( pWInfo->nLevel>=2
  95730. && pResultSet!=0
  95731. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  95732. ){
  95733. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  95734. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  95735. while( pWInfo->nLevel>=2 ){
  95736. WhereTerm *pTerm, *pEnd;
  95737. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  95738. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  95739. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  95740. && (pLoop->wsFlags & WHERE_ONEROW)==0
  95741. ){
  95742. break;
  95743. }
  95744. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  95745. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  95746. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  95747. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  95748. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  95749. ){
  95750. break;
  95751. }
  95752. }
  95753. if( pTerm<pEnd ) break;
  95754. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  95755. pWInfo->nLevel--;
  95756. nTabList--;
  95757. }
  95758. }
  95759. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  95760. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  95761. /* If the caller is an UPDATE or DELETE statement that is requesting
  95762. ** to use a one-pass algorithm, determine if this is appropriate.
  95763. ** The one-pass algorithm only works if the WHERE clause constrains
  95764. ** the statement to update a single row.
  95765. */
  95766. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  95767. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  95768. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  95769. pWInfo->okOnePass = 1;
  95770. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  95771. }
  95772. /* Open all tables in the pTabList and any indices selected for
  95773. ** searching those tables.
  95774. */
  95775. notReady = ~(Bitmask)0;
  95776. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  95777. Table *pTab; /* Table to open */
  95778. int iDb; /* Index of database containing table/index */
  95779. struct SrcList_item *pTabItem;
  95780. pTabItem = &pTabList->a[pLevel->iFrom];
  95781. pTab = pTabItem->pTab;
  95782. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95783. pLoop = pLevel->pWLoop;
  95784. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  95785. /* Do nothing */
  95786. }else
  95787. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95788. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  95789. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  95790. int iCur = pTabItem->iCursor;
  95791. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  95792. }else if( IsVirtual(pTab) ){
  95793. /* noop */
  95794. }else
  95795. #endif
  95796. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  95797. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  95798. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  95799. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  95800. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  95801. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  95802. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  95803. Bitmask b = pTabItem->colUsed;
  95804. int n = 0;
  95805. for(; b; b=b>>1, n++){}
  95806. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  95807. SQLITE_INT_TO_PTR(n), P4_INT32);
  95808. assert( n<=pTab->nCol );
  95809. }
  95810. }else{
  95811. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95812. }
  95813. if( pLoop->wsFlags & WHERE_INDEXED ){
  95814. Index *pIx = pLoop->u.btree.pIndex;
  95815. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  95816. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  95817. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  95818. assert( pIx->pSchema==pTab->pSchema );
  95819. assert( iIndexCur>=0 );
  95820. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  95821. (char*)pKey, P4_KEYINFO_HANDOFF);
  95822. VdbeComment((v, "%s", pIx->zName));
  95823. }
  95824. sqlite3CodeVerifySchema(pParse, iDb);
  95825. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  95826. }
  95827. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  95828. if( db->mallocFailed ) goto whereBeginError;
  95829. /* Generate the code to do the search. Each iteration of the for
  95830. ** loop below generates code for a single nested loop of the VM
  95831. ** program.
  95832. */
  95833. notReady = ~(Bitmask)0;
  95834. for(ii=0; ii<nTabList; ii++){
  95835. pLevel = &pWInfo->a[ii];
  95836. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  95837. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  95838. constructAutomaticIndex(pParse, &pWInfo->sWC,
  95839. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  95840. if( db->mallocFailed ) goto whereBeginError;
  95841. }
  95842. #endif
  95843. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  95844. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  95845. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  95846. pWInfo->iContinue = pLevel->addrCont;
  95847. }
  95848. /* Done. */
  95849. return pWInfo;
  95850. /* Jump here if malloc fails */
  95851. whereBeginError:
  95852. if( pWInfo ){
  95853. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95854. whereInfoFree(db, pWInfo);
  95855. }
  95856. return 0;
  95857. }
  95858. /*
  95859. ** Generate the end of the WHERE loop. See comments on
  95860. ** sqlite3WhereBegin() for additional information.
  95861. */
  95862. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  95863. Parse *pParse = pWInfo->pParse;
  95864. Vdbe *v = pParse->pVdbe;
  95865. int i;
  95866. WhereLevel *pLevel;
  95867. WhereLoop *pLoop;
  95868. SrcList *pTabList = pWInfo->pTabList;
  95869. sqlite3 *db = pParse->db;
  95870. /* Generate loop termination code.
  95871. */
  95872. sqlite3ExprCacheClear(pParse);
  95873. for(i=pWInfo->nLevel-1; i>=0; i--){
  95874. pLevel = &pWInfo->a[i];
  95875. pLoop = pLevel->pWLoop;
  95876. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  95877. if( pLevel->op!=OP_Noop ){
  95878. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  95879. sqlite3VdbeChangeP5(v, pLevel->p5);
  95880. }
  95881. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  95882. struct InLoop *pIn;
  95883. int j;
  95884. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  95885. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  95886. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  95887. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  95888. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  95889. }
  95890. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  95891. }
  95892. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  95893. if( pLevel->iLeftJoin ){
  95894. int addr;
  95895. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  95896. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  95897. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  95898. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  95899. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  95900. }
  95901. if( pLoop->wsFlags & WHERE_INDEXED ){
  95902. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  95903. }
  95904. if( pLevel->op==OP_Return ){
  95905. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  95906. }else{
  95907. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  95908. }
  95909. sqlite3VdbeJumpHere(v, addr);
  95910. }
  95911. }
  95912. /* The "break" point is here, just past the end of the outer loop.
  95913. ** Set it.
  95914. */
  95915. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  95916. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  95917. */
  95918. assert( pWInfo->nLevel<=pTabList->nSrc );
  95919. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  95920. Index *pIdx = 0;
  95921. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  95922. Table *pTab = pTabItem->pTab;
  95923. assert( pTab!=0 );
  95924. pLoop = pLevel->pWLoop;
  95925. if( (pTab->tabFlags & TF_Ephemeral)==0
  95926. && pTab->pSelect==0
  95927. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  95928. ){
  95929. int ws = pLoop->wsFlags;
  95930. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  95931. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  95932. }
  95933. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  95934. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  95935. }
  95936. }
  95937. /* If this scan uses an index, make VDBE code substitutions to read data
  95938. ** from the index instead of from the table where possible. In some cases
  95939. ** this optimization prevents the table from ever being read, which can
  95940. ** yield a significant performance boost.
  95941. **
  95942. ** Calls to the code generator in between sqlite3WhereBegin and
  95943. ** sqlite3WhereEnd will have created code that references the table
  95944. ** directly. This loop scans all that code looking for opcodes
  95945. ** that reference the table and converts them into opcodes that
  95946. ** reference the index.
  95947. */
  95948. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  95949. pIdx = pLoop->u.btree.pIndex;
  95950. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  95951. pIdx = pLevel->u.pCovidx;
  95952. }
  95953. if( pIdx && !db->mallocFailed ){
  95954. int k, j, last;
  95955. VdbeOp *pOp;
  95956. last = sqlite3VdbeCurrentAddr(v);
  95957. k = pLevel->addrBody;
  95958. pOp = sqlite3VdbeGetOp(v, k);
  95959. for(; k<last; k++, pOp++){
  95960. if( pOp->p1!=pLevel->iTabCur ) continue;
  95961. if( pOp->opcode==OP_Column ){
  95962. for(j=0; j<pIdx->nColumn; j++){
  95963. if( pOp->p2==pIdx->aiColumn[j] ){
  95964. pOp->p2 = j;
  95965. pOp->p1 = pLevel->iIdxCur;
  95966. break;
  95967. }
  95968. }
  95969. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  95970. }else if( pOp->opcode==OP_Rowid ){
  95971. pOp->p1 = pLevel->iIdxCur;
  95972. pOp->opcode = OP_IdxRowid;
  95973. }
  95974. }
  95975. }
  95976. }
  95977. /* Final cleanup
  95978. */
  95979. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95980. whereInfoFree(db, pWInfo);
  95981. return;
  95982. }
  95983. /************** End of where.c ***********************************************/
  95984. /************** Begin file parse.c *******************************************/
  95985. /* Driver template for the LEMON parser generator.
  95986. ** The author disclaims copyright to this source code.
  95987. **
  95988. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  95989. ** The only modifications are the addition of a couple of NEVER()
  95990. ** macros to disable tests that are needed in the case of a general
  95991. ** LALR(1) grammar but which are always false in the
  95992. ** specific grammar used by SQLite.
  95993. */
  95994. /* First off, code is included that follows the "include" declaration
  95995. ** in the input grammar file. */
  95996. /* #include <stdio.h> */
  95997. /*
  95998. ** Disable all error recovery processing in the parser push-down
  95999. ** automaton.
  96000. */
  96001. #define YYNOERRORRECOVERY 1
  96002. /*
  96003. ** Make yytestcase() the same as testcase()
  96004. */
  96005. #define yytestcase(X) testcase(X)
  96006. /*
  96007. ** An instance of this structure holds information about the
  96008. ** LIMIT clause of a SELECT statement.
  96009. */
  96010. struct LimitVal {
  96011. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  96012. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  96013. };
  96014. /*
  96015. ** An instance of this structure is used to store the LIKE,
  96016. ** GLOB, NOT LIKE, and NOT GLOB operators.
  96017. */
  96018. struct LikeOp {
  96019. Token eOperator; /* "like" or "glob" or "regexp" */
  96020. int bNot; /* True if the NOT keyword is present */
  96021. };
  96022. /*
  96023. ** An instance of the following structure describes the event of a
  96024. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  96025. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  96026. **
  96027. ** UPDATE ON (a,b,c)
  96028. **
  96029. ** Then the "b" IdList records the list "a,b,c".
  96030. */
  96031. struct TrigEvent { int a; IdList * b; };
  96032. /*
  96033. ** An instance of this structure holds the ATTACH key and the key type.
  96034. */
  96035. struct AttachKey { int type; Token key; };
  96036. /*
  96037. ** One or more VALUES claues
  96038. */
  96039. struct ValueList {
  96040. ExprList *pList;
  96041. Select *pSelect;
  96042. };
  96043. /* This is a utility routine used to set the ExprSpan.zStart and
  96044. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  96045. ** range of text beginning with pStart and going to the end of pEnd.
  96046. */
  96047. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  96048. pOut->zStart = pStart->z;
  96049. pOut->zEnd = &pEnd->z[pEnd->n];
  96050. }
  96051. /* Construct a new Expr object from a single identifier. Use the
  96052. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  96053. ** that created the expression.
  96054. */
  96055. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  96056. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  96057. pOut->zStart = pValue->z;
  96058. pOut->zEnd = &pValue->z[pValue->n];
  96059. }
  96060. /* This routine constructs a binary expression node out of two ExprSpan
  96061. ** objects and uses the result to populate a new ExprSpan object.
  96062. */
  96063. static void spanBinaryExpr(
  96064. ExprSpan *pOut, /* Write the result here */
  96065. Parse *pParse, /* The parsing context. Errors accumulate here */
  96066. int op, /* The binary operation */
  96067. ExprSpan *pLeft, /* The left operand */
  96068. ExprSpan *pRight /* The right operand */
  96069. ){
  96070. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  96071. pOut->zStart = pLeft->zStart;
  96072. pOut->zEnd = pRight->zEnd;
  96073. }
  96074. /* Construct an expression node for a unary postfix operator
  96075. */
  96076. static void spanUnaryPostfix(
  96077. ExprSpan *pOut, /* Write the new expression node here */
  96078. Parse *pParse, /* Parsing context to record errors */
  96079. int op, /* The operator */
  96080. ExprSpan *pOperand, /* The operand */
  96081. Token *pPostOp /* The operand token for setting the span */
  96082. ){
  96083. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  96084. pOut->zStart = pOperand->zStart;
  96085. pOut->zEnd = &pPostOp->z[pPostOp->n];
  96086. }
  96087. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  96088. ** unary TK_ISNULL or TK_NOTNULL expression. */
  96089. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  96090. sqlite3 *db = pParse->db;
  96091. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  96092. pA->op = (u8)op;
  96093. sqlite3ExprDelete(db, pA->pRight);
  96094. pA->pRight = 0;
  96095. }
  96096. }
  96097. /* Construct an expression node for a unary prefix operator
  96098. */
  96099. static void spanUnaryPrefix(
  96100. ExprSpan *pOut, /* Write the new expression node here */
  96101. Parse *pParse, /* Parsing context to record errors */
  96102. int op, /* The operator */
  96103. ExprSpan *pOperand, /* The operand */
  96104. Token *pPreOp /* The operand token for setting the span */
  96105. ){
  96106. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  96107. pOut->zStart = pPreOp->z;
  96108. pOut->zEnd = pOperand->zEnd;
  96109. }
  96110. /* Next is all token values, in a form suitable for use by makeheaders.
  96111. ** This section will be null unless lemon is run with the -m switch.
  96112. */
  96113. /*
  96114. ** These constants (all generated automatically by the parser generator)
  96115. ** specify the various kinds of tokens (terminals) that the parser
  96116. ** understands.
  96117. **
  96118. ** Each symbol here is a terminal symbol in the grammar.
  96119. */
  96120. /* Make sure the INTERFACE macro is defined.
  96121. */
  96122. #ifndef INTERFACE
  96123. # define INTERFACE 1
  96124. #endif
  96125. /* The next thing included is series of defines which control
  96126. ** various aspects of the generated parser.
  96127. ** YYCODETYPE is the data type used for storing terminal
  96128. ** and nonterminal numbers. "unsigned char" is
  96129. ** used if there are fewer than 250 terminals
  96130. ** and nonterminals. "int" is used otherwise.
  96131. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  96132. ** to no legal terminal or nonterminal number. This
  96133. ** number is used to fill in empty slots of the hash
  96134. ** table.
  96135. ** YYFALLBACK If defined, this indicates that one or more tokens
  96136. ** have fall-back values which should be used if the
  96137. ** original value of the token will not parse.
  96138. ** YYACTIONTYPE is the data type used for storing terminal
  96139. ** and nonterminal numbers. "unsigned char" is
  96140. ** used if there are fewer than 250 rules and
  96141. ** states combined. "int" is used otherwise.
  96142. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  96143. ** directly to the parser from the tokenizer.
  96144. ** YYMINORTYPE is the data type used for all minor tokens.
  96145. ** This is typically a union of many types, one of
  96146. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  96147. ** for base tokens is called "yy0".
  96148. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  96149. ** zero the stack is dynamically sized using realloc()
  96150. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  96151. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  96152. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  96153. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  96154. ** YYNSTATE the combined number of states.
  96155. ** YYNRULE the number of rules in the grammar
  96156. ** YYERRORSYMBOL is the code number of the error symbol. If not
  96157. ** defined, then do no error processing.
  96158. */
  96159. #define YYCODETYPE unsigned char
  96160. #define YYNOCODE 251
  96161. #define YYACTIONTYPE unsigned short int
  96162. #define YYWILDCARD 67
  96163. #define sqlite3ParserTOKENTYPE Token
  96164. typedef union {
  96165. int yyinit;
  96166. sqlite3ParserTOKENTYPE yy0;
  96167. struct LimitVal yy64;
  96168. Expr* yy122;
  96169. Select* yy159;
  96170. IdList* yy180;
  96171. struct {int value; int mask;} yy207;
  96172. u8 yy258;
  96173. u16 yy305;
  96174. struct LikeOp yy318;
  96175. TriggerStep* yy327;
  96176. ExprSpan yy342;
  96177. SrcList* yy347;
  96178. int yy392;
  96179. struct TrigEvent yy410;
  96180. ExprList* yy442;
  96181. struct ValueList yy487;
  96182. } YYMINORTYPE;
  96183. #ifndef YYSTACKDEPTH
  96184. #define YYSTACKDEPTH 100
  96185. #endif
  96186. #define sqlite3ParserARG_SDECL Parse *pParse;
  96187. #define sqlite3ParserARG_PDECL ,Parse *pParse
  96188. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  96189. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  96190. #define YYNSTATE 628
  96191. #define YYNRULE 327
  96192. #define YYFALLBACK 1
  96193. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  96194. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  96195. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  96196. /* The yyzerominor constant is used to initialize instances of
  96197. ** YYMINORTYPE objects to zero. */
  96198. static const YYMINORTYPE yyzerominor = { 0 };
  96199. /* Define the yytestcase() macro to be a no-op if is not already defined
  96200. ** otherwise.
  96201. **
  96202. ** Applications can choose to define yytestcase() in the %include section
  96203. ** to a macro that can assist in verifying code coverage. For production
  96204. ** code the yytestcase() macro should be turned off. But it is useful
  96205. ** for testing.
  96206. */
  96207. #ifndef yytestcase
  96208. # define yytestcase(X)
  96209. #endif
  96210. /* Next are the tables used to determine what action to take based on the
  96211. ** current state and lookahead token. These tables are used to implement
  96212. ** functions that take a state number and lookahead value and return an
  96213. ** action integer.
  96214. **
  96215. ** Suppose the action integer is N. Then the action is determined as
  96216. ** follows
  96217. **
  96218. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  96219. ** token onto the stack and goto state N.
  96220. **
  96221. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  96222. **
  96223. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  96224. **
  96225. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  96226. **
  96227. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  96228. ** slots in the yy_action[] table.
  96229. **
  96230. ** The action table is constructed as a single large table named yy_action[].
  96231. ** Given state S and lookahead X, the action is computed as
  96232. **
  96233. ** yy_action[ yy_shift_ofst[S] + X ]
  96234. **
  96235. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  96236. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  96237. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  96238. ** and that yy_default[S] should be used instead.
  96239. **
  96240. ** The formula above is for computing the action when the lookahead is
  96241. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  96242. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  96243. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  96244. ** YY_SHIFT_USE_DFLT.
  96245. **
  96246. ** The following are the tables generated in this section:
  96247. **
  96248. ** yy_action[] A single table containing all actions.
  96249. ** yy_lookahead[] A table containing the lookahead for each entry in
  96250. ** yy_action. Used to detect hash collisions.
  96251. ** yy_shift_ofst[] For each state, the offset into yy_action for
  96252. ** shifting terminals.
  96253. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  96254. ** shifting non-terminals after a reduce.
  96255. ** yy_default[] Default action for each state.
  96256. */
  96257. #define YY_ACTTAB_COUNT (1564)
  96258. static const YYACTIONTYPE yy_action[] = {
  96259. /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
  96260. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  96261. /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
  96262. /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
  96263. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
  96264. /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96265. /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
  96266. /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
  96267. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96268. /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
  96269. /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
  96270. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  96271. /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
  96272. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  96273. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
  96274. /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
  96275. /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
  96276. /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
  96277. /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
  96278. /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
  96279. /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96280. /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96281. /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
  96282. /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
  96283. /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
  96284. /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
  96285. /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
  96286. /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  96287. /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
  96288. /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
  96289. /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
  96290. /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
  96291. /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
  96292. /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
  96293. /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
  96294. /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
  96295. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96296. /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
  96297. /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
  96298. /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
  96299. /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
  96300. /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
  96301. /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96302. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  96303. /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
  96304. /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
  96305. /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
  96306. /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
  96307. /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
  96308. /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
  96309. /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
  96310. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
  96311. /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
  96312. /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
  96313. /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
  96314. /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
  96315. /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
  96316. /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96317. /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96318. /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
  96319. /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
  96320. /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
  96321. /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
  96322. /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
  96323. /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  96324. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  96325. /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
  96326. /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
  96327. /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
  96328. /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
  96329. /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
  96330. /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
  96331. /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  96332. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96333. /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
  96334. /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
  96335. /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
  96336. /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
  96337. /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
  96338. /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96339. /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
  96340. /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
  96341. /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
  96342. /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
  96343. /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
  96344. /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
  96345. /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
  96346. /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
  96347. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
  96348. /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
  96349. /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
  96350. /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
  96351. /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
  96352. /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
  96353. /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96354. /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96355. /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
  96356. /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
  96357. /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
  96358. /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
  96359. /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
  96360. /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
  96361. /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
  96362. /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
  96363. /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
  96364. /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
  96365. /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
  96366. /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
  96367. /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
  96368. /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  96369. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96370. /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
  96371. /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
  96372. /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
  96373. /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
  96374. /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
  96375. /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96376. /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
  96377. /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
  96378. /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
  96379. /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
  96380. /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
  96381. /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
  96382. /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
  96383. /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
  96384. /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
  96385. /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
  96386. /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
  96387. /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
  96388. /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
  96389. /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
  96390. /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
  96391. /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
  96392. /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
  96393. /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
  96394. /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
  96395. /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
  96396. /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
  96397. /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
  96398. /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
  96399. /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
  96400. /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
  96401. /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
  96402. /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
  96403. /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
  96404. /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
  96405. /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
  96406. /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
  96407. /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
  96408. /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
  96409. /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
  96410. /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
  96411. /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
  96412. /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
  96413. /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
  96414. /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
  96415. /* 1560 */ 400, 499, 523, 233,
  96416. };
  96417. static const YYCODETYPE yy_lookahead[] = {
  96418. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  96419. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  96420. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  96421. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  96422. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  96423. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96424. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  96425. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  96426. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96427. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  96428. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  96429. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  96430. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  96431. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  96432. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  96433. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  96434. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  96435. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  96436. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  96437. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  96438. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96439. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96440. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  96441. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  96442. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  96443. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  96444. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  96445. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96446. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  96447. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  96448. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  96449. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  96450. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  96451. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  96452. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  96453. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  96454. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96455. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  96456. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  96457. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  96458. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  96459. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  96460. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96461. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  96462. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  96463. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  96464. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  96465. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  96466. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  96467. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  96468. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  96469. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  96470. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  96471. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  96472. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  96473. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  96474. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  96475. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96476. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96477. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  96478. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  96479. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  96480. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  96481. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  96482. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96483. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  96484. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  96485. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  96486. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  96487. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  96488. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  96489. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  96490. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  96491. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96492. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  96493. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  96494. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  96495. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  96496. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  96497. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96498. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  96499. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  96500. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  96501. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  96502. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  96503. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  96504. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  96505. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  96506. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  96507. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  96508. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  96509. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  96510. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  96511. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  96512. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96513. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96514. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  96515. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  96516. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  96517. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  96518. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  96519. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96520. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  96521. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  96522. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  96523. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  96524. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  96525. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  96526. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  96527. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  96528. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96529. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  96530. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  96531. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  96532. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  96533. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  96534. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96535. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  96536. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  96537. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  96538. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  96539. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  96540. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  96541. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  96542. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  96543. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  96544. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  96545. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  96546. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  96547. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  96548. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  96549. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  96550. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  96551. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  96552. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  96553. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  96554. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  96555. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  96556. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  96557. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  96558. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  96559. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  96560. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  96561. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  96562. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  96563. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  96564. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  96565. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  96566. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  96567. /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
  96568. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  96569. /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
  96570. /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
  96571. /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
  96572. /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
  96573. /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
  96574. /* 1560 */ 191, 182, 173, 92,
  96575. };
  96576. #define YY_SHIFT_USE_DFLT (-70)
  96577. #define YY_SHIFT_COUNT (417)
  96578. #define YY_SHIFT_MIN (-69)
  96579. #define YY_SHIFT_MAX (1487)
  96580. static const short yy_shift_ofst[] = {
  96581. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  96582. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  96583. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96584. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96585. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  96586. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96587. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  96588. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  96589. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  96590. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  96591. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  96592. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96593. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  96594. /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
  96595. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  96596. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96597. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96598. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96599. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  96600. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  96601. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  96602. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  96603. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  96604. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
  96605. /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
  96606. /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
  96607. /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
  96608. /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
  96609. /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
  96610. /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
  96611. /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
  96612. /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
  96613. /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
  96614. /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
  96615. /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
  96616. /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
  96617. /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
  96618. /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
  96619. /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
  96620. /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
  96621. /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
  96622. /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
  96623. };
  96624. #define YY_REDUCE_USE_DFLT (-169)
  96625. #define YY_REDUCE_COUNT (309)
  96626. #define YY_REDUCE_MIN (-168)
  96627. #define YY_REDUCE_MAX (1397)
  96628. static const short yy_reduce_ofst[] = {
  96629. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  96630. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  96631. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  96632. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  96633. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  96634. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  96635. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  96636. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96637. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96638. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96639. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  96640. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  96641. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  96642. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  96643. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  96644. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  96645. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  96646. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  96647. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  96648. /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
  96649. /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
  96650. /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
  96651. /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
  96652. /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
  96653. /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
  96654. /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
  96655. /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
  96656. /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
  96657. /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
  96658. /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
  96659. /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  96660. };
  96661. static const YYACTIONTYPE yy_default[] = {
  96662. /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
  96663. /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
  96664. /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96665. /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96666. /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96667. /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96668. /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
  96669. /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
  96670. /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
  96671. /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
  96672. /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
  96673. /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96674. /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
  96675. /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
  96676. /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96677. /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
  96678. /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96679. /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96680. /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
  96681. /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96682. /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
  96683. /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
  96684. /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
  96685. /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
  96686. /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
  96687. /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
  96688. /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
  96689. /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
  96690. /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
  96691. /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
  96692. /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
  96693. /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
  96694. /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96695. /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
  96696. /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96697. /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
  96698. /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
  96699. /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96700. /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96701. /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
  96702. /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
  96703. /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
  96704. /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
  96705. /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
  96706. /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
  96707. /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
  96708. /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
  96709. /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
  96710. /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
  96711. /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
  96712. /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
  96713. /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
  96714. /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
  96715. /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
  96716. /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
  96717. /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
  96718. /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
  96719. /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
  96720. /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
  96721. /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
  96722. /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
  96723. /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
  96724. /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
  96725. };
  96726. /* The next table maps tokens into fallback tokens. If a construct
  96727. ** like the following:
  96728. **
  96729. ** %fallback ID X Y Z.
  96730. **
  96731. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  96732. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  96733. ** but it does not parse, the type of the token is changed to ID and
  96734. ** the parse is retried before an error is thrown.
  96735. */
  96736. #ifdef YYFALLBACK
  96737. static const YYCODETYPE yyFallback[] = {
  96738. 0, /* $ => nothing */
  96739. 0, /* SEMI => nothing */
  96740. 26, /* EXPLAIN => ID */
  96741. 26, /* QUERY => ID */
  96742. 26, /* PLAN => ID */
  96743. 26, /* BEGIN => ID */
  96744. 0, /* TRANSACTION => nothing */
  96745. 26, /* DEFERRED => ID */
  96746. 26, /* IMMEDIATE => ID */
  96747. 26, /* EXCLUSIVE => ID */
  96748. 0, /* COMMIT => nothing */
  96749. 26, /* END => ID */
  96750. 26, /* ROLLBACK => ID */
  96751. 26, /* SAVEPOINT => ID */
  96752. 26, /* RELEASE => ID */
  96753. 0, /* TO => nothing */
  96754. 0, /* TABLE => nothing */
  96755. 0, /* CREATE => nothing */
  96756. 26, /* IF => ID */
  96757. 0, /* NOT => nothing */
  96758. 0, /* EXISTS => nothing */
  96759. 26, /* TEMP => ID */
  96760. 0, /* LP => nothing */
  96761. 0, /* RP => nothing */
  96762. 0, /* AS => nothing */
  96763. 0, /* COMMA => nothing */
  96764. 0, /* ID => nothing */
  96765. 0, /* INDEXED => nothing */
  96766. 26, /* ABORT => ID */
  96767. 26, /* ACTION => ID */
  96768. 26, /* AFTER => ID */
  96769. 26, /* ANALYZE => ID */
  96770. 26, /* ASC => ID */
  96771. 26, /* ATTACH => ID */
  96772. 26, /* BEFORE => ID */
  96773. 26, /* BY => ID */
  96774. 26, /* CASCADE => ID */
  96775. 26, /* CAST => ID */
  96776. 26, /* COLUMNKW => ID */
  96777. 26, /* CONFLICT => ID */
  96778. 26, /* DATABASE => ID */
  96779. 26, /* DESC => ID */
  96780. 26, /* DETACH => ID */
  96781. 26, /* EACH => ID */
  96782. 26, /* FAIL => ID */
  96783. 26, /* FOR => ID */
  96784. 26, /* IGNORE => ID */
  96785. 26, /* INITIALLY => ID */
  96786. 26, /* INSTEAD => ID */
  96787. 26, /* LIKE_KW => ID */
  96788. 26, /* MATCH => ID */
  96789. 26, /* NO => ID */
  96790. 26, /* KEY => ID */
  96791. 26, /* OF => ID */
  96792. 26, /* OFFSET => ID */
  96793. 26, /* PRAGMA => ID */
  96794. 26, /* RAISE => ID */
  96795. 26, /* REPLACE => ID */
  96796. 26, /* RESTRICT => ID */
  96797. 26, /* ROW => ID */
  96798. 26, /* TRIGGER => ID */
  96799. 26, /* VACUUM => ID */
  96800. 26, /* VIEW => ID */
  96801. 26, /* VIRTUAL => ID */
  96802. 26, /* REINDEX => ID */
  96803. 26, /* RENAME => ID */
  96804. 26, /* CTIME_KW => ID */
  96805. };
  96806. #endif /* YYFALLBACK */
  96807. /* The following structure represents a single element of the
  96808. ** parser's stack. Information stored includes:
  96809. **
  96810. ** + The state number for the parser at this level of the stack.
  96811. **
  96812. ** + The value of the token stored at this level of the stack.
  96813. ** (In other words, the "major" token.)
  96814. **
  96815. ** + The semantic value stored at this level of the stack. This is
  96816. ** the information used by the action routines in the grammar.
  96817. ** It is sometimes called the "minor" token.
  96818. */
  96819. struct yyStackEntry {
  96820. YYACTIONTYPE stateno; /* The state-number */
  96821. YYCODETYPE major; /* The major token value. This is the code
  96822. ** number for the token at this stack level */
  96823. YYMINORTYPE minor; /* The user-supplied minor token value. This
  96824. ** is the value of the token */
  96825. };
  96826. typedef struct yyStackEntry yyStackEntry;
  96827. /* The state of the parser is completely contained in an instance of
  96828. ** the following structure */
  96829. struct yyParser {
  96830. int yyidx; /* Index of top element in stack */
  96831. #ifdef YYTRACKMAXSTACKDEPTH
  96832. int yyidxMax; /* Maximum value of yyidx */
  96833. #endif
  96834. int yyerrcnt; /* Shifts left before out of the error */
  96835. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  96836. #if YYSTACKDEPTH<=0
  96837. int yystksz; /* Current side of the stack */
  96838. yyStackEntry *yystack; /* The parser's stack */
  96839. #else
  96840. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  96841. #endif
  96842. };
  96843. typedef struct yyParser yyParser;
  96844. #ifndef NDEBUG
  96845. /* #include <stdio.h> */
  96846. static FILE *yyTraceFILE = 0;
  96847. static char *yyTracePrompt = 0;
  96848. #endif /* NDEBUG */
  96849. #ifndef NDEBUG
  96850. /*
  96851. ** Turn parser tracing on by giving a stream to which to write the trace
  96852. ** and a prompt to preface each trace message. Tracing is turned off
  96853. ** by making either argument NULL
  96854. **
  96855. ** Inputs:
  96856. ** <ul>
  96857. ** <li> A FILE* to which trace output should be written.
  96858. ** If NULL, then tracing is turned off.
  96859. ** <li> A prefix string written at the beginning of every
  96860. ** line of trace output. If NULL, then tracing is
  96861. ** turned off.
  96862. ** </ul>
  96863. **
  96864. ** Outputs:
  96865. ** None.
  96866. */
  96867. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  96868. yyTraceFILE = TraceFILE;
  96869. yyTracePrompt = zTracePrompt;
  96870. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  96871. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  96872. }
  96873. #endif /* NDEBUG */
  96874. #ifndef NDEBUG
  96875. /* For tracing shifts, the names of all terminals and nonterminals
  96876. ** are required. The following table supplies these names */
  96877. static const char *const yyTokenName[] = {
  96878. "$", "SEMI", "EXPLAIN", "QUERY",
  96879. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  96880. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  96881. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  96882. "TABLE", "CREATE", "IF", "NOT",
  96883. "EXISTS", "TEMP", "LP", "RP",
  96884. "AS", "COMMA", "ID", "INDEXED",
  96885. "ABORT", "ACTION", "AFTER", "ANALYZE",
  96886. "ASC", "ATTACH", "BEFORE", "BY",
  96887. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  96888. "DATABASE", "DESC", "DETACH", "EACH",
  96889. "FAIL", "FOR", "IGNORE", "INITIALLY",
  96890. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  96891. "KEY", "OF", "OFFSET", "PRAGMA",
  96892. "RAISE", "REPLACE", "RESTRICT", "ROW",
  96893. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  96894. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  96895. "OR", "AND", "IS", "BETWEEN",
  96896. "IN", "ISNULL", "NOTNULL", "NE",
  96897. "EQ", "GT", "LE", "LT",
  96898. "GE", "ESCAPE", "BITAND", "BITOR",
  96899. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  96900. "STAR", "SLASH", "REM", "CONCAT",
  96901. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  96902. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  96903. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  96904. "ON", "INSERT", "DELETE", "UPDATE",
  96905. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  96906. "UNION", "ALL", "EXCEPT", "INTERSECT",
  96907. "SELECT", "DISTINCT", "DOT", "FROM",
  96908. "JOIN", "USING", "ORDER", "GROUP",
  96909. "HAVING", "LIMIT", "WHERE", "INTO",
  96910. "VALUES", "INTEGER", "FLOAT", "BLOB",
  96911. "REGISTER", "VARIABLE", "CASE", "WHEN",
  96912. "THEN", "ELSE", "INDEX", "ALTER",
  96913. "ADD", "error", "input", "cmdlist",
  96914. "ecmd", "explain", "cmdx", "cmd",
  96915. "transtype", "trans_opt", "nm", "savepoint_opt",
  96916. "create_table", "create_table_args", "createkw", "temp",
  96917. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  96918. "select", "column", "columnid", "type",
  96919. "carglist", "id", "ids", "typetoken",
  96920. "typename", "signed", "plus_num", "minus_num",
  96921. "ccons", "term", "expr", "onconf",
  96922. "sortorder", "autoinc", "idxlist_opt", "refargs",
  96923. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  96924. "conslist", "tconscomma", "tcons", "idxlist",
  96925. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  96926. "ifexists", "fullname", "oneselect", "multiselect_op",
  96927. "distinct", "selcollist", "from", "where_opt",
  96928. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  96929. "sclp", "as", "seltablist", "stl_prefix",
  96930. "joinop", "indexed_opt", "on_opt", "using_opt",
  96931. "joinop2", "inscollist", "sortlist", "nexprlist",
  96932. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  96933. "exprlist", "likeop", "between_op", "in_op",
  96934. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  96935. "collate", "nmnum", "number", "trigger_decl",
  96936. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  96937. "when_clause", "trigger_cmd", "trnm", "tridxby",
  96938. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  96939. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  96940. "lp", "anylist",
  96941. };
  96942. #endif /* NDEBUG */
  96943. #ifndef NDEBUG
  96944. /* For tracing reduce actions, the names of all rules are required.
  96945. */
  96946. static const char *const yyRuleName[] = {
  96947. /* 0 */ "input ::= cmdlist",
  96948. /* 1 */ "cmdlist ::= cmdlist ecmd",
  96949. /* 2 */ "cmdlist ::= ecmd",
  96950. /* 3 */ "ecmd ::= SEMI",
  96951. /* 4 */ "ecmd ::= explain cmdx SEMI",
  96952. /* 5 */ "explain ::=",
  96953. /* 6 */ "explain ::= EXPLAIN",
  96954. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  96955. /* 8 */ "cmdx ::= cmd",
  96956. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  96957. /* 10 */ "trans_opt ::=",
  96958. /* 11 */ "trans_opt ::= TRANSACTION",
  96959. /* 12 */ "trans_opt ::= TRANSACTION nm",
  96960. /* 13 */ "transtype ::=",
  96961. /* 14 */ "transtype ::= DEFERRED",
  96962. /* 15 */ "transtype ::= IMMEDIATE",
  96963. /* 16 */ "transtype ::= EXCLUSIVE",
  96964. /* 17 */ "cmd ::= COMMIT trans_opt",
  96965. /* 18 */ "cmd ::= END trans_opt",
  96966. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  96967. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  96968. /* 21 */ "savepoint_opt ::=",
  96969. /* 22 */ "cmd ::= SAVEPOINT nm",
  96970. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  96971. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  96972. /* 25 */ "cmd ::= create_table create_table_args",
  96973. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  96974. /* 27 */ "createkw ::= CREATE",
  96975. /* 28 */ "ifnotexists ::=",
  96976. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  96977. /* 30 */ "temp ::= TEMP",
  96978. /* 31 */ "temp ::=",
  96979. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  96980. /* 33 */ "create_table_args ::= AS select",
  96981. /* 34 */ "columnlist ::= columnlist COMMA column",
  96982. /* 35 */ "columnlist ::= column",
  96983. /* 36 */ "column ::= columnid type carglist",
  96984. /* 37 */ "columnid ::= nm",
  96985. /* 38 */ "id ::= ID",
  96986. /* 39 */ "id ::= INDEXED",
  96987. /* 40 */ "ids ::= ID|STRING",
  96988. /* 41 */ "nm ::= id",
  96989. /* 42 */ "nm ::= STRING",
  96990. /* 43 */ "nm ::= JOIN_KW",
  96991. /* 44 */ "type ::=",
  96992. /* 45 */ "type ::= typetoken",
  96993. /* 46 */ "typetoken ::= typename",
  96994. /* 47 */ "typetoken ::= typename LP signed RP",
  96995. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  96996. /* 49 */ "typename ::= ids",
  96997. /* 50 */ "typename ::= typename ids",
  96998. /* 51 */ "signed ::= plus_num",
  96999. /* 52 */ "signed ::= minus_num",
  97000. /* 53 */ "carglist ::= carglist ccons",
  97001. /* 54 */ "carglist ::=",
  97002. /* 55 */ "ccons ::= CONSTRAINT nm",
  97003. /* 56 */ "ccons ::= DEFAULT term",
  97004. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  97005. /* 58 */ "ccons ::= DEFAULT PLUS term",
  97006. /* 59 */ "ccons ::= DEFAULT MINUS term",
  97007. /* 60 */ "ccons ::= DEFAULT id",
  97008. /* 61 */ "ccons ::= NULL onconf",
  97009. /* 62 */ "ccons ::= NOT NULL onconf",
  97010. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  97011. /* 64 */ "ccons ::= UNIQUE onconf",
  97012. /* 65 */ "ccons ::= CHECK LP expr RP",
  97013. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  97014. /* 67 */ "ccons ::= defer_subclause",
  97015. /* 68 */ "ccons ::= COLLATE ids",
  97016. /* 69 */ "autoinc ::=",
  97017. /* 70 */ "autoinc ::= AUTOINCR",
  97018. /* 71 */ "refargs ::=",
  97019. /* 72 */ "refargs ::= refargs refarg",
  97020. /* 73 */ "refarg ::= MATCH nm",
  97021. /* 74 */ "refarg ::= ON INSERT refact",
  97022. /* 75 */ "refarg ::= ON DELETE refact",
  97023. /* 76 */ "refarg ::= ON UPDATE refact",
  97024. /* 77 */ "refact ::= SET NULL",
  97025. /* 78 */ "refact ::= SET DEFAULT",
  97026. /* 79 */ "refact ::= CASCADE",
  97027. /* 80 */ "refact ::= RESTRICT",
  97028. /* 81 */ "refact ::= NO ACTION",
  97029. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  97030. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  97031. /* 84 */ "init_deferred_pred_opt ::=",
  97032. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  97033. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  97034. /* 87 */ "conslist_opt ::=",
  97035. /* 88 */ "conslist_opt ::= COMMA conslist",
  97036. /* 89 */ "conslist ::= conslist tconscomma tcons",
  97037. /* 90 */ "conslist ::= tcons",
  97038. /* 91 */ "tconscomma ::= COMMA",
  97039. /* 92 */ "tconscomma ::=",
  97040. /* 93 */ "tcons ::= CONSTRAINT nm",
  97041. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  97042. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  97043. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  97044. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  97045. /* 98 */ "defer_subclause_opt ::=",
  97046. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  97047. /* 100 */ "onconf ::=",
  97048. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  97049. /* 102 */ "orconf ::=",
  97050. /* 103 */ "orconf ::= OR resolvetype",
  97051. /* 104 */ "resolvetype ::= raisetype",
  97052. /* 105 */ "resolvetype ::= IGNORE",
  97053. /* 106 */ "resolvetype ::= REPLACE",
  97054. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  97055. /* 108 */ "ifexists ::= IF EXISTS",
  97056. /* 109 */ "ifexists ::=",
  97057. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  97058. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  97059. /* 112 */ "cmd ::= select",
  97060. /* 113 */ "select ::= oneselect",
  97061. /* 114 */ "select ::= select multiselect_op oneselect",
  97062. /* 115 */ "multiselect_op ::= UNION",
  97063. /* 116 */ "multiselect_op ::= UNION ALL",
  97064. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  97065. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  97066. /* 119 */ "distinct ::= DISTINCT",
  97067. /* 120 */ "distinct ::= ALL",
  97068. /* 121 */ "distinct ::=",
  97069. /* 122 */ "sclp ::= selcollist COMMA",
  97070. /* 123 */ "sclp ::=",
  97071. /* 124 */ "selcollist ::= sclp expr as",
  97072. /* 125 */ "selcollist ::= sclp STAR",
  97073. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  97074. /* 127 */ "as ::= AS nm",
  97075. /* 128 */ "as ::= ids",
  97076. /* 129 */ "as ::=",
  97077. /* 130 */ "from ::=",
  97078. /* 131 */ "from ::= FROM seltablist",
  97079. /* 132 */ "stl_prefix ::= seltablist joinop",
  97080. /* 133 */ "stl_prefix ::=",
  97081. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  97082. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  97083. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  97084. /* 137 */ "dbnm ::=",
  97085. /* 138 */ "dbnm ::= DOT nm",
  97086. /* 139 */ "fullname ::= nm dbnm",
  97087. /* 140 */ "joinop ::= COMMA|JOIN",
  97088. /* 141 */ "joinop ::= JOIN_KW JOIN",
  97089. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  97090. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  97091. /* 144 */ "on_opt ::= ON expr",
  97092. /* 145 */ "on_opt ::=",
  97093. /* 146 */ "indexed_opt ::=",
  97094. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  97095. /* 148 */ "indexed_opt ::= NOT INDEXED",
  97096. /* 149 */ "using_opt ::= USING LP inscollist RP",
  97097. /* 150 */ "using_opt ::=",
  97098. /* 151 */ "orderby_opt ::=",
  97099. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  97100. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  97101. /* 154 */ "sortlist ::= expr sortorder",
  97102. /* 155 */ "sortorder ::= ASC",
  97103. /* 156 */ "sortorder ::= DESC",
  97104. /* 157 */ "sortorder ::=",
  97105. /* 158 */ "groupby_opt ::=",
  97106. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  97107. /* 160 */ "having_opt ::=",
  97108. /* 161 */ "having_opt ::= HAVING expr",
  97109. /* 162 */ "limit_opt ::=",
  97110. /* 163 */ "limit_opt ::= LIMIT expr",
  97111. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  97112. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  97113. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  97114. /* 167 */ "where_opt ::=",
  97115. /* 168 */ "where_opt ::= WHERE expr",
  97116. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  97117. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  97118. /* 171 */ "setlist ::= nm EQ expr",
  97119. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  97120. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  97121. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  97122. /* 175 */ "insert_cmd ::= INSERT orconf",
  97123. /* 176 */ "insert_cmd ::= REPLACE",
  97124. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  97125. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  97126. /* 179 */ "inscollist_opt ::=",
  97127. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  97128. /* 181 */ "inscollist ::= inscollist COMMA nm",
  97129. /* 182 */ "inscollist ::= nm",
  97130. /* 183 */ "expr ::= term",
  97131. /* 184 */ "expr ::= LP expr RP",
  97132. /* 185 */ "term ::= NULL",
  97133. /* 186 */ "expr ::= id",
  97134. /* 187 */ "expr ::= JOIN_KW",
  97135. /* 188 */ "expr ::= nm DOT nm",
  97136. /* 189 */ "expr ::= nm DOT nm DOT nm",
  97137. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  97138. /* 191 */ "term ::= STRING",
  97139. /* 192 */ "expr ::= REGISTER",
  97140. /* 193 */ "expr ::= VARIABLE",
  97141. /* 194 */ "expr ::= expr COLLATE ids",
  97142. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  97143. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  97144. /* 197 */ "expr ::= ID LP STAR RP",
  97145. /* 198 */ "term ::= CTIME_KW",
  97146. /* 199 */ "expr ::= expr AND expr",
  97147. /* 200 */ "expr ::= expr OR expr",
  97148. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  97149. /* 202 */ "expr ::= expr EQ|NE expr",
  97150. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  97151. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  97152. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  97153. /* 206 */ "expr ::= expr CONCAT expr",
  97154. /* 207 */ "likeop ::= LIKE_KW",
  97155. /* 208 */ "likeop ::= NOT LIKE_KW",
  97156. /* 209 */ "likeop ::= MATCH",
  97157. /* 210 */ "likeop ::= NOT MATCH",
  97158. /* 211 */ "expr ::= expr likeop expr",
  97159. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  97160. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  97161. /* 214 */ "expr ::= expr NOT NULL",
  97162. /* 215 */ "expr ::= expr IS expr",
  97163. /* 216 */ "expr ::= expr IS NOT expr",
  97164. /* 217 */ "expr ::= NOT expr",
  97165. /* 218 */ "expr ::= BITNOT expr",
  97166. /* 219 */ "expr ::= MINUS expr",
  97167. /* 220 */ "expr ::= PLUS expr",
  97168. /* 221 */ "between_op ::= BETWEEN",
  97169. /* 222 */ "between_op ::= NOT BETWEEN",
  97170. /* 223 */ "expr ::= expr between_op expr AND expr",
  97171. /* 224 */ "in_op ::= IN",
  97172. /* 225 */ "in_op ::= NOT IN",
  97173. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  97174. /* 227 */ "expr ::= LP select RP",
  97175. /* 228 */ "expr ::= expr in_op LP select RP",
  97176. /* 229 */ "expr ::= expr in_op nm dbnm",
  97177. /* 230 */ "expr ::= EXISTS LP select RP",
  97178. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  97179. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  97180. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  97181. /* 234 */ "case_else ::= ELSE expr",
  97182. /* 235 */ "case_else ::=",
  97183. /* 236 */ "case_operand ::= expr",
  97184. /* 237 */ "case_operand ::=",
  97185. /* 238 */ "exprlist ::= nexprlist",
  97186. /* 239 */ "exprlist ::=",
  97187. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  97188. /* 241 */ "nexprlist ::= expr",
  97189. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  97190. /* 243 */ "uniqueflag ::= UNIQUE",
  97191. /* 244 */ "uniqueflag ::=",
  97192. /* 245 */ "idxlist_opt ::=",
  97193. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  97194. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  97195. /* 248 */ "idxlist ::= nm collate sortorder",
  97196. /* 249 */ "collate ::=",
  97197. /* 250 */ "collate ::= COLLATE ids",
  97198. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  97199. /* 252 */ "cmd ::= VACUUM",
  97200. /* 253 */ "cmd ::= VACUUM nm",
  97201. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  97202. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  97203. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  97204. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  97205. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  97206. /* 259 */ "nmnum ::= plus_num",
  97207. /* 260 */ "nmnum ::= nm",
  97208. /* 261 */ "nmnum ::= ON",
  97209. /* 262 */ "nmnum ::= DELETE",
  97210. /* 263 */ "nmnum ::= DEFAULT",
  97211. /* 264 */ "plus_num ::= PLUS number",
  97212. /* 265 */ "plus_num ::= number",
  97213. /* 266 */ "minus_num ::= MINUS number",
  97214. /* 267 */ "number ::= INTEGER|FLOAT",
  97215. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  97216. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  97217. /* 270 */ "trigger_time ::= BEFORE",
  97218. /* 271 */ "trigger_time ::= AFTER",
  97219. /* 272 */ "trigger_time ::= INSTEAD OF",
  97220. /* 273 */ "trigger_time ::=",
  97221. /* 274 */ "trigger_event ::= DELETE|INSERT",
  97222. /* 275 */ "trigger_event ::= UPDATE",
  97223. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  97224. /* 277 */ "foreach_clause ::=",
  97225. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  97226. /* 279 */ "when_clause ::=",
  97227. /* 280 */ "when_clause ::= WHEN expr",
  97228. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  97229. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  97230. /* 283 */ "trnm ::= nm",
  97231. /* 284 */ "trnm ::= nm DOT nm",
  97232. /* 285 */ "tridxby ::=",
  97233. /* 286 */ "tridxby ::= INDEXED BY nm",
  97234. /* 287 */ "tridxby ::= NOT INDEXED",
  97235. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  97236. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  97237. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  97238. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  97239. /* 292 */ "trigger_cmd ::= select",
  97240. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  97241. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  97242. /* 295 */ "raisetype ::= ROLLBACK",
  97243. /* 296 */ "raisetype ::= ABORT",
  97244. /* 297 */ "raisetype ::= FAIL",
  97245. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  97246. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  97247. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  97248. /* 301 */ "key_opt ::=",
  97249. /* 302 */ "key_opt ::= KEY expr",
  97250. /* 303 */ "database_kw_opt ::= DATABASE",
  97251. /* 304 */ "database_kw_opt ::=",
  97252. /* 305 */ "cmd ::= REINDEX",
  97253. /* 306 */ "cmd ::= REINDEX nm dbnm",
  97254. /* 307 */ "cmd ::= ANALYZE",
  97255. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  97256. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  97257. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  97258. /* 311 */ "add_column_fullname ::= fullname",
  97259. /* 312 */ "kwcolumn_opt ::=",
  97260. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  97261. /* 314 */ "cmd ::= create_vtab",
  97262. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  97263. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  97264. /* 317 */ "vtabarglist ::= vtabarg",
  97265. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  97266. /* 319 */ "vtabarg ::=",
  97267. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  97268. /* 321 */ "vtabargtoken ::= ANY",
  97269. /* 322 */ "vtabargtoken ::= lp anylist RP",
  97270. /* 323 */ "lp ::= LP",
  97271. /* 324 */ "anylist ::=",
  97272. /* 325 */ "anylist ::= anylist LP anylist RP",
  97273. /* 326 */ "anylist ::= anylist ANY",
  97274. };
  97275. #endif /* NDEBUG */
  97276. #if YYSTACKDEPTH<=0
  97277. /*
  97278. ** Try to increase the size of the parser stack.
  97279. */
  97280. static void yyGrowStack(yyParser *p){
  97281. int newSize;
  97282. yyStackEntry *pNew;
  97283. newSize = p->yystksz*2 + 100;
  97284. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  97285. if( pNew ){
  97286. p->yystack = pNew;
  97287. p->yystksz = newSize;
  97288. #ifndef NDEBUG
  97289. if( yyTraceFILE ){
  97290. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  97291. yyTracePrompt, p->yystksz);
  97292. }
  97293. #endif
  97294. }
  97295. }
  97296. #endif
  97297. /*
  97298. ** This function allocates a new parser.
  97299. ** The only argument is a pointer to a function which works like
  97300. ** malloc.
  97301. **
  97302. ** Inputs:
  97303. ** A pointer to the function used to allocate memory.
  97304. **
  97305. ** Outputs:
  97306. ** A pointer to a parser. This pointer is used in subsequent calls
  97307. ** to sqlite3Parser and sqlite3ParserFree.
  97308. */
  97309. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  97310. yyParser *pParser;
  97311. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  97312. if( pParser ){
  97313. pParser->yyidx = -1;
  97314. #ifdef YYTRACKMAXSTACKDEPTH
  97315. pParser->yyidxMax = 0;
  97316. #endif
  97317. #if YYSTACKDEPTH<=0
  97318. pParser->yystack = NULL;
  97319. pParser->yystksz = 0;
  97320. yyGrowStack(pParser);
  97321. #endif
  97322. }
  97323. return pParser;
  97324. }
  97325. /* The following function deletes the value associated with a
  97326. ** symbol. The symbol can be either a terminal or nonterminal.
  97327. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  97328. ** the value.
  97329. */
  97330. static void yy_destructor(
  97331. yyParser *yypParser, /* The parser */
  97332. YYCODETYPE yymajor, /* Type code for object to destroy */
  97333. YYMINORTYPE *yypminor /* The object to be destroyed */
  97334. ){
  97335. sqlite3ParserARG_FETCH;
  97336. switch( yymajor ){
  97337. /* Here is inserted the actions which take place when a
  97338. ** terminal or non-terminal is destroyed. This can happen
  97339. ** when the symbol is popped from the stack during a
  97340. ** reduce or during error processing or when a parser is
  97341. ** being destroyed before it is finished parsing.
  97342. **
  97343. ** Note: during a reduce, the only symbols destroyed are those
  97344. ** which appear on the RHS of the rule, but which are not used
  97345. ** inside the C code.
  97346. */
  97347. case 160: /* select */
  97348. case 194: /* oneselect */
  97349. {
  97350. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  97351. }
  97352. break;
  97353. case 173: /* term */
  97354. case 174: /* expr */
  97355. {
  97356. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  97357. }
  97358. break;
  97359. case 178: /* idxlist_opt */
  97360. case 187: /* idxlist */
  97361. case 197: /* selcollist */
  97362. case 200: /* groupby_opt */
  97363. case 202: /* orderby_opt */
  97364. case 204: /* sclp */
  97365. case 214: /* sortlist */
  97366. case 215: /* nexprlist */
  97367. case 216: /* setlist */
  97368. case 220: /* exprlist */
  97369. case 225: /* case_exprlist */
  97370. {
  97371. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  97372. }
  97373. break;
  97374. case 193: /* fullname */
  97375. case 198: /* from */
  97376. case 206: /* seltablist */
  97377. case 207: /* stl_prefix */
  97378. {
  97379. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  97380. }
  97381. break;
  97382. case 199: /* where_opt */
  97383. case 201: /* having_opt */
  97384. case 210: /* on_opt */
  97385. case 224: /* case_operand */
  97386. case 226: /* case_else */
  97387. case 236: /* when_clause */
  97388. case 241: /* key_opt */
  97389. {
  97390. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  97391. }
  97392. break;
  97393. case 211: /* using_opt */
  97394. case 213: /* inscollist */
  97395. case 218: /* inscollist_opt */
  97396. {
  97397. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  97398. }
  97399. break;
  97400. case 219: /* valuelist */
  97401. {
  97402. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  97403. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  97404. }
  97405. break;
  97406. case 232: /* trigger_cmd_list */
  97407. case 237: /* trigger_cmd */
  97408. {
  97409. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  97410. }
  97411. break;
  97412. case 234: /* trigger_event */
  97413. {
  97414. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  97415. }
  97416. break;
  97417. default: break; /* If no destructor action specified: do nothing */
  97418. }
  97419. }
  97420. /*
  97421. ** Pop the parser's stack once.
  97422. **
  97423. ** If there is a destructor routine associated with the token which
  97424. ** is popped from the stack, then call it.
  97425. **
  97426. ** Return the major token number for the symbol popped.
  97427. */
  97428. static int yy_pop_parser_stack(yyParser *pParser){
  97429. YYCODETYPE yymajor;
  97430. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  97431. /* There is no mechanism by which the parser stack can be popped below
  97432. ** empty in SQLite. */
  97433. if( NEVER(pParser->yyidx<0) ) return 0;
  97434. #ifndef NDEBUG
  97435. if( yyTraceFILE && pParser->yyidx>=0 ){
  97436. fprintf(yyTraceFILE,"%sPopping %s\n",
  97437. yyTracePrompt,
  97438. yyTokenName[yytos->major]);
  97439. }
  97440. #endif
  97441. yymajor = yytos->major;
  97442. yy_destructor(pParser, yymajor, &yytos->minor);
  97443. pParser->yyidx--;
  97444. return yymajor;
  97445. }
  97446. /*
  97447. ** Deallocate and destroy a parser. Destructors are all called for
  97448. ** all stack elements before shutting the parser down.
  97449. **
  97450. ** Inputs:
  97451. ** <ul>
  97452. ** <li> A pointer to the parser. This should be a pointer
  97453. ** obtained from sqlite3ParserAlloc.
  97454. ** <li> A pointer to a function used to reclaim memory obtained
  97455. ** from malloc.
  97456. ** </ul>
  97457. */
  97458. SQLITE_PRIVATE void sqlite3ParserFree(
  97459. void *p, /* The parser to be deleted */
  97460. void (*freeProc)(void*) /* Function used to reclaim memory */
  97461. ){
  97462. yyParser *pParser = (yyParser*)p;
  97463. /* In SQLite, we never try to destroy a parser that was not successfully
  97464. ** created in the first place. */
  97465. if( NEVER(pParser==0) ) return;
  97466. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  97467. #if YYSTACKDEPTH<=0
  97468. free(pParser->yystack);
  97469. #endif
  97470. (*freeProc)((void*)pParser);
  97471. }
  97472. /*
  97473. ** Return the peak depth of the stack for a parser.
  97474. */
  97475. #ifdef YYTRACKMAXSTACKDEPTH
  97476. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  97477. yyParser *pParser = (yyParser*)p;
  97478. return pParser->yyidxMax;
  97479. }
  97480. #endif
  97481. /*
  97482. ** Find the appropriate action for a parser given the terminal
  97483. ** look-ahead token iLookAhead.
  97484. **
  97485. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97486. ** independent of the look-ahead. If it is, return the action, otherwise
  97487. ** return YY_NO_ACTION.
  97488. */
  97489. static int yy_find_shift_action(
  97490. yyParser *pParser, /* The parser */
  97491. YYCODETYPE iLookAhead /* The look-ahead token */
  97492. ){
  97493. int i;
  97494. int stateno = pParser->yystack[pParser->yyidx].stateno;
  97495. if( stateno>YY_SHIFT_COUNT
  97496. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  97497. return yy_default[stateno];
  97498. }
  97499. assert( iLookAhead!=YYNOCODE );
  97500. i += iLookAhead;
  97501. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97502. if( iLookAhead>0 ){
  97503. #ifdef YYFALLBACK
  97504. YYCODETYPE iFallback; /* Fallback token */
  97505. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  97506. && (iFallback = yyFallback[iLookAhead])!=0 ){
  97507. #ifndef NDEBUG
  97508. if( yyTraceFILE ){
  97509. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  97510. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  97511. }
  97512. #endif
  97513. return yy_find_shift_action(pParser, iFallback);
  97514. }
  97515. #endif
  97516. #ifdef YYWILDCARD
  97517. {
  97518. int j = i - iLookAhead + YYWILDCARD;
  97519. if(
  97520. #if YY_SHIFT_MIN+YYWILDCARD<0
  97521. j>=0 &&
  97522. #endif
  97523. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  97524. j<YY_ACTTAB_COUNT &&
  97525. #endif
  97526. yy_lookahead[j]==YYWILDCARD
  97527. ){
  97528. #ifndef NDEBUG
  97529. if( yyTraceFILE ){
  97530. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  97531. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  97532. }
  97533. #endif /* NDEBUG */
  97534. return yy_action[j];
  97535. }
  97536. }
  97537. #endif /* YYWILDCARD */
  97538. }
  97539. return yy_default[stateno];
  97540. }else{
  97541. return yy_action[i];
  97542. }
  97543. }
  97544. /*
  97545. ** Find the appropriate action for a parser given the non-terminal
  97546. ** look-ahead token iLookAhead.
  97547. **
  97548. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97549. ** independent of the look-ahead. If it is, return the action, otherwise
  97550. ** return YY_NO_ACTION.
  97551. */
  97552. static int yy_find_reduce_action(
  97553. int stateno, /* Current state number */
  97554. YYCODETYPE iLookAhead /* The look-ahead token */
  97555. ){
  97556. int i;
  97557. #ifdef YYERRORSYMBOL
  97558. if( stateno>YY_REDUCE_COUNT ){
  97559. return yy_default[stateno];
  97560. }
  97561. #else
  97562. assert( stateno<=YY_REDUCE_COUNT );
  97563. #endif
  97564. i = yy_reduce_ofst[stateno];
  97565. assert( i!=YY_REDUCE_USE_DFLT );
  97566. assert( iLookAhead!=YYNOCODE );
  97567. i += iLookAhead;
  97568. #ifdef YYERRORSYMBOL
  97569. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97570. return yy_default[stateno];
  97571. }
  97572. #else
  97573. assert( i>=0 && i<YY_ACTTAB_COUNT );
  97574. assert( yy_lookahead[i]==iLookAhead );
  97575. #endif
  97576. return yy_action[i];
  97577. }
  97578. /*
  97579. ** The following routine is called if the stack overflows.
  97580. */
  97581. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  97582. sqlite3ParserARG_FETCH;
  97583. yypParser->yyidx--;
  97584. #ifndef NDEBUG
  97585. if( yyTraceFILE ){
  97586. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  97587. }
  97588. #endif
  97589. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  97590. /* Here code is inserted which will execute if the parser
  97591. ** stack every overflows */
  97592. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  97593. sqlite3ErrorMsg(pParse, "parser stack overflow");
  97594. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  97595. }
  97596. /*
  97597. ** Perform a shift action.
  97598. */
  97599. static void yy_shift(
  97600. yyParser *yypParser, /* The parser to be shifted */
  97601. int yyNewState, /* The new state to shift in */
  97602. int yyMajor, /* The major token to shift in */
  97603. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  97604. ){
  97605. yyStackEntry *yytos;
  97606. yypParser->yyidx++;
  97607. #ifdef YYTRACKMAXSTACKDEPTH
  97608. if( yypParser->yyidx>yypParser->yyidxMax ){
  97609. yypParser->yyidxMax = yypParser->yyidx;
  97610. }
  97611. #endif
  97612. #if YYSTACKDEPTH>0
  97613. if( yypParser->yyidx>=YYSTACKDEPTH ){
  97614. yyStackOverflow(yypParser, yypMinor);
  97615. return;
  97616. }
  97617. #else
  97618. if( yypParser->yyidx>=yypParser->yystksz ){
  97619. yyGrowStack(yypParser);
  97620. if( yypParser->yyidx>=yypParser->yystksz ){
  97621. yyStackOverflow(yypParser, yypMinor);
  97622. return;
  97623. }
  97624. }
  97625. #endif
  97626. yytos = &yypParser->yystack[yypParser->yyidx];
  97627. yytos->stateno = (YYACTIONTYPE)yyNewState;
  97628. yytos->major = (YYCODETYPE)yyMajor;
  97629. yytos->minor = *yypMinor;
  97630. #ifndef NDEBUG
  97631. if( yyTraceFILE && yypParser->yyidx>0 ){
  97632. int i;
  97633. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  97634. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  97635. for(i=1; i<=yypParser->yyidx; i++)
  97636. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  97637. fprintf(yyTraceFILE,"\n");
  97638. }
  97639. #endif
  97640. }
  97641. /* The following table contains information about every rule that
  97642. ** is used during the reduce.
  97643. */
  97644. static const struct {
  97645. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  97646. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  97647. } yyRuleInfo[] = {
  97648. { 142, 1 },
  97649. { 143, 2 },
  97650. { 143, 1 },
  97651. { 144, 1 },
  97652. { 144, 3 },
  97653. { 145, 0 },
  97654. { 145, 1 },
  97655. { 145, 3 },
  97656. { 146, 1 },
  97657. { 147, 3 },
  97658. { 149, 0 },
  97659. { 149, 1 },
  97660. { 149, 2 },
  97661. { 148, 0 },
  97662. { 148, 1 },
  97663. { 148, 1 },
  97664. { 148, 1 },
  97665. { 147, 2 },
  97666. { 147, 2 },
  97667. { 147, 2 },
  97668. { 151, 1 },
  97669. { 151, 0 },
  97670. { 147, 2 },
  97671. { 147, 3 },
  97672. { 147, 5 },
  97673. { 147, 2 },
  97674. { 152, 6 },
  97675. { 154, 1 },
  97676. { 156, 0 },
  97677. { 156, 3 },
  97678. { 155, 1 },
  97679. { 155, 0 },
  97680. { 153, 4 },
  97681. { 153, 2 },
  97682. { 158, 3 },
  97683. { 158, 1 },
  97684. { 161, 3 },
  97685. { 162, 1 },
  97686. { 165, 1 },
  97687. { 165, 1 },
  97688. { 166, 1 },
  97689. { 150, 1 },
  97690. { 150, 1 },
  97691. { 150, 1 },
  97692. { 163, 0 },
  97693. { 163, 1 },
  97694. { 167, 1 },
  97695. { 167, 4 },
  97696. { 167, 6 },
  97697. { 168, 1 },
  97698. { 168, 2 },
  97699. { 169, 1 },
  97700. { 169, 1 },
  97701. { 164, 2 },
  97702. { 164, 0 },
  97703. { 172, 2 },
  97704. { 172, 2 },
  97705. { 172, 4 },
  97706. { 172, 3 },
  97707. { 172, 3 },
  97708. { 172, 2 },
  97709. { 172, 2 },
  97710. { 172, 3 },
  97711. { 172, 5 },
  97712. { 172, 2 },
  97713. { 172, 4 },
  97714. { 172, 4 },
  97715. { 172, 1 },
  97716. { 172, 2 },
  97717. { 177, 0 },
  97718. { 177, 1 },
  97719. { 179, 0 },
  97720. { 179, 2 },
  97721. { 181, 2 },
  97722. { 181, 3 },
  97723. { 181, 3 },
  97724. { 181, 3 },
  97725. { 182, 2 },
  97726. { 182, 2 },
  97727. { 182, 1 },
  97728. { 182, 1 },
  97729. { 182, 2 },
  97730. { 180, 3 },
  97731. { 180, 2 },
  97732. { 183, 0 },
  97733. { 183, 2 },
  97734. { 183, 2 },
  97735. { 159, 0 },
  97736. { 159, 2 },
  97737. { 184, 3 },
  97738. { 184, 1 },
  97739. { 185, 1 },
  97740. { 185, 0 },
  97741. { 186, 2 },
  97742. { 186, 7 },
  97743. { 186, 5 },
  97744. { 186, 5 },
  97745. { 186, 10 },
  97746. { 188, 0 },
  97747. { 188, 1 },
  97748. { 175, 0 },
  97749. { 175, 3 },
  97750. { 189, 0 },
  97751. { 189, 2 },
  97752. { 190, 1 },
  97753. { 190, 1 },
  97754. { 190, 1 },
  97755. { 147, 4 },
  97756. { 192, 2 },
  97757. { 192, 0 },
  97758. { 147, 8 },
  97759. { 147, 4 },
  97760. { 147, 1 },
  97761. { 160, 1 },
  97762. { 160, 3 },
  97763. { 195, 1 },
  97764. { 195, 2 },
  97765. { 195, 1 },
  97766. { 194, 9 },
  97767. { 196, 1 },
  97768. { 196, 1 },
  97769. { 196, 0 },
  97770. { 204, 2 },
  97771. { 204, 0 },
  97772. { 197, 3 },
  97773. { 197, 2 },
  97774. { 197, 4 },
  97775. { 205, 2 },
  97776. { 205, 1 },
  97777. { 205, 0 },
  97778. { 198, 0 },
  97779. { 198, 2 },
  97780. { 207, 2 },
  97781. { 207, 0 },
  97782. { 206, 7 },
  97783. { 206, 7 },
  97784. { 206, 7 },
  97785. { 157, 0 },
  97786. { 157, 2 },
  97787. { 193, 2 },
  97788. { 208, 1 },
  97789. { 208, 2 },
  97790. { 208, 3 },
  97791. { 208, 4 },
  97792. { 210, 2 },
  97793. { 210, 0 },
  97794. { 209, 0 },
  97795. { 209, 3 },
  97796. { 209, 2 },
  97797. { 211, 4 },
  97798. { 211, 0 },
  97799. { 202, 0 },
  97800. { 202, 3 },
  97801. { 214, 4 },
  97802. { 214, 2 },
  97803. { 176, 1 },
  97804. { 176, 1 },
  97805. { 176, 0 },
  97806. { 200, 0 },
  97807. { 200, 3 },
  97808. { 201, 0 },
  97809. { 201, 2 },
  97810. { 203, 0 },
  97811. { 203, 2 },
  97812. { 203, 4 },
  97813. { 203, 4 },
  97814. { 147, 5 },
  97815. { 199, 0 },
  97816. { 199, 2 },
  97817. { 147, 7 },
  97818. { 216, 5 },
  97819. { 216, 3 },
  97820. { 147, 5 },
  97821. { 147, 5 },
  97822. { 147, 6 },
  97823. { 217, 2 },
  97824. { 217, 1 },
  97825. { 219, 4 },
  97826. { 219, 5 },
  97827. { 218, 0 },
  97828. { 218, 3 },
  97829. { 213, 3 },
  97830. { 213, 1 },
  97831. { 174, 1 },
  97832. { 174, 3 },
  97833. { 173, 1 },
  97834. { 174, 1 },
  97835. { 174, 1 },
  97836. { 174, 3 },
  97837. { 174, 5 },
  97838. { 173, 1 },
  97839. { 173, 1 },
  97840. { 174, 1 },
  97841. { 174, 1 },
  97842. { 174, 3 },
  97843. { 174, 6 },
  97844. { 174, 5 },
  97845. { 174, 4 },
  97846. { 173, 1 },
  97847. { 174, 3 },
  97848. { 174, 3 },
  97849. { 174, 3 },
  97850. { 174, 3 },
  97851. { 174, 3 },
  97852. { 174, 3 },
  97853. { 174, 3 },
  97854. { 174, 3 },
  97855. { 221, 1 },
  97856. { 221, 2 },
  97857. { 221, 1 },
  97858. { 221, 2 },
  97859. { 174, 3 },
  97860. { 174, 5 },
  97861. { 174, 2 },
  97862. { 174, 3 },
  97863. { 174, 3 },
  97864. { 174, 4 },
  97865. { 174, 2 },
  97866. { 174, 2 },
  97867. { 174, 2 },
  97868. { 174, 2 },
  97869. { 222, 1 },
  97870. { 222, 2 },
  97871. { 174, 5 },
  97872. { 223, 1 },
  97873. { 223, 2 },
  97874. { 174, 5 },
  97875. { 174, 3 },
  97876. { 174, 5 },
  97877. { 174, 4 },
  97878. { 174, 4 },
  97879. { 174, 5 },
  97880. { 225, 5 },
  97881. { 225, 4 },
  97882. { 226, 2 },
  97883. { 226, 0 },
  97884. { 224, 1 },
  97885. { 224, 0 },
  97886. { 220, 1 },
  97887. { 220, 0 },
  97888. { 215, 3 },
  97889. { 215, 1 },
  97890. { 147, 12 },
  97891. { 227, 1 },
  97892. { 227, 0 },
  97893. { 178, 0 },
  97894. { 178, 3 },
  97895. { 187, 5 },
  97896. { 187, 3 },
  97897. { 228, 0 },
  97898. { 228, 2 },
  97899. { 147, 4 },
  97900. { 147, 1 },
  97901. { 147, 2 },
  97902. { 147, 3 },
  97903. { 147, 5 },
  97904. { 147, 6 },
  97905. { 147, 5 },
  97906. { 147, 6 },
  97907. { 229, 1 },
  97908. { 229, 1 },
  97909. { 229, 1 },
  97910. { 229, 1 },
  97911. { 229, 1 },
  97912. { 170, 2 },
  97913. { 170, 1 },
  97914. { 171, 2 },
  97915. { 230, 1 },
  97916. { 147, 5 },
  97917. { 231, 11 },
  97918. { 233, 1 },
  97919. { 233, 1 },
  97920. { 233, 2 },
  97921. { 233, 0 },
  97922. { 234, 1 },
  97923. { 234, 1 },
  97924. { 234, 3 },
  97925. { 235, 0 },
  97926. { 235, 3 },
  97927. { 236, 0 },
  97928. { 236, 2 },
  97929. { 232, 3 },
  97930. { 232, 2 },
  97931. { 238, 1 },
  97932. { 238, 3 },
  97933. { 239, 0 },
  97934. { 239, 3 },
  97935. { 239, 2 },
  97936. { 237, 7 },
  97937. { 237, 5 },
  97938. { 237, 5 },
  97939. { 237, 5 },
  97940. { 237, 1 },
  97941. { 174, 4 },
  97942. { 174, 6 },
  97943. { 191, 1 },
  97944. { 191, 1 },
  97945. { 191, 1 },
  97946. { 147, 4 },
  97947. { 147, 6 },
  97948. { 147, 3 },
  97949. { 241, 0 },
  97950. { 241, 2 },
  97951. { 240, 1 },
  97952. { 240, 0 },
  97953. { 147, 1 },
  97954. { 147, 3 },
  97955. { 147, 1 },
  97956. { 147, 3 },
  97957. { 147, 6 },
  97958. { 147, 6 },
  97959. { 242, 1 },
  97960. { 243, 0 },
  97961. { 243, 1 },
  97962. { 147, 1 },
  97963. { 147, 4 },
  97964. { 244, 8 },
  97965. { 245, 1 },
  97966. { 245, 3 },
  97967. { 246, 0 },
  97968. { 246, 2 },
  97969. { 247, 1 },
  97970. { 247, 3 },
  97971. { 248, 1 },
  97972. { 249, 0 },
  97973. { 249, 4 },
  97974. { 249, 2 },
  97975. };
  97976. static void yy_accept(yyParser*); /* Forward Declaration */
  97977. /*
  97978. ** Perform a reduce action and the shift that must immediately
  97979. ** follow the reduce.
  97980. */
  97981. static void yy_reduce(
  97982. yyParser *yypParser, /* The parser */
  97983. int yyruleno /* Number of the rule by which to reduce */
  97984. ){
  97985. int yygoto; /* The next state */
  97986. int yyact; /* The next action */
  97987. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  97988. yyStackEntry *yymsp; /* The top of the parser's stack */
  97989. int yysize; /* Amount to pop the stack */
  97990. sqlite3ParserARG_FETCH;
  97991. yymsp = &yypParser->yystack[yypParser->yyidx];
  97992. #ifndef NDEBUG
  97993. if( yyTraceFILE && yyruleno>=0
  97994. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  97995. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  97996. yyRuleName[yyruleno]);
  97997. }
  97998. #endif /* NDEBUG */
  97999. /* Silence complaints from purify about yygotominor being uninitialized
  98000. ** in some cases when it is copied into the stack after the following
  98001. ** switch. yygotominor is uninitialized when a rule reduces that does
  98002. ** not set the value of its left-hand side nonterminal. Leaving the
  98003. ** value of the nonterminal uninitialized is utterly harmless as long
  98004. ** as the value is never used. So really the only thing this code
  98005. ** accomplishes is to quieten purify.
  98006. **
  98007. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  98008. ** without this code, their parser segfaults. I'm not sure what there
  98009. ** parser is doing to make this happen. This is the second bug report
  98010. ** from wireshark this week. Clearly they are stressing Lemon in ways
  98011. ** that it has not been previously stressed... (SQLite ticket #2172)
  98012. */
  98013. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  98014. yygotominor = yyzerominor;
  98015. switch( yyruleno ){
  98016. /* Beginning here are the reduction cases. A typical example
  98017. ** follows:
  98018. ** case 0:
  98019. ** #line <lineno> <grammarfile>
  98020. ** { ... } // User supplied code
  98021. ** #line <lineno> <thisfile>
  98022. ** break;
  98023. */
  98024. case 5: /* explain ::= */
  98025. { sqlite3BeginParse(pParse, 0); }
  98026. break;
  98027. case 6: /* explain ::= EXPLAIN */
  98028. { sqlite3BeginParse(pParse, 1); }
  98029. break;
  98030. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  98031. { sqlite3BeginParse(pParse, 2); }
  98032. break;
  98033. case 8: /* cmdx ::= cmd */
  98034. { sqlite3FinishCoding(pParse); }
  98035. break;
  98036. case 9: /* cmd ::= BEGIN transtype trans_opt */
  98037. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  98038. break;
  98039. case 13: /* transtype ::= */
  98040. {yygotominor.yy392 = TK_DEFERRED;}
  98041. break;
  98042. case 14: /* transtype ::= DEFERRED */
  98043. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  98044. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  98045. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  98046. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  98047. {yygotominor.yy392 = yymsp[0].major;}
  98048. break;
  98049. case 17: /* cmd ::= COMMIT trans_opt */
  98050. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  98051. {sqlite3CommitTransaction(pParse);}
  98052. break;
  98053. case 19: /* cmd ::= ROLLBACK trans_opt */
  98054. {sqlite3RollbackTransaction(pParse);}
  98055. break;
  98056. case 22: /* cmd ::= SAVEPOINT nm */
  98057. {
  98058. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  98059. }
  98060. break;
  98061. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  98062. {
  98063. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  98064. }
  98065. break;
  98066. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  98067. {
  98068. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  98069. }
  98070. break;
  98071. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  98072. {
  98073. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  98074. }
  98075. break;
  98076. case 27: /* createkw ::= CREATE */
  98077. {
  98078. pParse->db->lookaside.bEnabled = 0;
  98079. yygotominor.yy0 = yymsp[0].minor.yy0;
  98080. }
  98081. break;
  98082. case 28: /* ifnotexists ::= */
  98083. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  98084. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  98085. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  98086. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  98087. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  98088. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  98089. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  98090. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  98091. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  98092. {yygotominor.yy392 = 0;}
  98093. break;
  98094. case 29: /* ifnotexists ::= IF NOT EXISTS */
  98095. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  98096. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  98097. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  98098. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  98099. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  98100. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  98101. {yygotominor.yy392 = 1;}
  98102. break;
  98103. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  98104. {
  98105. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  98106. }
  98107. break;
  98108. case 33: /* create_table_args ::= AS select */
  98109. {
  98110. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  98111. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  98112. }
  98113. break;
  98114. case 36: /* column ::= columnid type carglist */
  98115. {
  98116. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  98117. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  98118. }
  98119. break;
  98120. case 37: /* columnid ::= nm */
  98121. {
  98122. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  98123. yygotominor.yy0 = yymsp[0].minor.yy0;
  98124. pParse->constraintName.n = 0;
  98125. }
  98126. break;
  98127. case 38: /* id ::= ID */
  98128. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  98129. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  98130. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  98131. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  98132. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  98133. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  98134. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  98135. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  98136. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  98137. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  98138. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  98139. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  98140. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  98141. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  98142. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  98143. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  98144. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  98145. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  98146. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  98147. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  98148. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  98149. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  98150. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  98151. break;
  98152. case 45: /* type ::= typetoken */
  98153. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  98154. break;
  98155. case 47: /* typetoken ::= typename LP signed RP */
  98156. {
  98157. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  98158. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  98159. }
  98160. break;
  98161. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  98162. {
  98163. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  98164. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  98165. }
  98166. break;
  98167. case 50: /* typename ::= typename ids */
  98168. {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);}
  98169. break;
  98170. case 55: /* ccons ::= CONSTRAINT nm */
  98171. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  98172. {pParse->constraintName = yymsp[0].minor.yy0;}
  98173. break;
  98174. case 56: /* ccons ::= DEFAULT term */
  98175. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  98176. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  98177. break;
  98178. case 57: /* ccons ::= DEFAULT LP expr RP */
  98179. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  98180. break;
  98181. case 59: /* ccons ::= DEFAULT MINUS term */
  98182. {
  98183. ExprSpan v;
  98184. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  98185. v.zStart = yymsp[-1].minor.yy0.z;
  98186. v.zEnd = yymsp[0].minor.yy342.zEnd;
  98187. sqlite3AddDefaultValue(pParse,&v);
  98188. }
  98189. break;
  98190. case 60: /* ccons ::= DEFAULT id */
  98191. {
  98192. ExprSpan v;
  98193. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  98194. sqlite3AddDefaultValue(pParse,&v);
  98195. }
  98196. break;
  98197. case 62: /* ccons ::= NOT NULL onconf */
  98198. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  98199. break;
  98200. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  98201. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  98202. break;
  98203. case 64: /* ccons ::= UNIQUE onconf */
  98204. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  98205. break;
  98206. case 65: /* ccons ::= CHECK LP expr RP */
  98207. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  98208. break;
  98209. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  98210. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  98211. break;
  98212. case 67: /* ccons ::= defer_subclause */
  98213. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  98214. break;
  98215. case 68: /* ccons ::= COLLATE ids */
  98216. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  98217. break;
  98218. case 71: /* refargs ::= */
  98219. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  98220. break;
  98221. case 72: /* refargs ::= refargs refarg */
  98222. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  98223. break;
  98224. case 73: /* refarg ::= MATCH nm */
  98225. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  98226. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  98227. break;
  98228. case 75: /* refarg ::= ON DELETE refact */
  98229. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  98230. break;
  98231. case 76: /* refarg ::= ON UPDATE refact */
  98232. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  98233. break;
  98234. case 77: /* refact ::= SET NULL */
  98235. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  98236. break;
  98237. case 78: /* refact ::= SET DEFAULT */
  98238. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  98239. break;
  98240. case 79: /* refact ::= CASCADE */
  98241. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  98242. break;
  98243. case 80: /* refact ::= RESTRICT */
  98244. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  98245. break;
  98246. case 81: /* refact ::= NO ACTION */
  98247. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  98248. break;
  98249. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  98250. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  98251. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  98252. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  98253. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  98254. break;
  98255. case 87: /* conslist_opt ::= */
  98256. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  98257. break;
  98258. case 88: /* conslist_opt ::= COMMA conslist */
  98259. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  98260. break;
  98261. case 91: /* tconscomma ::= COMMA */
  98262. {pParse->constraintName.n = 0;}
  98263. break;
  98264. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  98265. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  98266. break;
  98267. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  98268. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  98269. break;
  98270. case 96: /* tcons ::= CHECK LP expr RP onconf */
  98271. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  98272. break;
  98273. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  98274. {
  98275. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  98276. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  98277. }
  98278. break;
  98279. case 100: /* onconf ::= */
  98280. {yygotominor.yy392 = OE_Default;}
  98281. break;
  98282. case 102: /* orconf ::= */
  98283. {yygotominor.yy258 = OE_Default;}
  98284. break;
  98285. case 103: /* orconf ::= OR resolvetype */
  98286. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  98287. break;
  98288. case 105: /* resolvetype ::= IGNORE */
  98289. {yygotominor.yy392 = OE_Ignore;}
  98290. break;
  98291. case 106: /* resolvetype ::= REPLACE */
  98292. {yygotominor.yy392 = OE_Replace;}
  98293. break;
  98294. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  98295. {
  98296. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  98297. }
  98298. break;
  98299. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  98300. {
  98301. 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);
  98302. }
  98303. break;
  98304. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  98305. {
  98306. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  98307. }
  98308. break;
  98309. case 112: /* cmd ::= select */
  98310. {
  98311. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  98312. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  98313. sqlite3ExplainBegin(pParse->pVdbe);
  98314. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  98315. sqlite3ExplainFinish(pParse->pVdbe);
  98316. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  98317. }
  98318. break;
  98319. case 113: /* select ::= oneselect */
  98320. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  98321. break;
  98322. case 114: /* select ::= select multiselect_op oneselect */
  98323. {
  98324. if( yymsp[0].minor.yy159 ){
  98325. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  98326. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  98327. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  98328. }else{
  98329. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  98330. }
  98331. yygotominor.yy159 = yymsp[0].minor.yy159;
  98332. }
  98333. break;
  98334. case 116: /* multiselect_op ::= UNION ALL */
  98335. {yygotominor.yy392 = TK_ALL;}
  98336. break;
  98337. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  98338. {
  98339. 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);
  98340. }
  98341. break;
  98342. case 119: /* distinct ::= DISTINCT */
  98343. {yygotominor.yy305 = SF_Distinct;}
  98344. break;
  98345. case 120: /* distinct ::= ALL */
  98346. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  98347. {yygotominor.yy305 = 0;}
  98348. break;
  98349. case 122: /* sclp ::= selcollist COMMA */
  98350. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  98351. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  98352. break;
  98353. case 123: /* sclp ::= */
  98354. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  98355. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  98356. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  98357. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  98358. {yygotominor.yy442 = 0;}
  98359. break;
  98360. case 124: /* selcollist ::= sclp expr as */
  98361. {
  98362. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  98363. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  98364. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  98365. }
  98366. break;
  98367. case 125: /* selcollist ::= sclp STAR */
  98368. {
  98369. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  98370. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  98371. }
  98372. break;
  98373. case 126: /* selcollist ::= sclp nm DOT STAR */
  98374. {
  98375. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  98376. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98377. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  98378. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  98379. }
  98380. break;
  98381. case 129: /* as ::= */
  98382. {yygotominor.yy0.n = 0;}
  98383. break;
  98384. case 130: /* from ::= */
  98385. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  98386. break;
  98387. case 131: /* from ::= FROM seltablist */
  98388. {
  98389. yygotominor.yy347 = yymsp[0].minor.yy347;
  98390. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  98391. }
  98392. break;
  98393. case 132: /* stl_prefix ::= seltablist joinop */
  98394. {
  98395. yygotominor.yy347 = yymsp[-1].minor.yy347;
  98396. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  98397. }
  98398. break;
  98399. case 133: /* stl_prefix ::= */
  98400. {yygotominor.yy347 = 0;}
  98401. break;
  98402. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  98403. {
  98404. 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);
  98405. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  98406. }
  98407. break;
  98408. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  98409. {
  98410. 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);
  98411. }
  98412. break;
  98413. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  98414. {
  98415. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  98416. yygotominor.yy347 = yymsp[-4].minor.yy347;
  98417. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  98418. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98419. if( yygotominor.yy347 ){
  98420. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  98421. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  98422. pNew->zName = pOld->zName;
  98423. pNew->zDatabase = pOld->zDatabase;
  98424. pNew->pSelect = pOld->pSelect;
  98425. pOld->zName = pOld->zDatabase = 0;
  98426. pOld->pSelect = 0;
  98427. }
  98428. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  98429. }else{
  98430. Select *pSubquery;
  98431. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  98432. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  98433. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98434. }
  98435. }
  98436. break;
  98437. case 137: /* dbnm ::= */
  98438. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  98439. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  98440. break;
  98441. case 139: /* fullname ::= nm dbnm */
  98442. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  98443. break;
  98444. case 140: /* joinop ::= COMMA|JOIN */
  98445. { yygotominor.yy392 = JT_INNER; }
  98446. break;
  98447. case 141: /* joinop ::= JOIN_KW JOIN */
  98448. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  98449. break;
  98450. case 142: /* joinop ::= JOIN_KW nm JOIN */
  98451. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  98452. break;
  98453. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  98454. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  98455. break;
  98456. case 144: /* on_opt ::= ON expr */
  98457. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  98458. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  98459. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  98460. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  98461. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  98462. break;
  98463. case 145: /* on_opt ::= */
  98464. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  98465. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  98466. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  98467. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  98468. {yygotominor.yy122 = 0;}
  98469. break;
  98470. case 148: /* indexed_opt ::= NOT INDEXED */
  98471. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  98472. break;
  98473. case 149: /* using_opt ::= USING LP inscollist RP */
  98474. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  98475. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  98476. break;
  98477. case 150: /* using_opt ::= */
  98478. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  98479. {yygotominor.yy180 = 0;}
  98480. break;
  98481. case 152: /* orderby_opt ::= ORDER BY sortlist */
  98482. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  98483. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  98484. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  98485. break;
  98486. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  98487. {
  98488. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  98489. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98490. }
  98491. break;
  98492. case 154: /* sortlist ::= expr sortorder */
  98493. {
  98494. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  98495. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  98496. }
  98497. break;
  98498. case 155: /* sortorder ::= ASC */
  98499. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  98500. {yygotominor.yy392 = SQLITE_SO_ASC;}
  98501. break;
  98502. case 156: /* sortorder ::= DESC */
  98503. {yygotominor.yy392 = SQLITE_SO_DESC;}
  98504. break;
  98505. case 162: /* limit_opt ::= */
  98506. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  98507. break;
  98508. case 163: /* limit_opt ::= LIMIT expr */
  98509. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  98510. break;
  98511. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  98512. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  98513. break;
  98514. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  98515. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  98516. break;
  98517. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  98518. {
  98519. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  98520. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  98521. }
  98522. break;
  98523. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  98524. {
  98525. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  98526. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  98527. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  98528. }
  98529. break;
  98530. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  98531. {
  98532. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  98533. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98534. }
  98535. break;
  98536. case 171: /* setlist ::= nm EQ expr */
  98537. {
  98538. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  98539. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98540. }
  98541. break;
  98542. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  98543. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  98544. break;
  98545. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  98546. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  98547. break;
  98548. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  98549. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  98550. break;
  98551. case 175: /* insert_cmd ::= INSERT orconf */
  98552. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  98553. break;
  98554. case 176: /* insert_cmd ::= REPLACE */
  98555. {yygotominor.yy258 = OE_Replace;}
  98556. break;
  98557. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  98558. {
  98559. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  98560. yygotominor.yy487.pSelect = 0;
  98561. }
  98562. break;
  98563. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  98564. {
  98565. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  98566. if( yymsp[-4].minor.yy487.pList ){
  98567. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  98568. yymsp[-4].minor.yy487.pList = 0;
  98569. }
  98570. yygotominor.yy487.pList = 0;
  98571. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  98572. sqlite3SelectDelete(pParse->db, pRight);
  98573. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  98574. yygotominor.yy487.pSelect = 0;
  98575. }else{
  98576. pRight->op = TK_ALL;
  98577. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  98578. pRight->selFlags |= SF_Values;
  98579. pRight->pPrior->selFlags |= SF_Values;
  98580. yygotominor.yy487.pSelect = pRight;
  98581. }
  98582. }
  98583. break;
  98584. case 181: /* inscollist ::= inscollist COMMA nm */
  98585. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  98586. break;
  98587. case 182: /* inscollist ::= nm */
  98588. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  98589. break;
  98590. case 183: /* expr ::= term */
  98591. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  98592. break;
  98593. case 184: /* expr ::= LP expr RP */
  98594. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  98595. break;
  98596. case 185: /* term ::= NULL */
  98597. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  98598. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  98599. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  98600. break;
  98601. case 186: /* expr ::= id */
  98602. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  98603. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  98604. break;
  98605. case 188: /* expr ::= nm DOT nm */
  98606. {
  98607. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98608. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98609. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  98610. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  98611. }
  98612. break;
  98613. case 189: /* expr ::= nm DOT nm DOT nm */
  98614. {
  98615. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  98616. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98617. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98618. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  98619. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  98620. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98621. }
  98622. break;
  98623. case 192: /* expr ::= REGISTER */
  98624. {
  98625. /* When doing a nested parse, one can include terms in an expression
  98626. ** that look like this: #1 #2 ... These terms refer to registers
  98627. ** in the virtual machine. #N is the N-th register. */
  98628. if( pParse->nested==0 ){
  98629. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  98630. yygotominor.yy342.pExpr = 0;
  98631. }else{
  98632. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  98633. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  98634. }
  98635. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98636. }
  98637. break;
  98638. case 193: /* expr ::= VARIABLE */
  98639. {
  98640. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  98641. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  98642. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98643. }
  98644. break;
  98645. case 194: /* expr ::= expr COLLATE ids */
  98646. {
  98647. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  98648. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  98649. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98650. }
  98651. break;
  98652. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  98653. {
  98654. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  98655. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  98656. }
  98657. break;
  98658. case 196: /* expr ::= ID LP distinct exprlist RP */
  98659. {
  98660. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  98661. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  98662. }
  98663. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  98664. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98665. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  98666. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  98667. }
  98668. }
  98669. break;
  98670. case 197: /* expr ::= ID LP STAR RP */
  98671. {
  98672. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  98673. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  98674. }
  98675. break;
  98676. case 198: /* term ::= CTIME_KW */
  98677. {
  98678. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  98679. ** treated as functions that return constants */
  98680. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  98681. if( yygotominor.yy342.pExpr ){
  98682. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  98683. }
  98684. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98685. }
  98686. break;
  98687. case 199: /* expr ::= expr AND expr */
  98688. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  98689. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  98690. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  98691. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  98692. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  98693. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  98694. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  98695. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  98696. break;
  98697. case 207: /* likeop ::= LIKE_KW */
  98698. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  98699. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  98700. break;
  98701. case 208: /* likeop ::= NOT LIKE_KW */
  98702. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  98703. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  98704. break;
  98705. case 211: /* expr ::= expr likeop expr */
  98706. {
  98707. ExprList *pList;
  98708. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  98709. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  98710. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  98711. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98712. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  98713. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98714. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  98715. }
  98716. break;
  98717. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  98718. {
  98719. ExprList *pList;
  98720. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98721. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  98722. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  98723. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  98724. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98725. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98726. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98727. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  98728. }
  98729. break;
  98730. case 213: /* expr ::= expr ISNULL|NOTNULL */
  98731. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  98732. break;
  98733. case 214: /* expr ::= expr NOT NULL */
  98734. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  98735. break;
  98736. case 215: /* expr ::= expr IS expr */
  98737. {
  98738. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  98739. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  98740. }
  98741. break;
  98742. case 216: /* expr ::= expr IS NOT expr */
  98743. {
  98744. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  98745. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  98746. }
  98747. break;
  98748. case 217: /* expr ::= NOT expr */
  98749. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  98750. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98751. break;
  98752. case 219: /* expr ::= MINUS expr */
  98753. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98754. break;
  98755. case 220: /* expr ::= PLUS expr */
  98756. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98757. break;
  98758. case 223: /* expr ::= expr between_op expr AND expr */
  98759. {
  98760. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98761. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  98762. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98763. if( yygotominor.yy342.pExpr ){
  98764. yygotominor.yy342.pExpr->x.pList = pList;
  98765. }else{
  98766. sqlite3ExprListDelete(pParse->db, pList);
  98767. }
  98768. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98769. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98770. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98771. }
  98772. break;
  98773. case 226: /* expr ::= expr in_op LP exprlist RP */
  98774. {
  98775. if( yymsp[-1].minor.yy442==0 ){
  98776. /* Expressions of the form
  98777. **
  98778. ** expr1 IN ()
  98779. ** expr1 NOT IN ()
  98780. **
  98781. ** simplify to constants 0 (false) and 1 (true), respectively,
  98782. ** regardless of the value of expr1.
  98783. */
  98784. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  98785. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  98786. }else{
  98787. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98788. if( yygotominor.yy342.pExpr ){
  98789. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  98790. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98791. }else{
  98792. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  98793. }
  98794. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98795. }
  98796. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98797. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98798. }
  98799. break;
  98800. case 227: /* expr ::= LP select RP */
  98801. {
  98802. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  98803. if( yygotominor.yy342.pExpr ){
  98804. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  98805. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98806. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98807. }else{
  98808. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98809. }
  98810. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  98811. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98812. }
  98813. break;
  98814. case 228: /* expr ::= expr in_op LP select RP */
  98815. {
  98816. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98817. if( yygotominor.yy342.pExpr ){
  98818. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  98819. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98820. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98821. }else{
  98822. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98823. }
  98824. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98825. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98826. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98827. }
  98828. break;
  98829. case 229: /* expr ::= expr in_op nm dbnm */
  98830. {
  98831. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  98832. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  98833. if( yygotominor.yy342.pExpr ){
  98834. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  98835. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98836. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98837. }else{
  98838. sqlite3SrcListDelete(pParse->db, pSrc);
  98839. }
  98840. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98841. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  98842. 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];
  98843. }
  98844. break;
  98845. case 230: /* expr ::= EXISTS LP select RP */
  98846. {
  98847. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  98848. if( p ){
  98849. p->x.pSelect = yymsp[-1].minor.yy159;
  98850. ExprSetProperty(p, EP_xIsSelect);
  98851. sqlite3ExprSetHeight(pParse, p);
  98852. }else{
  98853. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98854. }
  98855. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  98856. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98857. }
  98858. break;
  98859. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  98860. {
  98861. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  98862. if( yygotominor.yy342.pExpr ){
  98863. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  98864. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98865. }else{
  98866. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  98867. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  98868. }
  98869. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  98870. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98871. }
  98872. break;
  98873. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  98874. {
  98875. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  98876. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  98877. }
  98878. break;
  98879. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  98880. {
  98881. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98882. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  98883. }
  98884. break;
  98885. case 240: /* nexprlist ::= nexprlist COMMA expr */
  98886. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  98887. break;
  98888. case 241: /* nexprlist ::= expr */
  98889. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  98890. break;
  98891. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  98892. {
  98893. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  98894. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  98895. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  98896. }
  98897. break;
  98898. case 243: /* uniqueflag ::= UNIQUE */
  98899. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  98900. {yygotominor.yy392 = OE_Abort;}
  98901. break;
  98902. case 244: /* uniqueflag ::= */
  98903. {yygotominor.yy392 = OE_None;}
  98904. break;
  98905. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  98906. {
  98907. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  98908. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  98909. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  98910. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  98911. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98912. }
  98913. break;
  98914. case 248: /* idxlist ::= nm collate sortorder */
  98915. {
  98916. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  98917. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  98918. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98919. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  98920. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98921. }
  98922. break;
  98923. case 249: /* collate ::= */
  98924. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  98925. break;
  98926. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  98927. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  98928. break;
  98929. case 252: /* cmd ::= VACUUM */
  98930. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  98931. {sqlite3Vacuum(pParse);}
  98932. break;
  98933. case 254: /* cmd ::= PRAGMA nm dbnm */
  98934. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  98935. break;
  98936. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  98937. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  98938. break;
  98939. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  98940. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  98941. break;
  98942. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  98943. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  98944. break;
  98945. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  98946. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  98947. break;
  98948. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  98949. {
  98950. Token all;
  98951. all.z = yymsp[-3].minor.yy0.z;
  98952. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  98953. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  98954. }
  98955. break;
  98956. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  98957. {
  98958. 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);
  98959. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  98960. }
  98961. break;
  98962. case 270: /* trigger_time ::= BEFORE */
  98963. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  98964. { yygotominor.yy392 = TK_BEFORE; }
  98965. break;
  98966. case 271: /* trigger_time ::= AFTER */
  98967. { yygotominor.yy392 = TK_AFTER; }
  98968. break;
  98969. case 272: /* trigger_time ::= INSTEAD OF */
  98970. { yygotominor.yy392 = TK_INSTEAD;}
  98971. break;
  98972. case 274: /* trigger_event ::= DELETE|INSERT */
  98973. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  98974. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  98975. break;
  98976. case 276: /* trigger_event ::= UPDATE OF inscollist */
  98977. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  98978. break;
  98979. case 279: /* when_clause ::= */
  98980. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  98981. { yygotominor.yy122 = 0; }
  98982. break;
  98983. case 280: /* when_clause ::= WHEN expr */
  98984. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  98985. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  98986. break;
  98987. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  98988. {
  98989. assert( yymsp[-2].minor.yy327!=0 );
  98990. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  98991. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  98992. yygotominor.yy327 = yymsp[-2].minor.yy327;
  98993. }
  98994. break;
  98995. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  98996. {
  98997. assert( yymsp[-1].minor.yy327!=0 );
  98998. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  98999. yygotominor.yy327 = yymsp[-1].minor.yy327;
  99000. }
  99001. break;
  99002. case 284: /* trnm ::= nm DOT nm */
  99003. {
  99004. yygotominor.yy0 = yymsp[0].minor.yy0;
  99005. sqlite3ErrorMsg(pParse,
  99006. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  99007. "statements within triggers");
  99008. }
  99009. break;
  99010. case 286: /* tridxby ::= INDEXED BY nm */
  99011. {
  99012. sqlite3ErrorMsg(pParse,
  99013. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  99014. "within triggers");
  99015. }
  99016. break;
  99017. case 287: /* tridxby ::= NOT INDEXED */
  99018. {
  99019. sqlite3ErrorMsg(pParse,
  99020. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  99021. "within triggers");
  99022. }
  99023. break;
  99024. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  99025. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  99026. break;
  99027. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  99028. {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);}
  99029. break;
  99030. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  99031. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  99032. break;
  99033. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  99034. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  99035. break;
  99036. case 292: /* trigger_cmd ::= select */
  99037. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  99038. break;
  99039. case 293: /* expr ::= RAISE LP IGNORE RP */
  99040. {
  99041. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  99042. if( yygotominor.yy342.pExpr ){
  99043. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  99044. }
  99045. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  99046. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  99047. }
  99048. break;
  99049. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  99050. {
  99051. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  99052. if( yygotominor.yy342.pExpr ) {
  99053. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  99054. }
  99055. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  99056. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  99057. }
  99058. break;
  99059. case 295: /* raisetype ::= ROLLBACK */
  99060. {yygotominor.yy392 = OE_Rollback;}
  99061. break;
  99062. case 297: /* raisetype ::= FAIL */
  99063. {yygotominor.yy392 = OE_Fail;}
  99064. break;
  99065. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  99066. {
  99067. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  99068. }
  99069. break;
  99070. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  99071. {
  99072. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  99073. }
  99074. break;
  99075. case 300: /* cmd ::= DETACH database_kw_opt expr */
  99076. {
  99077. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  99078. }
  99079. break;
  99080. case 305: /* cmd ::= REINDEX */
  99081. {sqlite3Reindex(pParse, 0, 0);}
  99082. break;
  99083. case 306: /* cmd ::= REINDEX nm dbnm */
  99084. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  99085. break;
  99086. case 307: /* cmd ::= ANALYZE */
  99087. {sqlite3Analyze(pParse, 0, 0);}
  99088. break;
  99089. case 308: /* cmd ::= ANALYZE nm dbnm */
  99090. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  99091. break;
  99092. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  99093. {
  99094. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  99095. }
  99096. break;
  99097. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  99098. {
  99099. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  99100. }
  99101. break;
  99102. case 311: /* add_column_fullname ::= fullname */
  99103. {
  99104. pParse->db->lookaside.bEnabled = 0;
  99105. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  99106. }
  99107. break;
  99108. case 314: /* cmd ::= create_vtab */
  99109. {sqlite3VtabFinishParse(pParse,0);}
  99110. break;
  99111. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  99112. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  99113. break;
  99114. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  99115. {
  99116. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  99117. }
  99118. break;
  99119. case 319: /* vtabarg ::= */
  99120. {sqlite3VtabArgInit(pParse);}
  99121. break;
  99122. case 321: /* vtabargtoken ::= ANY */
  99123. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  99124. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  99125. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  99126. break;
  99127. default:
  99128. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  99129. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  99130. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  99131. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  99132. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  99133. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  99134. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  99135. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  99136. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  99137. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  99138. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  99139. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  99140. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  99141. /* (44) type ::= */ yytestcase(yyruleno==44);
  99142. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  99143. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  99144. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  99145. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  99146. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  99147. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  99148. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  99149. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  99150. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  99151. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  99152. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  99153. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  99154. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  99155. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  99156. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  99157. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  99158. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  99159. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  99160. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  99161. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  99162. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  99163. break;
  99164. };
  99165. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  99166. yygoto = yyRuleInfo[yyruleno].lhs;
  99167. yysize = yyRuleInfo[yyruleno].nrhs;
  99168. yypParser->yyidx -= yysize;
  99169. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  99170. if( yyact < YYNSTATE ){
  99171. #ifdef NDEBUG
  99172. /* If we are not debugging and the reduce action popped at least
  99173. ** one element off the stack, then we can push the new element back
  99174. ** onto the stack here, and skip the stack overflow test in yy_shift().
  99175. ** That gives a significant speed improvement. */
  99176. if( yysize ){
  99177. yypParser->yyidx++;
  99178. yymsp -= yysize-1;
  99179. yymsp->stateno = (YYACTIONTYPE)yyact;
  99180. yymsp->major = (YYCODETYPE)yygoto;
  99181. yymsp->minor = yygotominor;
  99182. }else
  99183. #endif
  99184. {
  99185. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  99186. }
  99187. }else{
  99188. assert( yyact == YYNSTATE + YYNRULE + 1 );
  99189. yy_accept(yypParser);
  99190. }
  99191. }
  99192. /*
  99193. ** The following code executes when the parse fails
  99194. */
  99195. #ifndef YYNOERRORRECOVERY
  99196. static void yy_parse_failed(
  99197. yyParser *yypParser /* The parser */
  99198. ){
  99199. sqlite3ParserARG_FETCH;
  99200. #ifndef NDEBUG
  99201. if( yyTraceFILE ){
  99202. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  99203. }
  99204. #endif
  99205. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99206. /* Here code is inserted which will be executed whenever the
  99207. ** parser fails */
  99208. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99209. }
  99210. #endif /* YYNOERRORRECOVERY */
  99211. /*
  99212. ** The following code executes when a syntax error first occurs.
  99213. */
  99214. static void yy_syntax_error(
  99215. yyParser *yypParser, /* The parser */
  99216. int yymajor, /* The major type of the error token */
  99217. YYMINORTYPE yyminor /* The minor type of the error token */
  99218. ){
  99219. sqlite3ParserARG_FETCH;
  99220. #define TOKEN (yyminor.yy0)
  99221. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  99222. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  99223. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  99224. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99225. }
  99226. /*
  99227. ** The following is executed when the parser accepts
  99228. */
  99229. static void yy_accept(
  99230. yyParser *yypParser /* The parser */
  99231. ){
  99232. sqlite3ParserARG_FETCH;
  99233. #ifndef NDEBUG
  99234. if( yyTraceFILE ){
  99235. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  99236. }
  99237. #endif
  99238. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99239. /* Here code is inserted which will be executed whenever the
  99240. ** parser accepts */
  99241. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99242. }
  99243. /* The main parser program.
  99244. ** The first argument is a pointer to a structure obtained from
  99245. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  99246. ** The second argument is the major token number. The third is
  99247. ** the minor token. The fourth optional argument is whatever the
  99248. ** user wants (and specified in the grammar) and is available for
  99249. ** use by the action routines.
  99250. **
  99251. ** Inputs:
  99252. ** <ul>
  99253. ** <li> A pointer to the parser (an opaque structure.)
  99254. ** <li> The major token number.
  99255. ** <li> The minor token number.
  99256. ** <li> An option argument of a grammar-specified type.
  99257. ** </ul>
  99258. **
  99259. ** Outputs:
  99260. ** None.
  99261. */
  99262. SQLITE_PRIVATE void sqlite3Parser(
  99263. void *yyp, /* The parser */
  99264. int yymajor, /* The major token code number */
  99265. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  99266. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  99267. ){
  99268. YYMINORTYPE yyminorunion;
  99269. int yyact; /* The parser action. */
  99270. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  99271. int yyendofinput; /* True if we are at the end of input */
  99272. #endif
  99273. #ifdef YYERRORSYMBOL
  99274. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  99275. #endif
  99276. yyParser *yypParser; /* The parser */
  99277. /* (re)initialize the parser, if necessary */
  99278. yypParser = (yyParser*)yyp;
  99279. if( yypParser->yyidx<0 ){
  99280. #if YYSTACKDEPTH<=0
  99281. if( yypParser->yystksz <=0 ){
  99282. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  99283. yyminorunion = yyzerominor;
  99284. yyStackOverflow(yypParser, &yyminorunion);
  99285. return;
  99286. }
  99287. #endif
  99288. yypParser->yyidx = 0;
  99289. yypParser->yyerrcnt = -1;
  99290. yypParser->yystack[0].stateno = 0;
  99291. yypParser->yystack[0].major = 0;
  99292. }
  99293. yyminorunion.yy0 = yyminor;
  99294. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  99295. yyendofinput = (yymajor==0);
  99296. #endif
  99297. sqlite3ParserARG_STORE;
  99298. #ifndef NDEBUG
  99299. if( yyTraceFILE ){
  99300. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  99301. }
  99302. #endif
  99303. do{
  99304. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  99305. if( yyact<YYNSTATE ){
  99306. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  99307. yypParser->yyerrcnt--;
  99308. yymajor = YYNOCODE;
  99309. }else if( yyact < YYNSTATE + YYNRULE ){
  99310. yy_reduce(yypParser,yyact-YYNSTATE);
  99311. }else{
  99312. assert( yyact == YY_ERROR_ACTION );
  99313. #ifdef YYERRORSYMBOL
  99314. int yymx;
  99315. #endif
  99316. #ifndef NDEBUG
  99317. if( yyTraceFILE ){
  99318. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  99319. }
  99320. #endif
  99321. #ifdef YYERRORSYMBOL
  99322. /* A syntax error has occurred.
  99323. ** The response to an error depends upon whether or not the
  99324. ** grammar defines an error token "ERROR".
  99325. **
  99326. ** This is what we do if the grammar does define ERROR:
  99327. **
  99328. ** * Call the %syntax_error function.
  99329. **
  99330. ** * Begin popping the stack until we enter a state where
  99331. ** it is legal to shift the error symbol, then shift
  99332. ** the error symbol.
  99333. **
  99334. ** * Set the error count to three.
  99335. **
  99336. ** * Begin accepting and shifting new tokens. No new error
  99337. ** processing will occur until three tokens have been
  99338. ** shifted successfully.
  99339. **
  99340. */
  99341. if( yypParser->yyerrcnt<0 ){
  99342. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99343. }
  99344. yymx = yypParser->yystack[yypParser->yyidx].major;
  99345. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  99346. #ifndef NDEBUG
  99347. if( yyTraceFILE ){
  99348. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  99349. yyTracePrompt,yyTokenName[yymajor]);
  99350. }
  99351. #endif
  99352. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  99353. yymajor = YYNOCODE;
  99354. }else{
  99355. while(
  99356. yypParser->yyidx >= 0 &&
  99357. yymx != YYERRORSYMBOL &&
  99358. (yyact = yy_find_reduce_action(
  99359. yypParser->yystack[yypParser->yyidx].stateno,
  99360. YYERRORSYMBOL)) >= YYNSTATE
  99361. ){
  99362. yy_pop_parser_stack(yypParser);
  99363. }
  99364. if( yypParser->yyidx < 0 || yymajor==0 ){
  99365. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99366. yy_parse_failed(yypParser);
  99367. yymajor = YYNOCODE;
  99368. }else if( yymx!=YYERRORSYMBOL ){
  99369. YYMINORTYPE u2;
  99370. u2.YYERRSYMDT = 0;
  99371. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  99372. }
  99373. }
  99374. yypParser->yyerrcnt = 3;
  99375. yyerrorhit = 1;
  99376. #elif defined(YYNOERRORRECOVERY)
  99377. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  99378. ** do any kind of error recovery. Instead, simply invoke the syntax
  99379. ** error routine and continue going as if nothing had happened.
  99380. **
  99381. ** Applications can set this macro (for example inside %include) if
  99382. ** they intend to abandon the parse upon the first syntax error seen.
  99383. */
  99384. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99385. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99386. yymajor = YYNOCODE;
  99387. #else /* YYERRORSYMBOL is not defined */
  99388. /* This is what we do if the grammar does not define ERROR:
  99389. **
  99390. ** * Report an error message, and throw away the input token.
  99391. **
  99392. ** * If the input token is $, then fail the parse.
  99393. **
  99394. ** As before, subsequent error messages are suppressed until
  99395. ** three input tokens have been successfully shifted.
  99396. */
  99397. if( yypParser->yyerrcnt<=0 ){
  99398. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99399. }
  99400. yypParser->yyerrcnt = 3;
  99401. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99402. if( yyendofinput ){
  99403. yy_parse_failed(yypParser);
  99404. }
  99405. yymajor = YYNOCODE;
  99406. #endif
  99407. }
  99408. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  99409. return;
  99410. }
  99411. /************** End of parse.c ***********************************************/
  99412. /************** Begin file tokenize.c ****************************************/
  99413. /*
  99414. ** 2001 September 15
  99415. **
  99416. ** The author disclaims copyright to this source code. In place of
  99417. ** a legal notice, here is a blessing:
  99418. **
  99419. ** May you do good and not evil.
  99420. ** May you find forgiveness for yourself and forgive others.
  99421. ** May you share freely, never taking more than you give.
  99422. **
  99423. *************************************************************************
  99424. ** An tokenizer for SQL
  99425. **
  99426. ** This file contains C code that splits an SQL input string up into
  99427. ** individual tokens and sends those tokens one-by-one over to the
  99428. ** parser for analysis.
  99429. */
  99430. /* #include <stdlib.h> */
  99431. /*
  99432. ** The charMap() macro maps alphabetic characters into their
  99433. ** lower-case ASCII equivalent. On ASCII machines, this is just
  99434. ** an upper-to-lower case map. On EBCDIC machines we also need
  99435. ** to adjust the encoding. Only alphabetic characters and underscores
  99436. ** need to be translated.
  99437. */
  99438. #ifdef SQLITE_ASCII
  99439. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  99440. #endif
  99441. #ifdef SQLITE_EBCDIC
  99442. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  99443. const unsigned char ebcdicToAscii[] = {
  99444. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  99445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  99446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  99447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  99448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  99449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  99450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  99451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  99452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99453. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  99454. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  99455. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  99456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99457. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  99458. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  99459. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  99460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  99461. };
  99462. #endif
  99463. /*
  99464. ** The sqlite3KeywordCode function looks up an identifier to determine if
  99465. ** it is a keyword. If it is a keyword, the token code of that keyword is
  99466. ** returned. If the input is not a keyword, TK_ID is returned.
  99467. **
  99468. ** The implementation of this routine was generated by a program,
  99469. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  99470. ** The output of the mkkeywordhash.c program is written into a file
  99471. ** named keywordhash.h and then included into this source file by
  99472. ** the #include below.
  99473. */
  99474. /************** Include keywordhash.h in the middle of tokenize.c ************/
  99475. /************** Begin file keywordhash.h *************************************/
  99476. /***** This file contains automatically generated code ******
  99477. **
  99478. ** The code in this file has been automatically generated by
  99479. **
  99480. ** sqlite/tool/mkkeywordhash.c
  99481. **
  99482. ** The code in this file implements a function that determines whether
  99483. ** or not a given identifier is really an SQL keyword. The same thing
  99484. ** might be implemented more directly using a hand-written hash table.
  99485. ** But by using this automatically generated code, the size of the code
  99486. ** is substantially reduced. This is important for embedded applications
  99487. ** on platforms with limited memory.
  99488. */
  99489. /* Hash score: 175 */
  99490. static int keywordCode(const char *z, int n){
  99491. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  99492. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  99493. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  99494. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  99495. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  99496. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  99497. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  99498. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  99499. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  99500. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  99501. /* INITIALLY */
  99502. static const char zText[540] = {
  99503. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  99504. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  99505. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  99506. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  99507. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  99508. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  99509. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  99510. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  99511. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  99512. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  99513. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  99514. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  99515. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  99516. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  99517. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  99518. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  99519. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  99520. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  99521. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  99522. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  99523. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  99524. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  99525. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  99526. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  99527. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  99528. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  99529. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  99530. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  99531. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  99532. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  99533. };
  99534. static const unsigned char aHash[127] = {
  99535. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  99536. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  99537. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  99538. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  99539. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  99540. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  99541. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  99542. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  99543. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  99544. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  99545. };
  99546. static const unsigned char aNext[121] = {
  99547. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  99548. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  99549. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  99550. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  99551. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  99552. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  99553. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  99554. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  99555. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  99556. 35, 64, 0, 0,
  99557. };
  99558. static const unsigned char aLen[121] = {
  99559. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  99560. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  99561. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  99562. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  99563. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  99564. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  99565. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  99566. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  99567. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  99568. 6, 4, 9, 3,
  99569. };
  99570. static const unsigned short int aOffset[121] = {
  99571. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  99572. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  99573. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  99574. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  99575. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  99576. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  99577. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  99578. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  99579. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  99580. 521, 527, 531, 536,
  99581. };
  99582. static const unsigned char aCode[121] = {
  99583. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  99584. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  99585. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  99586. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  99587. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  99588. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  99589. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  99590. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  99591. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  99592. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  99593. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  99594. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  99595. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  99596. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  99597. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  99598. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  99599. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  99600. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  99601. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  99602. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  99603. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  99604. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  99605. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  99606. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  99607. TK_ALL,
  99608. };
  99609. int h, i;
  99610. if( n<2 ) return TK_ID;
  99611. h = ((charMap(z[0])*4) ^
  99612. (charMap(z[n-1])*3) ^
  99613. n) % 127;
  99614. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  99615. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  99616. testcase( i==0 ); /* REINDEX */
  99617. testcase( i==1 ); /* INDEXED */
  99618. testcase( i==2 ); /* INDEX */
  99619. testcase( i==3 ); /* DESC */
  99620. testcase( i==4 ); /* ESCAPE */
  99621. testcase( i==5 ); /* EACH */
  99622. testcase( i==6 ); /* CHECK */
  99623. testcase( i==7 ); /* KEY */
  99624. testcase( i==8 ); /* BEFORE */
  99625. testcase( i==9 ); /* FOREIGN */
  99626. testcase( i==10 ); /* FOR */
  99627. testcase( i==11 ); /* IGNORE */
  99628. testcase( i==12 ); /* REGEXP */
  99629. testcase( i==13 ); /* EXPLAIN */
  99630. testcase( i==14 ); /* INSTEAD */
  99631. testcase( i==15 ); /* ADD */
  99632. testcase( i==16 ); /* DATABASE */
  99633. testcase( i==17 ); /* AS */
  99634. testcase( i==18 ); /* SELECT */
  99635. testcase( i==19 ); /* TABLE */
  99636. testcase( i==20 ); /* LEFT */
  99637. testcase( i==21 ); /* THEN */
  99638. testcase( i==22 ); /* END */
  99639. testcase( i==23 ); /* DEFERRABLE */
  99640. testcase( i==24 ); /* ELSE */
  99641. testcase( i==25 ); /* EXCEPT */
  99642. testcase( i==26 ); /* TRANSACTION */
  99643. testcase( i==27 ); /* ACTION */
  99644. testcase( i==28 ); /* ON */
  99645. testcase( i==29 ); /* NATURAL */
  99646. testcase( i==30 ); /* ALTER */
  99647. testcase( i==31 ); /* RAISE */
  99648. testcase( i==32 ); /* EXCLUSIVE */
  99649. testcase( i==33 ); /* EXISTS */
  99650. testcase( i==34 ); /* SAVEPOINT */
  99651. testcase( i==35 ); /* INTERSECT */
  99652. testcase( i==36 ); /* TRIGGER */
  99653. testcase( i==37 ); /* REFERENCES */
  99654. testcase( i==38 ); /* CONSTRAINT */
  99655. testcase( i==39 ); /* INTO */
  99656. testcase( i==40 ); /* OFFSET */
  99657. testcase( i==41 ); /* OF */
  99658. testcase( i==42 ); /* SET */
  99659. testcase( i==43 ); /* TEMPORARY */
  99660. testcase( i==44 ); /* TEMP */
  99661. testcase( i==45 ); /* OR */
  99662. testcase( i==46 ); /* UNIQUE */
  99663. testcase( i==47 ); /* QUERY */
  99664. testcase( i==48 ); /* ATTACH */
  99665. testcase( i==49 ); /* HAVING */
  99666. testcase( i==50 ); /* GROUP */
  99667. testcase( i==51 ); /* UPDATE */
  99668. testcase( i==52 ); /* BEGIN */
  99669. testcase( i==53 ); /* INNER */
  99670. testcase( i==54 ); /* RELEASE */
  99671. testcase( i==55 ); /* BETWEEN */
  99672. testcase( i==56 ); /* NOTNULL */
  99673. testcase( i==57 ); /* NOT */
  99674. testcase( i==58 ); /* NO */
  99675. testcase( i==59 ); /* NULL */
  99676. testcase( i==60 ); /* LIKE */
  99677. testcase( i==61 ); /* CASCADE */
  99678. testcase( i==62 ); /* ASC */
  99679. testcase( i==63 ); /* DELETE */
  99680. testcase( i==64 ); /* CASE */
  99681. testcase( i==65 ); /* COLLATE */
  99682. testcase( i==66 ); /* CREATE */
  99683. testcase( i==67 ); /* CURRENT_DATE */
  99684. testcase( i==68 ); /* DETACH */
  99685. testcase( i==69 ); /* IMMEDIATE */
  99686. testcase( i==70 ); /* JOIN */
  99687. testcase( i==71 ); /* INSERT */
  99688. testcase( i==72 ); /* MATCH */
  99689. testcase( i==73 ); /* PLAN */
  99690. testcase( i==74 ); /* ANALYZE */
  99691. testcase( i==75 ); /* PRAGMA */
  99692. testcase( i==76 ); /* ABORT */
  99693. testcase( i==77 ); /* VALUES */
  99694. testcase( i==78 ); /* VIRTUAL */
  99695. testcase( i==79 ); /* LIMIT */
  99696. testcase( i==80 ); /* WHEN */
  99697. testcase( i==81 ); /* WHERE */
  99698. testcase( i==82 ); /* RENAME */
  99699. testcase( i==83 ); /* AFTER */
  99700. testcase( i==84 ); /* REPLACE */
  99701. testcase( i==85 ); /* AND */
  99702. testcase( i==86 ); /* DEFAULT */
  99703. testcase( i==87 ); /* AUTOINCREMENT */
  99704. testcase( i==88 ); /* TO */
  99705. testcase( i==89 ); /* IN */
  99706. testcase( i==90 ); /* CAST */
  99707. testcase( i==91 ); /* COLUMN */
  99708. testcase( i==92 ); /* COMMIT */
  99709. testcase( i==93 ); /* CONFLICT */
  99710. testcase( i==94 ); /* CROSS */
  99711. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  99712. testcase( i==96 ); /* CURRENT_TIME */
  99713. testcase( i==97 ); /* PRIMARY */
  99714. testcase( i==98 ); /* DEFERRED */
  99715. testcase( i==99 ); /* DISTINCT */
  99716. testcase( i==100 ); /* IS */
  99717. testcase( i==101 ); /* DROP */
  99718. testcase( i==102 ); /* FAIL */
  99719. testcase( i==103 ); /* FROM */
  99720. testcase( i==104 ); /* FULL */
  99721. testcase( i==105 ); /* GLOB */
  99722. testcase( i==106 ); /* BY */
  99723. testcase( i==107 ); /* IF */
  99724. testcase( i==108 ); /* ISNULL */
  99725. testcase( i==109 ); /* ORDER */
  99726. testcase( i==110 ); /* RESTRICT */
  99727. testcase( i==111 ); /* OUTER */
  99728. testcase( i==112 ); /* RIGHT */
  99729. testcase( i==113 ); /* ROLLBACK */
  99730. testcase( i==114 ); /* ROW */
  99731. testcase( i==115 ); /* UNION */
  99732. testcase( i==116 ); /* USING */
  99733. testcase( i==117 ); /* VACUUM */
  99734. testcase( i==118 ); /* VIEW */
  99735. testcase( i==119 ); /* INITIALLY */
  99736. testcase( i==120 ); /* ALL */
  99737. return aCode[i];
  99738. }
  99739. }
  99740. return TK_ID;
  99741. }
  99742. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  99743. return keywordCode((char*)z, n);
  99744. }
  99745. #define SQLITE_N_KEYWORD 121
  99746. /************** End of keywordhash.h *****************************************/
  99747. /************** Continuing where we left off in tokenize.c *******************/
  99748. /*
  99749. ** If X is a character that can be used in an identifier then
  99750. ** IdChar(X) will be true. Otherwise it is false.
  99751. **
  99752. ** For ASCII, any character with the high-order bit set is
  99753. ** allowed in an identifier. For 7-bit characters,
  99754. ** sqlite3IsIdChar[X] must be 1.
  99755. **
  99756. ** For EBCDIC, the rules are more complex but have the same
  99757. ** end result.
  99758. **
  99759. ** Ticket #1066. the SQL standard does not allow '$' in the
  99760. ** middle of identfiers. But many SQL implementations do.
  99761. ** SQLite will allow '$' in identifiers for compatibility.
  99762. ** But the feature is undocumented.
  99763. */
  99764. #ifdef SQLITE_ASCII
  99765. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  99766. #endif
  99767. #ifdef SQLITE_EBCDIC
  99768. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  99769. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  99770. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  99771. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  99772. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  99773. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99774. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  99775. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  99776. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  99777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99778. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  99779. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  99780. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  99781. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  99782. };
  99783. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  99784. #endif
  99785. /*
  99786. ** Return the length of the token that begins at z[0].
  99787. ** Store the token type in *tokenType before returning.
  99788. */
  99789. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  99790. int i, c;
  99791. switch( *z ){
  99792. case ' ': case '\t': case '\n': case '\f': case '\r': {
  99793. testcase( z[0]==' ' );
  99794. testcase( z[0]=='\t' );
  99795. testcase( z[0]=='\n' );
  99796. testcase( z[0]=='\f' );
  99797. testcase( z[0]=='\r' );
  99798. for(i=1; sqlite3Isspace(z[i]); i++){}
  99799. *tokenType = TK_SPACE;
  99800. return i;
  99801. }
  99802. case '-': {
  99803. if( z[1]=='-' ){
  99804. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  99805. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99806. return i;
  99807. }
  99808. *tokenType = TK_MINUS;
  99809. return 1;
  99810. }
  99811. case '(': {
  99812. *tokenType = TK_LP;
  99813. return 1;
  99814. }
  99815. case ')': {
  99816. *tokenType = TK_RP;
  99817. return 1;
  99818. }
  99819. case ';': {
  99820. *tokenType = TK_SEMI;
  99821. return 1;
  99822. }
  99823. case '+': {
  99824. *tokenType = TK_PLUS;
  99825. return 1;
  99826. }
  99827. case '*': {
  99828. *tokenType = TK_STAR;
  99829. return 1;
  99830. }
  99831. case '/': {
  99832. if( z[1]!='*' || z[2]==0 ){
  99833. *tokenType = TK_SLASH;
  99834. return 1;
  99835. }
  99836. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  99837. if( c ) i++;
  99838. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99839. return i;
  99840. }
  99841. case '%': {
  99842. *tokenType = TK_REM;
  99843. return 1;
  99844. }
  99845. case '=': {
  99846. *tokenType = TK_EQ;
  99847. return 1 + (z[1]=='=');
  99848. }
  99849. case '<': {
  99850. if( (c=z[1])=='=' ){
  99851. *tokenType = TK_LE;
  99852. return 2;
  99853. }else if( c=='>' ){
  99854. *tokenType = TK_NE;
  99855. return 2;
  99856. }else if( c=='<' ){
  99857. *tokenType = TK_LSHIFT;
  99858. return 2;
  99859. }else{
  99860. *tokenType = TK_LT;
  99861. return 1;
  99862. }
  99863. }
  99864. case '>': {
  99865. if( (c=z[1])=='=' ){
  99866. *tokenType = TK_GE;
  99867. return 2;
  99868. }else if( c=='>' ){
  99869. *tokenType = TK_RSHIFT;
  99870. return 2;
  99871. }else{
  99872. *tokenType = TK_GT;
  99873. return 1;
  99874. }
  99875. }
  99876. case '!': {
  99877. if( z[1]!='=' ){
  99878. *tokenType = TK_ILLEGAL;
  99879. return 2;
  99880. }else{
  99881. *tokenType = TK_NE;
  99882. return 2;
  99883. }
  99884. }
  99885. case '|': {
  99886. if( z[1]!='|' ){
  99887. *tokenType = TK_BITOR;
  99888. return 1;
  99889. }else{
  99890. *tokenType = TK_CONCAT;
  99891. return 2;
  99892. }
  99893. }
  99894. case ',': {
  99895. *tokenType = TK_COMMA;
  99896. return 1;
  99897. }
  99898. case '&': {
  99899. *tokenType = TK_BITAND;
  99900. return 1;
  99901. }
  99902. case '~': {
  99903. *tokenType = TK_BITNOT;
  99904. return 1;
  99905. }
  99906. case '`':
  99907. case '\'':
  99908. case '"': {
  99909. int delim = z[0];
  99910. testcase( delim=='`' );
  99911. testcase( delim=='\'' );
  99912. testcase( delim=='"' );
  99913. for(i=1; (c=z[i])!=0; i++){
  99914. if( c==delim ){
  99915. if( z[i+1]==delim ){
  99916. i++;
  99917. }else{
  99918. break;
  99919. }
  99920. }
  99921. }
  99922. if( c=='\'' ){
  99923. *tokenType = TK_STRING;
  99924. return i+1;
  99925. }else if( c!=0 ){
  99926. *tokenType = TK_ID;
  99927. return i+1;
  99928. }else{
  99929. *tokenType = TK_ILLEGAL;
  99930. return i;
  99931. }
  99932. }
  99933. case '.': {
  99934. #ifndef SQLITE_OMIT_FLOATING_POINT
  99935. if( !sqlite3Isdigit(z[1]) )
  99936. #endif
  99937. {
  99938. *tokenType = TK_DOT;
  99939. return 1;
  99940. }
  99941. /* If the next character is a digit, this is a floating point
  99942. ** number that begins with ".". Fall thru into the next case */
  99943. }
  99944. case '0': case '1': case '2': case '3': case '4':
  99945. case '5': case '6': case '7': case '8': case '9': {
  99946. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  99947. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  99948. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  99949. testcase( z[0]=='9' );
  99950. *tokenType = TK_INTEGER;
  99951. for(i=0; sqlite3Isdigit(z[i]); i++){}
  99952. #ifndef SQLITE_OMIT_FLOATING_POINT
  99953. if( z[i]=='.' ){
  99954. i++;
  99955. while( sqlite3Isdigit(z[i]) ){ i++; }
  99956. *tokenType = TK_FLOAT;
  99957. }
  99958. if( (z[i]=='e' || z[i]=='E') &&
  99959. ( sqlite3Isdigit(z[i+1])
  99960. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  99961. )
  99962. ){
  99963. i += 2;
  99964. while( sqlite3Isdigit(z[i]) ){ i++; }
  99965. *tokenType = TK_FLOAT;
  99966. }
  99967. #endif
  99968. while( IdChar(z[i]) ){
  99969. *tokenType = TK_ILLEGAL;
  99970. i++;
  99971. }
  99972. return i;
  99973. }
  99974. case '[': {
  99975. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  99976. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  99977. return i;
  99978. }
  99979. case '?': {
  99980. *tokenType = TK_VARIABLE;
  99981. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99982. return i;
  99983. }
  99984. case '#': {
  99985. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99986. if( i>1 ){
  99987. /* Parameters of the form #NNN (where NNN is a number) are used
  99988. ** internally by sqlite3NestedParse. */
  99989. *tokenType = TK_REGISTER;
  99990. return i;
  99991. }
  99992. /* Fall through into the next case if the '#' is not followed by
  99993. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  99994. }
  99995. #ifndef SQLITE_OMIT_TCL_VARIABLE
  99996. case '$':
  99997. #endif
  99998. case '@': /* For compatibility with MS SQL Server */
  99999. case ':': {
  100000. int n = 0;
  100001. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  100002. *tokenType = TK_VARIABLE;
  100003. for(i=1; (c=z[i])!=0; i++){
  100004. if( IdChar(c) ){
  100005. n++;
  100006. #ifndef SQLITE_OMIT_TCL_VARIABLE
  100007. }else if( c=='(' && n>0 ){
  100008. do{
  100009. i++;
  100010. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  100011. if( c==')' ){
  100012. i++;
  100013. }else{
  100014. *tokenType = TK_ILLEGAL;
  100015. }
  100016. break;
  100017. }else if( c==':' && z[i+1]==':' ){
  100018. i++;
  100019. #endif
  100020. }else{
  100021. break;
  100022. }
  100023. }
  100024. if( n==0 ) *tokenType = TK_ILLEGAL;
  100025. return i;
  100026. }
  100027. #ifndef SQLITE_OMIT_BLOB_LITERAL
  100028. case 'x': case 'X': {
  100029. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  100030. if( z[1]=='\'' ){
  100031. *tokenType = TK_BLOB;
  100032. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  100033. if( z[i]!='\'' || i%2 ){
  100034. *tokenType = TK_ILLEGAL;
  100035. while( z[i] && z[i]!='\'' ){ i++; }
  100036. }
  100037. if( z[i] ) i++;
  100038. return i;
  100039. }
  100040. /* Otherwise fall through to the next case */
  100041. }
  100042. #endif
  100043. default: {
  100044. if( !IdChar(*z) ){
  100045. break;
  100046. }
  100047. for(i=1; IdChar(z[i]); i++){}
  100048. *tokenType = keywordCode((char*)z, i);
  100049. return i;
  100050. }
  100051. }
  100052. *tokenType = TK_ILLEGAL;
  100053. return 1;
  100054. }
  100055. /*
  100056. ** Run the parser on the given SQL string. The parser structure is
  100057. ** passed in. An SQLITE_ status code is returned. If an error occurs
  100058. ** then an and attempt is made to write an error message into
  100059. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  100060. ** error message.
  100061. */
  100062. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  100063. int nErr = 0; /* Number of errors encountered */
  100064. int i; /* Loop counter */
  100065. void *pEngine; /* The LEMON-generated LALR(1) parser */
  100066. int tokenType; /* type of the next token */
  100067. int lastTokenParsed = -1; /* type of the previous token */
  100068. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  100069. sqlite3 *db = pParse->db; /* The database connection */
  100070. int mxSqlLen; /* Max length of an SQL string */
  100071. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  100072. if( db->nVdbeActive==0 ){
  100073. db->u1.isInterrupted = 0;
  100074. }
  100075. pParse->rc = SQLITE_OK;
  100076. pParse->zTail = zSql;
  100077. i = 0;
  100078. assert( pzErrMsg!=0 );
  100079. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  100080. if( pEngine==0 ){
  100081. db->mallocFailed = 1;
  100082. return SQLITE_NOMEM;
  100083. }
  100084. assert( pParse->pNewTable==0 );
  100085. assert( pParse->pNewTrigger==0 );
  100086. assert( pParse->nVar==0 );
  100087. assert( pParse->nzVar==0 );
  100088. assert( pParse->azVar==0 );
  100089. enableLookaside = db->lookaside.bEnabled;
  100090. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  100091. while( !db->mallocFailed && zSql[i]!=0 ){
  100092. assert( i>=0 );
  100093. pParse->sLastToken.z = &zSql[i];
  100094. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  100095. i += pParse->sLastToken.n;
  100096. if( i>mxSqlLen ){
  100097. pParse->rc = SQLITE_TOOBIG;
  100098. break;
  100099. }
  100100. switch( tokenType ){
  100101. case TK_SPACE: {
  100102. if( db->u1.isInterrupted ){
  100103. sqlite3ErrorMsg(pParse, "interrupt");
  100104. pParse->rc = SQLITE_INTERRUPT;
  100105. goto abort_parse;
  100106. }
  100107. break;
  100108. }
  100109. case TK_ILLEGAL: {
  100110. sqlite3DbFree(db, *pzErrMsg);
  100111. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  100112. &pParse->sLastToken);
  100113. nErr++;
  100114. goto abort_parse;
  100115. }
  100116. case TK_SEMI: {
  100117. pParse->zTail = &zSql[i];
  100118. /* Fall thru into the default case */
  100119. }
  100120. default: {
  100121. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  100122. lastTokenParsed = tokenType;
  100123. if( pParse->rc!=SQLITE_OK ){
  100124. goto abort_parse;
  100125. }
  100126. break;
  100127. }
  100128. }
  100129. }
  100130. abort_parse:
  100131. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  100132. if( lastTokenParsed!=TK_SEMI ){
  100133. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  100134. pParse->zTail = &zSql[i];
  100135. }
  100136. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  100137. }
  100138. #ifdef YYTRACKMAXSTACKDEPTH
  100139. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  100140. sqlite3ParserStackPeak(pEngine)
  100141. );
  100142. #endif /* YYDEBUG */
  100143. sqlite3ParserFree(pEngine, sqlite3_free);
  100144. db->lookaside.bEnabled = enableLookaside;
  100145. if( db->mallocFailed ){
  100146. pParse->rc = SQLITE_NOMEM;
  100147. }
  100148. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  100149. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  100150. }
  100151. assert( pzErrMsg!=0 );
  100152. if( pParse->zErrMsg ){
  100153. *pzErrMsg = pParse->zErrMsg;
  100154. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  100155. pParse->zErrMsg = 0;
  100156. nErr++;
  100157. }
  100158. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  100159. sqlite3VdbeDelete(pParse->pVdbe);
  100160. pParse->pVdbe = 0;
  100161. }
  100162. #ifndef SQLITE_OMIT_SHARED_CACHE
  100163. if( pParse->nested==0 ){
  100164. sqlite3DbFree(db, pParse->aTableLock);
  100165. pParse->aTableLock = 0;
  100166. pParse->nTableLock = 0;
  100167. }
  100168. #endif
  100169. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100170. sqlite3_free(pParse->apVtabLock);
  100171. #endif
  100172. if( !IN_DECLARE_VTAB ){
  100173. /* If the pParse->declareVtab flag is set, do not delete any table
  100174. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  100175. ** will take responsibility for freeing the Table structure.
  100176. */
  100177. sqlite3DeleteTable(db, pParse->pNewTable);
  100178. }
  100179. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  100180. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  100181. sqlite3DbFree(db, pParse->azVar);
  100182. sqlite3DbFree(db, pParse->aAlias);
  100183. while( pParse->pAinc ){
  100184. AutoincInfo *p = pParse->pAinc;
  100185. pParse->pAinc = p->pNext;
  100186. sqlite3DbFree(db, p);
  100187. }
  100188. while( pParse->pZombieTab ){
  100189. Table *p = pParse->pZombieTab;
  100190. pParse->pZombieTab = p->pNextZombie;
  100191. sqlite3DeleteTable(db, p);
  100192. }
  100193. if( nErr>0 && pParse->rc==SQLITE_OK ){
  100194. pParse->rc = SQLITE_ERROR;
  100195. }
  100196. return nErr;
  100197. }
  100198. /************** End of tokenize.c ********************************************/
  100199. /************** Begin file complete.c ****************************************/
  100200. /*
  100201. ** 2001 September 15
  100202. **
  100203. ** The author disclaims copyright to this source code. In place of
  100204. ** a legal notice, here is a blessing:
  100205. **
  100206. ** May you do good and not evil.
  100207. ** May you find forgiveness for yourself and forgive others.
  100208. ** May you share freely, never taking more than you give.
  100209. **
  100210. *************************************************************************
  100211. ** An tokenizer for SQL
  100212. **
  100213. ** This file contains C code that implements the sqlite3_complete() API.
  100214. ** This code used to be part of the tokenizer.c source file. But by
  100215. ** separating it out, the code will be automatically omitted from
  100216. ** static links that do not use it.
  100217. */
  100218. #ifndef SQLITE_OMIT_COMPLETE
  100219. /*
  100220. ** This is defined in tokenize.c. We just have to import the definition.
  100221. */
  100222. #ifndef SQLITE_AMALGAMATION
  100223. #ifdef SQLITE_ASCII
  100224. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  100225. #endif
  100226. #ifdef SQLITE_EBCDIC
  100227. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  100228. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  100229. #endif
  100230. #endif /* SQLITE_AMALGAMATION */
  100231. /*
  100232. ** Token types used by the sqlite3_complete() routine. See the header
  100233. ** comments on that procedure for additional information.
  100234. */
  100235. #define tkSEMI 0
  100236. #define tkWS 1
  100237. #define tkOTHER 2
  100238. #ifndef SQLITE_OMIT_TRIGGER
  100239. #define tkEXPLAIN 3
  100240. #define tkCREATE 4
  100241. #define tkTEMP 5
  100242. #define tkTRIGGER 6
  100243. #define tkEND 7
  100244. #endif
  100245. /*
  100246. ** Return TRUE if the given SQL string ends in a semicolon.
  100247. **
  100248. ** Special handling is require for CREATE TRIGGER statements.
  100249. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  100250. ** must end with ";END;".
  100251. **
  100252. ** This implementation uses a state machine with 8 states:
  100253. **
  100254. ** (0) INVALID We have not yet seen a non-whitespace character.
  100255. **
  100256. ** (1) START At the beginning or end of an SQL statement. This routine
  100257. ** returns 1 if it ends in the START state and 0 if it ends
  100258. ** in any other state.
  100259. **
  100260. ** (2) NORMAL We are in the middle of statement which ends with a single
  100261. ** semicolon.
  100262. **
  100263. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  100264. ** a statement.
  100265. **
  100266. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  100267. ** statement, possibly preceeded by EXPLAIN and/or followed by
  100268. ** TEMP or TEMPORARY
  100269. **
  100270. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  100271. ** ended by a semicolon, the keyword END, and another semicolon.
  100272. **
  100273. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  100274. ** the end of a trigger definition.
  100275. **
  100276. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  100277. ** of a trigger difinition.
  100278. **
  100279. ** Transitions between states above are determined by tokens extracted
  100280. ** from the input. The following tokens are significant:
  100281. **
  100282. ** (0) tkSEMI A semicolon.
  100283. ** (1) tkWS Whitespace.
  100284. ** (2) tkOTHER Any other SQL token.
  100285. ** (3) tkEXPLAIN The "explain" keyword.
  100286. ** (4) tkCREATE The "create" keyword.
  100287. ** (5) tkTEMP The "temp" or "temporary" keyword.
  100288. ** (6) tkTRIGGER The "trigger" keyword.
  100289. ** (7) tkEND The "end" keyword.
  100290. **
  100291. ** Whitespace never causes a state transition and is always ignored.
  100292. ** This means that a SQL string of all whitespace is invalid.
  100293. **
  100294. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  100295. ** to recognize the end of a trigger can be omitted. All we have to do
  100296. ** is look for a semicolon that is not part of an string or comment.
  100297. */
  100298. SQLITE_API int sqlite3_complete(const char *zSql){
  100299. u8 state = 0; /* Current state, using numbers defined in header comment */
  100300. u8 token; /* Value of the next token */
  100301. #ifndef SQLITE_OMIT_TRIGGER
  100302. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  100303. ** statement. This is the normal case.
  100304. */
  100305. static const u8 trans[8][8] = {
  100306. /* Token: */
  100307. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  100308. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  100309. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  100310. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  100311. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  100312. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  100313. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  100314. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  100315. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  100316. };
  100317. #else
  100318. /* If triggers are not supported by this compile then the statement machine
  100319. ** used to detect the end of a statement is much simplier
  100320. */
  100321. static const u8 trans[3][3] = {
  100322. /* Token: */
  100323. /* State: ** SEMI WS OTHER */
  100324. /* 0 INVALID: */ { 1, 0, 2, },
  100325. /* 1 START: */ { 1, 1, 2, },
  100326. /* 2 NORMAL: */ { 1, 2, 2, },
  100327. };
  100328. #endif /* SQLITE_OMIT_TRIGGER */
  100329. while( *zSql ){
  100330. switch( *zSql ){
  100331. case ';': { /* A semicolon */
  100332. token = tkSEMI;
  100333. break;
  100334. }
  100335. case ' ':
  100336. case '\r':
  100337. case '\t':
  100338. case '\n':
  100339. case '\f': { /* White space is ignored */
  100340. token = tkWS;
  100341. break;
  100342. }
  100343. case '/': { /* C-style comments */
  100344. if( zSql[1]!='*' ){
  100345. token = tkOTHER;
  100346. break;
  100347. }
  100348. zSql += 2;
  100349. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  100350. if( zSql[0]==0 ) return 0;
  100351. zSql++;
  100352. token = tkWS;
  100353. break;
  100354. }
  100355. case '-': { /* SQL-style comments from "--" to end of line */
  100356. if( zSql[1]!='-' ){
  100357. token = tkOTHER;
  100358. break;
  100359. }
  100360. while( *zSql && *zSql!='\n' ){ zSql++; }
  100361. if( *zSql==0 ) return state==1;
  100362. token = tkWS;
  100363. break;
  100364. }
  100365. case '[': { /* Microsoft-style identifiers in [...] */
  100366. zSql++;
  100367. while( *zSql && *zSql!=']' ){ zSql++; }
  100368. if( *zSql==0 ) return 0;
  100369. token = tkOTHER;
  100370. break;
  100371. }
  100372. case '`': /* Grave-accent quoted symbols used by MySQL */
  100373. case '"': /* single- and double-quoted strings */
  100374. case '\'': {
  100375. int c = *zSql;
  100376. zSql++;
  100377. while( *zSql && *zSql!=c ){ zSql++; }
  100378. if( *zSql==0 ) return 0;
  100379. token = tkOTHER;
  100380. break;
  100381. }
  100382. default: {
  100383. #ifdef SQLITE_EBCDIC
  100384. unsigned char c;
  100385. #endif
  100386. if( IdChar((u8)*zSql) ){
  100387. /* Keywords and unquoted identifiers */
  100388. int nId;
  100389. for(nId=1; IdChar(zSql[nId]); nId++){}
  100390. #ifdef SQLITE_OMIT_TRIGGER
  100391. token = tkOTHER;
  100392. #else
  100393. switch( *zSql ){
  100394. case 'c': case 'C': {
  100395. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  100396. token = tkCREATE;
  100397. }else{
  100398. token = tkOTHER;
  100399. }
  100400. break;
  100401. }
  100402. case 't': case 'T': {
  100403. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  100404. token = tkTRIGGER;
  100405. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  100406. token = tkTEMP;
  100407. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  100408. token = tkTEMP;
  100409. }else{
  100410. token = tkOTHER;
  100411. }
  100412. break;
  100413. }
  100414. case 'e': case 'E': {
  100415. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  100416. token = tkEND;
  100417. }else
  100418. #ifndef SQLITE_OMIT_EXPLAIN
  100419. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  100420. token = tkEXPLAIN;
  100421. }else
  100422. #endif
  100423. {
  100424. token = tkOTHER;
  100425. }
  100426. break;
  100427. }
  100428. default: {
  100429. token = tkOTHER;
  100430. break;
  100431. }
  100432. }
  100433. #endif /* SQLITE_OMIT_TRIGGER */
  100434. zSql += nId-1;
  100435. }else{
  100436. /* Operators and special symbols */
  100437. token = tkOTHER;
  100438. }
  100439. break;
  100440. }
  100441. }
  100442. state = trans[state][token];
  100443. zSql++;
  100444. }
  100445. return state==1;
  100446. }
  100447. #ifndef SQLITE_OMIT_UTF16
  100448. /*
  100449. ** This routine is the same as the sqlite3_complete() routine described
  100450. ** above, except that the parameter is required to be UTF-16 encoded, not
  100451. ** UTF-8.
  100452. */
  100453. SQLITE_API int sqlite3_complete16(const void *zSql){
  100454. sqlite3_value *pVal;
  100455. char const *zSql8;
  100456. int rc = SQLITE_NOMEM;
  100457. #ifndef SQLITE_OMIT_AUTOINIT
  100458. rc = sqlite3_initialize();
  100459. if( rc ) return rc;
  100460. #endif
  100461. pVal = sqlite3ValueNew(0);
  100462. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  100463. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  100464. if( zSql8 ){
  100465. rc = sqlite3_complete(zSql8);
  100466. }else{
  100467. rc = SQLITE_NOMEM;
  100468. }
  100469. sqlite3ValueFree(pVal);
  100470. return sqlite3ApiExit(0, rc);
  100471. }
  100472. #endif /* SQLITE_OMIT_UTF16 */
  100473. #endif /* SQLITE_OMIT_COMPLETE */
  100474. /************** End of complete.c ********************************************/
  100475. /************** Begin file main.c ********************************************/
  100476. /*
  100477. ** 2001 September 15
  100478. **
  100479. ** The author disclaims copyright to this source code. In place of
  100480. ** a legal notice, here is a blessing:
  100481. **
  100482. ** May you do good and not evil.
  100483. ** May you find forgiveness for yourself and forgive others.
  100484. ** May you share freely, never taking more than you give.
  100485. **
  100486. *************************************************************************
  100487. ** Main file for the SQLite library. The routines in this file
  100488. ** implement the programmer interface to the library. Routines in
  100489. ** other files are for internal use by SQLite and should not be
  100490. ** accessed by users of the library.
  100491. */
  100492. #ifdef SQLITE_ENABLE_FTS3
  100493. /************** Include fts3.h in the middle of main.c ***********************/
  100494. /************** Begin file fts3.h ********************************************/
  100495. /*
  100496. ** 2006 Oct 10
  100497. **
  100498. ** The author disclaims copyright to this source code. In place of
  100499. ** a legal notice, here is a blessing:
  100500. **
  100501. ** May you do good and not evil.
  100502. ** May you find forgiveness for yourself and forgive others.
  100503. ** May you share freely, never taking more than you give.
  100504. **
  100505. ******************************************************************************
  100506. **
  100507. ** This header file is used by programs that want to link against the
  100508. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  100509. */
  100510. #if 0
  100511. extern "C" {
  100512. #endif /* __cplusplus */
  100513. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  100514. #if 0
  100515. } /* extern "C" */
  100516. #endif /* __cplusplus */
  100517. /************** End of fts3.h ************************************************/
  100518. /************** Continuing where we left off in main.c ***********************/
  100519. #endif
  100520. #ifdef SQLITE_ENABLE_RTREE
  100521. /************** Include rtree.h in the middle of main.c **********************/
  100522. /************** Begin file rtree.h *******************************************/
  100523. /*
  100524. ** 2008 May 26
  100525. **
  100526. ** The author disclaims copyright to this source code. In place of
  100527. ** a legal notice, here is a blessing:
  100528. **
  100529. ** May you do good and not evil.
  100530. ** May you find forgiveness for yourself and forgive others.
  100531. ** May you share freely, never taking more than you give.
  100532. **
  100533. ******************************************************************************
  100534. **
  100535. ** This header file is used by programs that want to link against the
  100536. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  100537. */
  100538. #if 0
  100539. extern "C" {
  100540. #endif /* __cplusplus */
  100541. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  100542. #if 0
  100543. } /* extern "C" */
  100544. #endif /* __cplusplus */
  100545. /************** End of rtree.h ***********************************************/
  100546. /************** Continuing where we left off in main.c ***********************/
  100547. #endif
  100548. #ifdef SQLITE_ENABLE_ICU
  100549. /************** Include sqliteicu.h in the middle of main.c ******************/
  100550. /************** Begin file sqliteicu.h ***************************************/
  100551. /*
  100552. ** 2008 May 26
  100553. **
  100554. ** The author disclaims copyright to this source code. In place of
  100555. ** a legal notice, here is a blessing:
  100556. **
  100557. ** May you do good and not evil.
  100558. ** May you find forgiveness for yourself and forgive others.
  100559. ** May you share freely, never taking more than you give.
  100560. **
  100561. ******************************************************************************
  100562. **
  100563. ** This header file is used by programs that want to link against the
  100564. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  100565. */
  100566. #if 0
  100567. extern "C" {
  100568. #endif /* __cplusplus */
  100569. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  100570. #if 0
  100571. } /* extern "C" */
  100572. #endif /* __cplusplus */
  100573. /************** End of sqliteicu.h *******************************************/
  100574. /************** Continuing where we left off in main.c ***********************/
  100575. #endif
  100576. #ifndef SQLITE_AMALGAMATION
  100577. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  100578. ** contains the text of SQLITE_VERSION macro.
  100579. */
  100580. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  100581. #endif
  100582. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  100583. ** a pointer to the to the sqlite3_version[] string constant.
  100584. */
  100585. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  100586. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  100587. ** pointer to a string constant whose value is the same as the
  100588. ** SQLITE_SOURCE_ID C preprocessor macro.
  100589. */
  100590. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  100591. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  100592. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  100593. */
  100594. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  100595. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  100596. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  100597. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  100598. */
  100599. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  100600. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  100601. /*
  100602. ** If the following function pointer is not NULL and if
  100603. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  100604. ** I/O active are written using this function. These messages
  100605. ** are intended for debugging activity only.
  100606. */
  100607. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  100608. #endif
  100609. /*
  100610. ** If the following global variable points to a string which is the
  100611. ** name of a directory, then that directory will be used to store
  100612. ** temporary files.
  100613. **
  100614. ** See also the "PRAGMA temp_store_directory" SQL command.
  100615. */
  100616. SQLITE_API char *sqlite3_temp_directory = 0;
  100617. /*
  100618. ** If the following global variable points to a string which is the
  100619. ** name of a directory, then that directory will be used to store
  100620. ** all database files specified with a relative pathname.
  100621. **
  100622. ** See also the "PRAGMA data_store_directory" SQL command.
  100623. */
  100624. SQLITE_API char *sqlite3_data_directory = 0;
  100625. /*
  100626. ** Initialize SQLite.
  100627. **
  100628. ** This routine must be called to initialize the memory allocation,
  100629. ** VFS, and mutex subsystems prior to doing any serious work with
  100630. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  100631. ** this routine will be called automatically by key routines such as
  100632. ** sqlite3_open().
  100633. **
  100634. ** This routine is a no-op except on its very first call for the process,
  100635. ** or for the first call after a call to sqlite3_shutdown.
  100636. **
  100637. ** The first thread to call this routine runs the initialization to
  100638. ** completion. If subsequent threads call this routine before the first
  100639. ** thread has finished the initialization process, then the subsequent
  100640. ** threads must block until the first thread finishes with the initialization.
  100641. **
  100642. ** The first thread might call this routine recursively. Recursive
  100643. ** calls to this routine should not block, of course. Otherwise the
  100644. ** initialization process would never complete.
  100645. **
  100646. ** Let X be the first thread to enter this routine. Let Y be some other
  100647. ** thread. Then while the initial invocation of this routine by X is
  100648. ** incomplete, it is required that:
  100649. **
  100650. ** * Calls to this routine from Y must block until the outer-most
  100651. ** call by X completes.
  100652. **
  100653. ** * Recursive calls to this routine from thread X return immediately
  100654. ** without blocking.
  100655. */
  100656. SQLITE_API int sqlite3_initialize(void){
  100657. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  100658. int rc; /* Result code */
  100659. #ifdef SQLITE_EXTRA_INIT
  100660. int bRunExtraInit = 0; /* Extra initialization needed */
  100661. #endif
  100662. #ifdef SQLITE_OMIT_WSD
  100663. rc = sqlite3_wsd_init(4096, 24);
  100664. if( rc!=SQLITE_OK ){
  100665. return rc;
  100666. }
  100667. #endif
  100668. /* If SQLite is already completely initialized, then this call
  100669. ** to sqlite3_initialize() should be a no-op. But the initialization
  100670. ** must be complete. So isInit must not be set until the very end
  100671. ** of this routine.
  100672. */
  100673. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  100674. #ifdef SQLITE_ENABLE_SQLLOG
  100675. {
  100676. extern void sqlite3_init_sqllog(void);
  100677. sqlite3_init_sqllog();
  100678. }
  100679. #endif
  100680. /* Make sure the mutex subsystem is initialized. If unable to
  100681. ** initialize the mutex subsystem, return early with the error.
  100682. ** If the system is so sick that we are unable to allocate a mutex,
  100683. ** there is not much SQLite is going to be able to do.
  100684. **
  100685. ** The mutex subsystem must take care of serializing its own
  100686. ** initialization.
  100687. */
  100688. rc = sqlite3MutexInit();
  100689. if( rc ) return rc;
  100690. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  100691. ** This operation is protected by the STATIC_MASTER mutex. Note that
  100692. ** MutexAlloc() is called for a static mutex prior to initializing the
  100693. ** malloc subsystem - this implies that the allocation of a static
  100694. ** mutex must not require support from the malloc subsystem.
  100695. */
  100696. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  100697. sqlite3_mutex_enter(pMaster);
  100698. sqlite3GlobalConfig.isMutexInit = 1;
  100699. if( !sqlite3GlobalConfig.isMallocInit ){
  100700. rc = sqlite3MallocInit();
  100701. }
  100702. if( rc==SQLITE_OK ){
  100703. sqlite3GlobalConfig.isMallocInit = 1;
  100704. if( !sqlite3GlobalConfig.pInitMutex ){
  100705. sqlite3GlobalConfig.pInitMutex =
  100706. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  100707. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  100708. rc = SQLITE_NOMEM;
  100709. }
  100710. }
  100711. }
  100712. if( rc==SQLITE_OK ){
  100713. sqlite3GlobalConfig.nRefInitMutex++;
  100714. }
  100715. sqlite3_mutex_leave(pMaster);
  100716. /* If rc is not SQLITE_OK at this point, then either the malloc
  100717. ** subsystem could not be initialized or the system failed to allocate
  100718. ** the pInitMutex mutex. Return an error in either case. */
  100719. if( rc!=SQLITE_OK ){
  100720. return rc;
  100721. }
  100722. /* Do the rest of the initialization under the recursive mutex so
  100723. ** that we will be able to handle recursive calls into
  100724. ** sqlite3_initialize(). The recursive calls normally come through
  100725. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  100726. ** recursive calls might also be possible.
  100727. **
  100728. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  100729. ** to the xInit method, so the xInit method need not be threadsafe.
  100730. **
  100731. ** The following mutex is what serializes access to the appdef pcache xInit
  100732. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  100733. ** call to sqlite3PcacheInitialize().
  100734. */
  100735. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  100736. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  100737. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  100738. sqlite3GlobalConfig.inProgress = 1;
  100739. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  100740. sqlite3RegisterGlobalFunctions();
  100741. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  100742. rc = sqlite3PcacheInitialize();
  100743. }
  100744. if( rc==SQLITE_OK ){
  100745. sqlite3GlobalConfig.isPCacheInit = 1;
  100746. rc = sqlite3OsInit();
  100747. }
  100748. if( rc==SQLITE_OK ){
  100749. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  100750. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  100751. sqlite3GlobalConfig.isInit = 1;
  100752. #ifdef SQLITE_EXTRA_INIT
  100753. bRunExtraInit = 1;
  100754. #endif
  100755. }
  100756. sqlite3GlobalConfig.inProgress = 0;
  100757. }
  100758. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  100759. /* Go back under the static mutex and clean up the recursive
  100760. ** mutex to prevent a resource leak.
  100761. */
  100762. sqlite3_mutex_enter(pMaster);
  100763. sqlite3GlobalConfig.nRefInitMutex--;
  100764. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  100765. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  100766. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  100767. sqlite3GlobalConfig.pInitMutex = 0;
  100768. }
  100769. sqlite3_mutex_leave(pMaster);
  100770. /* The following is just a sanity check to make sure SQLite has
  100771. ** been compiled correctly. It is important to run this code, but
  100772. ** we don't want to run it too often and soak up CPU cycles for no
  100773. ** reason. So we run it once during initialization.
  100774. */
  100775. #ifndef NDEBUG
  100776. #ifndef SQLITE_OMIT_FLOATING_POINT
  100777. /* This section of code's only "output" is via assert() statements. */
  100778. if ( rc==SQLITE_OK ){
  100779. u64 x = (((u64)1)<<63)-1;
  100780. double y;
  100781. assert(sizeof(x)==8);
  100782. assert(sizeof(x)==sizeof(y));
  100783. memcpy(&y, &x, 8);
  100784. assert( sqlite3IsNaN(y) );
  100785. }
  100786. #endif
  100787. #endif
  100788. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  100789. ** compile-time option.
  100790. */
  100791. #ifdef SQLITE_EXTRA_INIT
  100792. if( bRunExtraInit ){
  100793. int SQLITE_EXTRA_INIT(const char*);
  100794. rc = SQLITE_EXTRA_INIT(0);
  100795. }
  100796. #endif
  100797. return rc;
  100798. }
  100799. /*
  100800. ** Undo the effects of sqlite3_initialize(). Must not be called while
  100801. ** there are outstanding database connections or memory allocations or
  100802. ** while any part of SQLite is otherwise in use in any thread. This
  100803. ** routine is not threadsafe. But it is safe to invoke this routine
  100804. ** on when SQLite is already shut down. If SQLite is already shut down
  100805. ** when this routine is invoked, then this routine is a harmless no-op.
  100806. */
  100807. SQLITE_API int sqlite3_shutdown(void){
  100808. if( sqlite3GlobalConfig.isInit ){
  100809. #ifdef SQLITE_EXTRA_SHUTDOWN
  100810. void SQLITE_EXTRA_SHUTDOWN(void);
  100811. SQLITE_EXTRA_SHUTDOWN();
  100812. #endif
  100813. sqlite3_os_end();
  100814. sqlite3_reset_auto_extension();
  100815. sqlite3GlobalConfig.isInit = 0;
  100816. }
  100817. if( sqlite3GlobalConfig.isPCacheInit ){
  100818. sqlite3PcacheShutdown();
  100819. sqlite3GlobalConfig.isPCacheInit = 0;
  100820. }
  100821. if( sqlite3GlobalConfig.isMallocInit ){
  100822. sqlite3MallocEnd();
  100823. sqlite3GlobalConfig.isMallocInit = 0;
  100824. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  100825. /* The heap subsystem has now been shutdown and these values are supposed
  100826. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  100827. ** which would rely on that heap subsystem; therefore, make sure these
  100828. ** values cannot refer to heap memory that was just invalidated when the
  100829. ** heap subsystem was shutdown. This is only done if the current call to
  100830. ** this function resulted in the heap subsystem actually being shutdown.
  100831. */
  100832. sqlite3_data_directory = 0;
  100833. sqlite3_temp_directory = 0;
  100834. #endif
  100835. }
  100836. if( sqlite3GlobalConfig.isMutexInit ){
  100837. sqlite3MutexEnd();
  100838. sqlite3GlobalConfig.isMutexInit = 0;
  100839. }
  100840. return SQLITE_OK;
  100841. }
  100842. /*
  100843. ** This API allows applications to modify the global configuration of
  100844. ** the SQLite library at run-time.
  100845. **
  100846. ** This routine should only be called when there are no outstanding
  100847. ** database connections or memory allocations. This routine is not
  100848. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  100849. ** behavior.
  100850. */
  100851. SQLITE_API int sqlite3_config(int op, ...){
  100852. va_list ap;
  100853. int rc = SQLITE_OK;
  100854. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  100855. ** the SQLite library is in use. */
  100856. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  100857. va_start(ap, op);
  100858. switch( op ){
  100859. /* Mutex configuration options are only available in a threadsafe
  100860. ** compile.
  100861. */
  100862. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  100863. case SQLITE_CONFIG_SINGLETHREAD: {
  100864. /* Disable all mutexing */
  100865. sqlite3GlobalConfig.bCoreMutex = 0;
  100866. sqlite3GlobalConfig.bFullMutex = 0;
  100867. break;
  100868. }
  100869. case SQLITE_CONFIG_MULTITHREAD: {
  100870. /* Disable mutexing of database connections */
  100871. /* Enable mutexing of core data structures */
  100872. sqlite3GlobalConfig.bCoreMutex = 1;
  100873. sqlite3GlobalConfig.bFullMutex = 0;
  100874. break;
  100875. }
  100876. case SQLITE_CONFIG_SERIALIZED: {
  100877. /* Enable all mutexing */
  100878. sqlite3GlobalConfig.bCoreMutex = 1;
  100879. sqlite3GlobalConfig.bFullMutex = 1;
  100880. break;
  100881. }
  100882. case SQLITE_CONFIG_MUTEX: {
  100883. /* Specify an alternative mutex implementation */
  100884. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  100885. break;
  100886. }
  100887. case SQLITE_CONFIG_GETMUTEX: {
  100888. /* Retrieve the current mutex implementation */
  100889. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  100890. break;
  100891. }
  100892. #endif
  100893. case SQLITE_CONFIG_MALLOC: {
  100894. /* Specify an alternative malloc implementation */
  100895. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  100896. break;
  100897. }
  100898. case SQLITE_CONFIG_GETMALLOC: {
  100899. /* Retrieve the current malloc() implementation */
  100900. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  100901. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  100902. break;
  100903. }
  100904. case SQLITE_CONFIG_MEMSTATUS: {
  100905. /* Enable or disable the malloc status collection */
  100906. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  100907. break;
  100908. }
  100909. case SQLITE_CONFIG_SCRATCH: {
  100910. /* Designate a buffer for scratch memory space */
  100911. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  100912. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  100913. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  100914. break;
  100915. }
  100916. case SQLITE_CONFIG_PAGECACHE: {
  100917. /* Designate a buffer for page cache memory space */
  100918. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  100919. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  100920. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  100921. break;
  100922. }
  100923. case SQLITE_CONFIG_PCACHE: {
  100924. /* no-op */
  100925. break;
  100926. }
  100927. case SQLITE_CONFIG_GETPCACHE: {
  100928. /* now an error */
  100929. rc = SQLITE_ERROR;
  100930. break;
  100931. }
  100932. case SQLITE_CONFIG_PCACHE2: {
  100933. /* Specify an alternative page cache implementation */
  100934. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  100935. break;
  100936. }
  100937. case SQLITE_CONFIG_GETPCACHE2: {
  100938. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  100939. sqlite3PCacheSetDefault();
  100940. }
  100941. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  100942. break;
  100943. }
  100944. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  100945. case SQLITE_CONFIG_HEAP: {
  100946. /* Designate a buffer for heap memory space */
  100947. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  100948. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  100949. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  100950. if( sqlite3GlobalConfig.mnReq<1 ){
  100951. sqlite3GlobalConfig.mnReq = 1;
  100952. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  100953. /* cap min request size at 2^12 */
  100954. sqlite3GlobalConfig.mnReq = (1<<12);
  100955. }
  100956. if( sqlite3GlobalConfig.pHeap==0 ){
  100957. /* If the heap pointer is NULL, then restore the malloc implementation
  100958. ** back to NULL pointers too. This will cause the malloc to go
  100959. ** back to its default implementation when sqlite3_initialize() is
  100960. ** run.
  100961. */
  100962. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  100963. }else{
  100964. /* The heap pointer is not NULL, then install one of the
  100965. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  100966. ** least one of these methods is currently enabled.
  100967. */
  100968. #ifdef SQLITE_ENABLE_MEMSYS3
  100969. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  100970. #endif
  100971. #ifdef SQLITE_ENABLE_MEMSYS5
  100972. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  100973. #endif
  100974. }
  100975. break;
  100976. }
  100977. #endif
  100978. case SQLITE_CONFIG_LOOKASIDE: {
  100979. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  100980. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  100981. break;
  100982. }
  100983. /* Record a pointer to the logger function and its first argument.
  100984. ** The default is NULL. Logging is disabled if the function pointer is
  100985. ** NULL.
  100986. */
  100987. case SQLITE_CONFIG_LOG: {
  100988. /* MSVC is picky about pulling func ptrs from va lists.
  100989. ** http://support.microsoft.com/kb/47961
  100990. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  100991. */
  100992. typedef void(*LOGFUNC_t)(void*,int,const char*);
  100993. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  100994. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  100995. break;
  100996. }
  100997. case SQLITE_CONFIG_URI: {
  100998. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  100999. break;
  101000. }
  101001. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  101002. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  101003. break;
  101004. }
  101005. #ifdef SQLITE_ENABLE_SQLLOG
  101006. case SQLITE_CONFIG_SQLLOG: {
  101007. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  101008. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  101009. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  101010. break;
  101011. }
  101012. #endif
  101013. case SQLITE_CONFIG_MMAP_SIZE: {
  101014. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  101015. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  101016. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  101017. mxMmap = SQLITE_MAX_MMAP_SIZE;
  101018. }
  101019. sqlite3GlobalConfig.mxMmap = mxMmap;
  101020. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  101021. if( szMmap>mxMmap) szMmap = mxMmap;
  101022. sqlite3GlobalConfig.szMmap = szMmap;
  101023. break;
  101024. }
  101025. default: {
  101026. rc = SQLITE_ERROR;
  101027. break;
  101028. }
  101029. }
  101030. va_end(ap);
  101031. return rc;
  101032. }
  101033. /*
  101034. ** Set up the lookaside buffers for a database connection.
  101035. ** Return SQLITE_OK on success.
  101036. ** If lookaside is already active, return SQLITE_BUSY.
  101037. **
  101038. ** The sz parameter is the number of bytes in each lookaside slot.
  101039. ** The cnt parameter is the number of slots. If pStart is NULL the
  101040. ** space for the lookaside memory is obtained from sqlite3_malloc().
  101041. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  101042. ** the lookaside memory.
  101043. */
  101044. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  101045. void *pStart;
  101046. if( db->lookaside.nOut ){
  101047. return SQLITE_BUSY;
  101048. }
  101049. /* Free any existing lookaside buffer for this handle before
  101050. ** allocating a new one so we don't have to have space for
  101051. ** both at the same time.
  101052. */
  101053. if( db->lookaside.bMalloced ){
  101054. sqlite3_free(db->lookaside.pStart);
  101055. }
  101056. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  101057. ** than a pointer to be useful.
  101058. */
  101059. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  101060. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  101061. if( cnt<0 ) cnt = 0;
  101062. if( sz==0 || cnt==0 ){
  101063. sz = 0;
  101064. pStart = 0;
  101065. }else if( pBuf==0 ){
  101066. sqlite3BeginBenignMalloc();
  101067. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  101068. sqlite3EndBenignMalloc();
  101069. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  101070. }else{
  101071. pStart = pBuf;
  101072. }
  101073. db->lookaside.pStart = pStart;
  101074. db->lookaside.pFree = 0;
  101075. db->lookaside.sz = (u16)sz;
  101076. if( pStart ){
  101077. int i;
  101078. LookasideSlot *p;
  101079. assert( sz > (int)sizeof(LookasideSlot*) );
  101080. p = (LookasideSlot*)pStart;
  101081. for(i=cnt-1; i>=0; i--){
  101082. p->pNext = db->lookaside.pFree;
  101083. db->lookaside.pFree = p;
  101084. p = (LookasideSlot*)&((u8*)p)[sz];
  101085. }
  101086. db->lookaside.pEnd = p;
  101087. db->lookaside.bEnabled = 1;
  101088. db->lookaside.bMalloced = pBuf==0 ?1:0;
  101089. }else{
  101090. db->lookaside.pEnd = 0;
  101091. db->lookaside.bEnabled = 0;
  101092. db->lookaside.bMalloced = 0;
  101093. }
  101094. return SQLITE_OK;
  101095. }
  101096. /*
  101097. ** Return the mutex associated with a database connection.
  101098. */
  101099. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  101100. return db->mutex;
  101101. }
  101102. /*
  101103. ** Free up as much memory as we can from the given database
  101104. ** connection.
  101105. */
  101106. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  101107. int i;
  101108. sqlite3_mutex_enter(db->mutex);
  101109. sqlite3BtreeEnterAll(db);
  101110. for(i=0; i<db->nDb; i++){
  101111. Btree *pBt = db->aDb[i].pBt;
  101112. if( pBt ){
  101113. Pager *pPager = sqlite3BtreePager(pBt);
  101114. sqlite3PagerShrink(pPager);
  101115. }
  101116. }
  101117. sqlite3BtreeLeaveAll(db);
  101118. sqlite3_mutex_leave(db->mutex);
  101119. return SQLITE_OK;
  101120. }
  101121. /*
  101122. ** Configuration settings for an individual database connection
  101123. */
  101124. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  101125. va_list ap;
  101126. int rc;
  101127. va_start(ap, op);
  101128. switch( op ){
  101129. case SQLITE_DBCONFIG_LOOKASIDE: {
  101130. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  101131. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  101132. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  101133. rc = setupLookaside(db, pBuf, sz, cnt);
  101134. break;
  101135. }
  101136. default: {
  101137. static const struct {
  101138. int op; /* The opcode */
  101139. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  101140. } aFlagOp[] = {
  101141. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  101142. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  101143. };
  101144. unsigned int i;
  101145. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  101146. for(i=0; i<ArraySize(aFlagOp); i++){
  101147. if( aFlagOp[i].op==op ){
  101148. int onoff = va_arg(ap, int);
  101149. int *pRes = va_arg(ap, int*);
  101150. int oldFlags = db->flags;
  101151. if( onoff>0 ){
  101152. db->flags |= aFlagOp[i].mask;
  101153. }else if( onoff==0 ){
  101154. db->flags &= ~aFlagOp[i].mask;
  101155. }
  101156. if( oldFlags!=db->flags ){
  101157. sqlite3ExpirePreparedStatements(db);
  101158. }
  101159. if( pRes ){
  101160. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  101161. }
  101162. rc = SQLITE_OK;
  101163. break;
  101164. }
  101165. }
  101166. break;
  101167. }
  101168. }
  101169. va_end(ap);
  101170. return rc;
  101171. }
  101172. /*
  101173. ** Return true if the buffer z[0..n-1] contains all spaces.
  101174. */
  101175. static int allSpaces(const char *z, int n){
  101176. while( n>0 && z[n-1]==' ' ){ n--; }
  101177. return n==0;
  101178. }
  101179. /*
  101180. ** This is the default collating function named "BINARY" which is always
  101181. ** available.
  101182. **
  101183. ** If the padFlag argument is not NULL then space padding at the end
  101184. ** of strings is ignored. This implements the RTRIM collation.
  101185. */
  101186. static int binCollFunc(
  101187. void *padFlag,
  101188. int nKey1, const void *pKey1,
  101189. int nKey2, const void *pKey2
  101190. ){
  101191. int rc, n;
  101192. n = nKey1<nKey2 ? nKey1 : nKey2;
  101193. rc = memcmp(pKey1, pKey2, n);
  101194. if( rc==0 ){
  101195. if( padFlag
  101196. && allSpaces(((char*)pKey1)+n, nKey1-n)
  101197. && allSpaces(((char*)pKey2)+n, nKey2-n)
  101198. ){
  101199. /* Leave rc unchanged at 0 */
  101200. }else{
  101201. rc = nKey1 - nKey2;
  101202. }
  101203. }
  101204. return rc;
  101205. }
  101206. /*
  101207. ** Another built-in collating sequence: NOCASE.
  101208. **
  101209. ** This collating sequence is intended to be used for "case independent
  101210. ** comparison". SQLite's knowledge of upper and lower case equivalents
  101211. ** extends only to the 26 characters used in the English language.
  101212. **
  101213. ** At the moment there is only a UTF-8 implementation.
  101214. */
  101215. static int nocaseCollatingFunc(
  101216. void *NotUsed,
  101217. int nKey1, const void *pKey1,
  101218. int nKey2, const void *pKey2
  101219. ){
  101220. int r = sqlite3StrNICmp(
  101221. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  101222. UNUSED_PARAMETER(NotUsed);
  101223. if( 0==r ){
  101224. r = nKey1-nKey2;
  101225. }
  101226. return r;
  101227. }
  101228. /*
  101229. ** Return the ROWID of the most recent insert
  101230. */
  101231. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  101232. return db->lastRowid;
  101233. }
  101234. /*
  101235. ** Return the number of changes in the most recent call to sqlite3_exec().
  101236. */
  101237. SQLITE_API int sqlite3_changes(sqlite3 *db){
  101238. return db->nChange;
  101239. }
  101240. /*
  101241. ** Return the number of changes since the database handle was opened.
  101242. */
  101243. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  101244. return db->nTotalChange;
  101245. }
  101246. /*
  101247. ** Close all open savepoints. This function only manipulates fields of the
  101248. ** database handle object, it does not close any savepoints that may be open
  101249. ** at the b-tree/pager level.
  101250. */
  101251. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  101252. while( db->pSavepoint ){
  101253. Savepoint *pTmp = db->pSavepoint;
  101254. db->pSavepoint = pTmp->pNext;
  101255. sqlite3DbFree(db, pTmp);
  101256. }
  101257. db->nSavepoint = 0;
  101258. db->nStatement = 0;
  101259. db->isTransactionSavepoint = 0;
  101260. }
  101261. /*
  101262. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  101263. ** if this is not the last copy of the function, do not invoke it. Multiple
  101264. ** copies of a single function are created when create_function() is called
  101265. ** with SQLITE_ANY as the encoding.
  101266. */
  101267. static void functionDestroy(sqlite3 *db, FuncDef *p){
  101268. FuncDestructor *pDestructor = p->pDestructor;
  101269. if( pDestructor ){
  101270. pDestructor->nRef--;
  101271. if( pDestructor->nRef==0 ){
  101272. pDestructor->xDestroy(pDestructor->pUserData);
  101273. sqlite3DbFree(db, pDestructor);
  101274. }
  101275. }
  101276. }
  101277. /*
  101278. ** Disconnect all sqlite3_vtab objects that belong to database connection
  101279. ** db. This is called when db is being closed.
  101280. */
  101281. static void disconnectAllVtab(sqlite3 *db){
  101282. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101283. int i;
  101284. sqlite3BtreeEnterAll(db);
  101285. for(i=0; i<db->nDb; i++){
  101286. Schema *pSchema = db->aDb[i].pSchema;
  101287. if( db->aDb[i].pSchema ){
  101288. HashElem *p;
  101289. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  101290. Table *pTab = (Table *)sqliteHashData(p);
  101291. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  101292. }
  101293. }
  101294. }
  101295. sqlite3BtreeLeaveAll(db);
  101296. #else
  101297. UNUSED_PARAMETER(db);
  101298. #endif
  101299. }
  101300. /*
  101301. ** Return TRUE if database connection db has unfinalized prepared
  101302. ** statements or unfinished sqlite3_backup objects.
  101303. */
  101304. static int connectionIsBusy(sqlite3 *db){
  101305. int j;
  101306. assert( sqlite3_mutex_held(db->mutex) );
  101307. if( db->pVdbe ) return 1;
  101308. for(j=0; j<db->nDb; j++){
  101309. Btree *pBt = db->aDb[j].pBt;
  101310. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  101311. }
  101312. return 0;
  101313. }
  101314. /*
  101315. ** Close an existing SQLite database
  101316. */
  101317. static int sqlite3Close(sqlite3 *db, int forceZombie){
  101318. if( !db ){
  101319. return SQLITE_OK;
  101320. }
  101321. if( !sqlite3SafetyCheckSickOrOk(db) ){
  101322. return SQLITE_MISUSE_BKPT;
  101323. }
  101324. sqlite3_mutex_enter(db->mutex);
  101325. /* Force xDisconnect calls on all virtual tables */
  101326. disconnectAllVtab(db);
  101327. /* If a transaction is open, the disconnectAllVtab() call above
  101328. ** will not have called the xDisconnect() method on any virtual
  101329. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  101330. ** call will do so. We need to do this before the check for active
  101331. ** SQL statements below, as the v-table implementation may be storing
  101332. ** some prepared statements internally.
  101333. */
  101334. sqlite3VtabRollback(db);
  101335. /* Legacy behavior (sqlite3_close() behavior) is to return
  101336. ** SQLITE_BUSY if the connection can not be closed immediately.
  101337. */
  101338. if( !forceZombie && connectionIsBusy(db) ){
  101339. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  101340. "statements or unfinished backups");
  101341. sqlite3_mutex_leave(db->mutex);
  101342. return SQLITE_BUSY;
  101343. }
  101344. #ifdef SQLITE_ENABLE_SQLLOG
  101345. if( sqlite3GlobalConfig.xSqllog ){
  101346. /* Closing the handle. Fourth parameter is passed the value 2. */
  101347. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  101348. }
  101349. #endif
  101350. /* Convert the connection into a zombie and then close it.
  101351. */
  101352. db->magic = SQLITE_MAGIC_ZOMBIE;
  101353. sqlite3LeaveMutexAndCloseZombie(db);
  101354. return SQLITE_OK;
  101355. }
  101356. /*
  101357. ** Two variations on the public interface for closing a database
  101358. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  101359. ** leaves the connection option if there are unfinalized prepared
  101360. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  101361. ** version forces the connection to become a zombie if there are
  101362. ** unclosed resources, and arranges for deallocation when the last
  101363. ** prepare statement or sqlite3_backup closes.
  101364. */
  101365. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  101366. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  101367. /*
  101368. ** Close the mutex on database connection db.
  101369. **
  101370. ** Furthermore, if database connection db is a zombie (meaning that there
  101371. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  101372. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  101373. ** finished, then free all resources.
  101374. */
  101375. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  101376. HashElem *i; /* Hash table iterator */
  101377. int j;
  101378. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  101379. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  101380. ** then just leave the mutex and return.
  101381. */
  101382. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  101383. sqlite3_mutex_leave(db->mutex);
  101384. return;
  101385. }
  101386. /* If we reach this point, it means that the database connection has
  101387. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  101388. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  101389. ** go ahead and free all resources.
  101390. */
  101391. /* If a transaction is open, roll it back. This also ensures that if
  101392. ** any database schemas have been modified by an uncommitted transaction
  101393. ** they are reset. And that the required b-tree mutex is held to make
  101394. ** the pager rollback and schema reset an atomic operation. */
  101395. sqlite3RollbackAll(db, SQLITE_OK);
  101396. /* Free any outstanding Savepoint structures. */
  101397. sqlite3CloseSavepoints(db);
  101398. /* Close all database connections */
  101399. for(j=0; j<db->nDb; j++){
  101400. struct Db *pDb = &db->aDb[j];
  101401. if( pDb->pBt ){
  101402. sqlite3BtreeClose(pDb->pBt);
  101403. pDb->pBt = 0;
  101404. if( j!=1 ){
  101405. pDb->pSchema = 0;
  101406. }
  101407. }
  101408. }
  101409. /* Clear the TEMP schema separately and last */
  101410. if( db->aDb[1].pSchema ){
  101411. sqlite3SchemaClear(db->aDb[1].pSchema);
  101412. }
  101413. sqlite3VtabUnlockList(db);
  101414. /* Free up the array of auxiliary databases */
  101415. sqlite3CollapseDatabaseArray(db);
  101416. assert( db->nDb<=2 );
  101417. assert( db->aDb==db->aDbStatic );
  101418. /* Tell the code in notify.c that the connection no longer holds any
  101419. ** locks and does not require any further unlock-notify callbacks.
  101420. */
  101421. sqlite3ConnectionClosed(db);
  101422. for(j=0; j<ArraySize(db->aFunc.a); j++){
  101423. FuncDef *pNext, *pHash, *p;
  101424. for(p=db->aFunc.a[j]; p; p=pHash){
  101425. pHash = p->pHash;
  101426. while( p ){
  101427. functionDestroy(db, p);
  101428. pNext = p->pNext;
  101429. sqlite3DbFree(db, p);
  101430. p = pNext;
  101431. }
  101432. }
  101433. }
  101434. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  101435. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  101436. /* Invoke any destructors registered for collation sequence user data. */
  101437. for(j=0; j<3; j++){
  101438. if( pColl[j].xDel ){
  101439. pColl[j].xDel(pColl[j].pUser);
  101440. }
  101441. }
  101442. sqlite3DbFree(db, pColl);
  101443. }
  101444. sqlite3HashClear(&db->aCollSeq);
  101445. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101446. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  101447. Module *pMod = (Module *)sqliteHashData(i);
  101448. if( pMod->xDestroy ){
  101449. pMod->xDestroy(pMod->pAux);
  101450. }
  101451. sqlite3DbFree(db, pMod);
  101452. }
  101453. sqlite3HashClear(&db->aModule);
  101454. #endif
  101455. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  101456. if( db->pErr ){
  101457. sqlite3ValueFree(db->pErr);
  101458. }
  101459. sqlite3CloseExtensions(db);
  101460. db->magic = SQLITE_MAGIC_ERROR;
  101461. /* The temp-database schema is allocated differently from the other schema
  101462. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  101463. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  101464. ** the same sqliteMalloc() as the one that allocates the database
  101465. ** structure?
  101466. */
  101467. sqlite3DbFree(db, db->aDb[1].pSchema);
  101468. sqlite3_mutex_leave(db->mutex);
  101469. db->magic = SQLITE_MAGIC_CLOSED;
  101470. sqlite3_mutex_free(db->mutex);
  101471. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  101472. if( db->lookaside.bMalloced ){
  101473. sqlite3_free(db->lookaside.pStart);
  101474. }
  101475. sqlite3_free(db);
  101476. }
  101477. /*
  101478. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  101479. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  101480. ** breaker") and made to return tripCode if there are any further
  101481. ** attempts to use that cursor.
  101482. */
  101483. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  101484. int i;
  101485. int inTrans = 0;
  101486. assert( sqlite3_mutex_held(db->mutex) );
  101487. sqlite3BeginBenignMalloc();
  101488. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  101489. ** This is important in case the transaction being rolled back has
  101490. ** modified the database schema. If the b-tree mutexes are not taken
  101491. ** here, then another shared-cache connection might sneak in between
  101492. ** the database rollback and schema reset, which can cause false
  101493. ** corruption reports in some cases. */
  101494. sqlite3BtreeEnterAll(db);
  101495. for(i=0; i<db->nDb; i++){
  101496. Btree *p = db->aDb[i].pBt;
  101497. if( p ){
  101498. if( sqlite3BtreeIsInTrans(p) ){
  101499. inTrans = 1;
  101500. }
  101501. sqlite3BtreeRollback(p, tripCode);
  101502. }
  101503. }
  101504. sqlite3VtabRollback(db);
  101505. sqlite3EndBenignMalloc();
  101506. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  101507. sqlite3ExpirePreparedStatements(db);
  101508. sqlite3ResetAllSchemasOfConnection(db);
  101509. }
  101510. sqlite3BtreeLeaveAll(db);
  101511. /* Any deferred constraint violations have now been resolved. */
  101512. db->nDeferredCons = 0;
  101513. db->nDeferredImmCons = 0;
  101514. db->flags &= ~SQLITE_DeferFKs;
  101515. /* If one has been configured, invoke the rollback-hook callback */
  101516. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  101517. db->xRollbackCallback(db->pRollbackArg);
  101518. }
  101519. }
  101520. /*
  101521. ** Return a static string containing the name corresponding to the error code
  101522. ** specified in the argument.
  101523. */
  101524. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  101525. defined(SQLITE_DEBUG_OS_TRACE)
  101526. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  101527. const char *zName = 0;
  101528. int i, origRc = rc;
  101529. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  101530. switch( rc ){
  101531. case SQLITE_OK: zName = "SQLITE_OK"; break;
  101532. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  101533. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  101534. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  101535. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  101536. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  101537. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  101538. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  101539. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  101540. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  101541. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  101542. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  101543. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  101544. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  101545. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  101546. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  101547. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  101548. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  101549. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  101550. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  101551. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  101552. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  101553. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  101554. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  101555. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  101556. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  101557. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  101558. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  101559. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  101560. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  101561. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  101562. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  101563. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  101564. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  101565. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  101566. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  101567. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  101568. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  101569. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  101570. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  101571. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  101572. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  101573. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  101574. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  101575. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  101576. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  101577. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  101578. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  101579. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  101580. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  101581. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  101582. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  101583. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  101584. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  101585. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  101586. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  101587. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  101588. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  101589. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  101590. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  101591. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  101592. case SQLITE_CONSTRAINT_FOREIGNKEY:
  101593. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  101594. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  101595. case SQLITE_CONSTRAINT_PRIMARYKEY:
  101596. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  101597. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  101598. case SQLITE_CONSTRAINT_COMMITHOOK:
  101599. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  101600. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  101601. case SQLITE_CONSTRAINT_FUNCTION:
  101602. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  101603. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  101604. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  101605. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  101606. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  101607. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  101608. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  101609. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  101610. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  101611. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  101612. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  101613. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  101614. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  101615. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  101616. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  101617. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  101618. }
  101619. }
  101620. if( zName==0 ){
  101621. static char zBuf[50];
  101622. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  101623. zName = zBuf;
  101624. }
  101625. return zName;
  101626. }
  101627. #endif
  101628. /*
  101629. ** Return a static string that describes the kind of error specified in the
  101630. ** argument.
  101631. */
  101632. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  101633. static const char* const aMsg[] = {
  101634. /* SQLITE_OK */ "not an error",
  101635. /* SQLITE_ERROR */ "SQL logic error or missing database",
  101636. /* SQLITE_INTERNAL */ 0,
  101637. /* SQLITE_PERM */ "access permission denied",
  101638. /* SQLITE_ABORT */ "callback requested query abort",
  101639. /* SQLITE_BUSY */ "database is locked",
  101640. /* SQLITE_LOCKED */ "database table is locked",
  101641. /* SQLITE_NOMEM */ "out of memory",
  101642. /* SQLITE_READONLY */ "attempt to write a readonly database",
  101643. /* SQLITE_INTERRUPT */ "interrupted",
  101644. /* SQLITE_IOERR */ "disk I/O error",
  101645. /* SQLITE_CORRUPT */ "database disk image is malformed",
  101646. /* SQLITE_NOTFOUND */ "unknown operation",
  101647. /* SQLITE_FULL */ "database or disk is full",
  101648. /* SQLITE_CANTOPEN */ "unable to open database file",
  101649. /* SQLITE_PROTOCOL */ "locking protocol",
  101650. /* SQLITE_EMPTY */ "table contains no data",
  101651. /* SQLITE_SCHEMA */ "database schema has changed",
  101652. /* SQLITE_TOOBIG */ "string or blob too big",
  101653. /* SQLITE_CONSTRAINT */ "constraint failed",
  101654. /* SQLITE_MISMATCH */ "datatype mismatch",
  101655. /* SQLITE_MISUSE */ "library routine called out of sequence",
  101656. /* SQLITE_NOLFS */ "large file support is disabled",
  101657. /* SQLITE_AUTH */ "authorization denied",
  101658. /* SQLITE_FORMAT */ "auxiliary database format error",
  101659. /* SQLITE_RANGE */ "bind or column index out of range",
  101660. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  101661. };
  101662. const char *zErr = "unknown error";
  101663. switch( rc ){
  101664. case SQLITE_ABORT_ROLLBACK: {
  101665. zErr = "abort due to ROLLBACK";
  101666. break;
  101667. }
  101668. default: {
  101669. rc &= 0xff;
  101670. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  101671. zErr = aMsg[rc];
  101672. }
  101673. break;
  101674. }
  101675. }
  101676. return zErr;
  101677. }
  101678. /*
  101679. ** This routine implements a busy callback that sleeps and tries
  101680. ** again until a timeout value is reached. The timeout value is
  101681. ** an integer number of milliseconds passed in as the first
  101682. ** argument.
  101683. */
  101684. static int sqliteDefaultBusyCallback(
  101685. void *ptr, /* Database connection */
  101686. int count /* Number of times table has been busy */
  101687. ){
  101688. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  101689. static const u8 delays[] =
  101690. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  101691. static const u8 totals[] =
  101692. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  101693. # define NDELAY ArraySize(delays)
  101694. sqlite3 *db = (sqlite3 *)ptr;
  101695. int timeout = db->busyTimeout;
  101696. int delay, prior;
  101697. assert( count>=0 );
  101698. if( count < NDELAY ){
  101699. delay = delays[count];
  101700. prior = totals[count];
  101701. }else{
  101702. delay = delays[NDELAY-1];
  101703. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  101704. }
  101705. if( prior + delay > timeout ){
  101706. delay = timeout - prior;
  101707. if( delay<=0 ) return 0;
  101708. }
  101709. sqlite3OsSleep(db->pVfs, delay*1000);
  101710. return 1;
  101711. #else
  101712. sqlite3 *db = (sqlite3 *)ptr;
  101713. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  101714. if( (count+1)*1000 > timeout ){
  101715. return 0;
  101716. }
  101717. sqlite3OsSleep(db->pVfs, 1000000);
  101718. return 1;
  101719. #endif
  101720. }
  101721. /*
  101722. ** Invoke the given busy handler.
  101723. **
  101724. ** This routine is called when an operation failed with a lock.
  101725. ** If this routine returns non-zero, the lock is retried. If it
  101726. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  101727. */
  101728. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  101729. int rc;
  101730. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  101731. rc = p->xFunc(p->pArg, p->nBusy);
  101732. if( rc==0 ){
  101733. p->nBusy = -1;
  101734. }else{
  101735. p->nBusy++;
  101736. }
  101737. return rc;
  101738. }
  101739. /*
  101740. ** This routine sets the busy callback for an Sqlite database to the
  101741. ** given callback function with the given argument.
  101742. */
  101743. SQLITE_API int sqlite3_busy_handler(
  101744. sqlite3 *db,
  101745. int (*xBusy)(void*,int),
  101746. void *pArg
  101747. ){
  101748. sqlite3_mutex_enter(db->mutex);
  101749. db->busyHandler.xFunc = xBusy;
  101750. db->busyHandler.pArg = pArg;
  101751. db->busyHandler.nBusy = 0;
  101752. db->busyTimeout = 0;
  101753. sqlite3_mutex_leave(db->mutex);
  101754. return SQLITE_OK;
  101755. }
  101756. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  101757. /*
  101758. ** This routine sets the progress callback for an Sqlite database to the
  101759. ** given callback function with the given argument. The progress callback will
  101760. ** be invoked every nOps opcodes.
  101761. */
  101762. SQLITE_API void sqlite3_progress_handler(
  101763. sqlite3 *db,
  101764. int nOps,
  101765. int (*xProgress)(void*),
  101766. void *pArg
  101767. ){
  101768. sqlite3_mutex_enter(db->mutex);
  101769. if( nOps>0 ){
  101770. db->xProgress = xProgress;
  101771. db->nProgressOps = (unsigned)nOps;
  101772. db->pProgressArg = pArg;
  101773. }else{
  101774. db->xProgress = 0;
  101775. db->nProgressOps = 0;
  101776. db->pProgressArg = 0;
  101777. }
  101778. sqlite3_mutex_leave(db->mutex);
  101779. }
  101780. #endif
  101781. /*
  101782. ** This routine installs a default busy handler that waits for the
  101783. ** specified number of milliseconds before returning 0.
  101784. */
  101785. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  101786. if( ms>0 ){
  101787. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  101788. db->busyTimeout = ms;
  101789. }else{
  101790. sqlite3_busy_handler(db, 0, 0);
  101791. }
  101792. return SQLITE_OK;
  101793. }
  101794. /*
  101795. ** Cause any pending operation to stop at its earliest opportunity.
  101796. */
  101797. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  101798. db->u1.isInterrupted = 1;
  101799. }
  101800. /*
  101801. ** This function is exactly the same as sqlite3_create_function(), except
  101802. ** that it is designed to be called by internal code. The difference is
  101803. ** that if a malloc() fails in sqlite3_create_function(), an error code
  101804. ** is returned and the mallocFailed flag cleared.
  101805. */
  101806. SQLITE_PRIVATE int sqlite3CreateFunc(
  101807. sqlite3 *db,
  101808. const char *zFunctionName,
  101809. int nArg,
  101810. int enc,
  101811. void *pUserData,
  101812. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101813. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101814. void (*xFinal)(sqlite3_context*),
  101815. FuncDestructor *pDestructor
  101816. ){
  101817. FuncDef *p;
  101818. int nName;
  101819. assert( sqlite3_mutex_held(db->mutex) );
  101820. if( zFunctionName==0 ||
  101821. (xFunc && (xFinal || xStep)) ||
  101822. (!xFunc && (xFinal && !xStep)) ||
  101823. (!xFunc && (!xFinal && xStep)) ||
  101824. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  101825. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  101826. return SQLITE_MISUSE_BKPT;
  101827. }
  101828. #ifndef SQLITE_OMIT_UTF16
  101829. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  101830. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  101831. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  101832. **
  101833. ** If SQLITE_ANY is specified, add three versions of the function
  101834. ** to the hash table.
  101835. */
  101836. if( enc==SQLITE_UTF16 ){
  101837. enc = SQLITE_UTF16NATIVE;
  101838. }else if( enc==SQLITE_ANY ){
  101839. int rc;
  101840. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  101841. pUserData, xFunc, xStep, xFinal, pDestructor);
  101842. if( rc==SQLITE_OK ){
  101843. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  101844. pUserData, xFunc, xStep, xFinal, pDestructor);
  101845. }
  101846. if( rc!=SQLITE_OK ){
  101847. return rc;
  101848. }
  101849. enc = SQLITE_UTF16BE;
  101850. }
  101851. #else
  101852. enc = SQLITE_UTF8;
  101853. #endif
  101854. /* Check if an existing function is being overridden or deleted. If so,
  101855. ** and there are active VMs, then return SQLITE_BUSY. If a function
  101856. ** is being overridden/deleted but there are no active VMs, allow the
  101857. ** operation to continue but invalidate all precompiled statements.
  101858. */
  101859. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  101860. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  101861. if( db->nVdbeActive ){
  101862. sqlite3Error(db, SQLITE_BUSY,
  101863. "unable to delete/modify user-function due to active statements");
  101864. assert( !db->mallocFailed );
  101865. return SQLITE_BUSY;
  101866. }else{
  101867. sqlite3ExpirePreparedStatements(db);
  101868. }
  101869. }
  101870. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  101871. assert(p || db->mallocFailed);
  101872. if( !p ){
  101873. return SQLITE_NOMEM;
  101874. }
  101875. /* If an older version of the function with a configured destructor is
  101876. ** being replaced invoke the destructor function here. */
  101877. functionDestroy(db, p);
  101878. if( pDestructor ){
  101879. pDestructor->nRef++;
  101880. }
  101881. p->pDestructor = pDestructor;
  101882. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  101883. p->xFunc = xFunc;
  101884. p->xStep = xStep;
  101885. p->xFinalize = xFinal;
  101886. p->pUserData = pUserData;
  101887. p->nArg = (u16)nArg;
  101888. return SQLITE_OK;
  101889. }
  101890. /*
  101891. ** Create new user functions.
  101892. */
  101893. SQLITE_API int sqlite3_create_function(
  101894. sqlite3 *db,
  101895. const char *zFunc,
  101896. int nArg,
  101897. int enc,
  101898. void *p,
  101899. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101900. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101901. void (*xFinal)(sqlite3_context*)
  101902. ){
  101903. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  101904. xFinal, 0);
  101905. }
  101906. SQLITE_API int sqlite3_create_function_v2(
  101907. sqlite3 *db,
  101908. const char *zFunc,
  101909. int nArg,
  101910. int enc,
  101911. void *p,
  101912. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101913. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101914. void (*xFinal)(sqlite3_context*),
  101915. void (*xDestroy)(void *)
  101916. ){
  101917. int rc = SQLITE_ERROR;
  101918. FuncDestructor *pArg = 0;
  101919. sqlite3_mutex_enter(db->mutex);
  101920. if( xDestroy ){
  101921. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  101922. if( !pArg ){
  101923. xDestroy(p);
  101924. goto out;
  101925. }
  101926. pArg->xDestroy = xDestroy;
  101927. pArg->pUserData = p;
  101928. }
  101929. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  101930. if( pArg && pArg->nRef==0 ){
  101931. assert( rc!=SQLITE_OK );
  101932. xDestroy(p);
  101933. sqlite3DbFree(db, pArg);
  101934. }
  101935. out:
  101936. rc = sqlite3ApiExit(db, rc);
  101937. sqlite3_mutex_leave(db->mutex);
  101938. return rc;
  101939. }
  101940. #ifndef SQLITE_OMIT_UTF16
  101941. SQLITE_API int sqlite3_create_function16(
  101942. sqlite3 *db,
  101943. const void *zFunctionName,
  101944. int nArg,
  101945. int eTextRep,
  101946. void *p,
  101947. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  101948. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  101949. void (*xFinal)(sqlite3_context*)
  101950. ){
  101951. int rc;
  101952. char *zFunc8;
  101953. sqlite3_mutex_enter(db->mutex);
  101954. assert( !db->mallocFailed );
  101955. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  101956. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  101957. sqlite3DbFree(db, zFunc8);
  101958. rc = sqlite3ApiExit(db, rc);
  101959. sqlite3_mutex_leave(db->mutex);
  101960. return rc;
  101961. }
  101962. #endif
  101963. /*
  101964. ** Declare that a function has been overloaded by a virtual table.
  101965. **
  101966. ** If the function already exists as a regular global function, then
  101967. ** this routine is a no-op. If the function does not exist, then create
  101968. ** a new one that always throws a run-time error.
  101969. **
  101970. ** When virtual tables intend to provide an overloaded function, they
  101971. ** should call this routine to make sure the global function exists.
  101972. ** A global function must exist in order for name resolution to work
  101973. ** properly.
  101974. */
  101975. SQLITE_API int sqlite3_overload_function(
  101976. sqlite3 *db,
  101977. const char *zName,
  101978. int nArg
  101979. ){
  101980. int nName = sqlite3Strlen30(zName);
  101981. int rc = SQLITE_OK;
  101982. sqlite3_mutex_enter(db->mutex);
  101983. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  101984. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  101985. 0, sqlite3InvalidFunction, 0, 0, 0);
  101986. }
  101987. rc = sqlite3ApiExit(db, rc);
  101988. sqlite3_mutex_leave(db->mutex);
  101989. return rc;
  101990. }
  101991. #ifndef SQLITE_OMIT_TRACE
  101992. /*
  101993. ** Register a trace function. The pArg from the previously registered trace
  101994. ** is returned.
  101995. **
  101996. ** A NULL trace function means that no tracing is executes. A non-NULL
  101997. ** trace is a pointer to a function that is invoked at the start of each
  101998. ** SQL statement.
  101999. */
  102000. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  102001. void *pOld;
  102002. sqlite3_mutex_enter(db->mutex);
  102003. pOld = db->pTraceArg;
  102004. db->xTrace = xTrace;
  102005. db->pTraceArg = pArg;
  102006. sqlite3_mutex_leave(db->mutex);
  102007. return pOld;
  102008. }
  102009. /*
  102010. ** Register a profile function. The pArg from the previously registered
  102011. ** profile function is returned.
  102012. **
  102013. ** A NULL profile function means that no profiling is executes. A non-NULL
  102014. ** profile is a pointer to a function that is invoked at the conclusion of
  102015. ** each SQL statement that is run.
  102016. */
  102017. SQLITE_API void *sqlite3_profile(
  102018. sqlite3 *db,
  102019. void (*xProfile)(void*,const char*,sqlite_uint64),
  102020. void *pArg
  102021. ){
  102022. void *pOld;
  102023. sqlite3_mutex_enter(db->mutex);
  102024. pOld = db->pProfileArg;
  102025. db->xProfile = xProfile;
  102026. db->pProfileArg = pArg;
  102027. sqlite3_mutex_leave(db->mutex);
  102028. return pOld;
  102029. }
  102030. #endif /* SQLITE_OMIT_TRACE */
  102031. /*
  102032. ** Register a function to be invoked when a transaction commits.
  102033. ** If the invoked function returns non-zero, then the commit becomes a
  102034. ** rollback.
  102035. */
  102036. SQLITE_API void *sqlite3_commit_hook(
  102037. sqlite3 *db, /* Attach the hook to this database */
  102038. int (*xCallback)(void*), /* Function to invoke on each commit */
  102039. void *pArg /* Argument to the function */
  102040. ){
  102041. void *pOld;
  102042. sqlite3_mutex_enter(db->mutex);
  102043. pOld = db->pCommitArg;
  102044. db->xCommitCallback = xCallback;
  102045. db->pCommitArg = pArg;
  102046. sqlite3_mutex_leave(db->mutex);
  102047. return pOld;
  102048. }
  102049. /*
  102050. ** Register a callback to be invoked each time a row is updated,
  102051. ** inserted or deleted using this database connection.
  102052. */
  102053. SQLITE_API void *sqlite3_update_hook(
  102054. sqlite3 *db, /* Attach the hook to this database */
  102055. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  102056. void *pArg /* Argument to the function */
  102057. ){
  102058. void *pRet;
  102059. sqlite3_mutex_enter(db->mutex);
  102060. pRet = db->pUpdateArg;
  102061. db->xUpdateCallback = xCallback;
  102062. db->pUpdateArg = pArg;
  102063. sqlite3_mutex_leave(db->mutex);
  102064. return pRet;
  102065. }
  102066. /*
  102067. ** Register a callback to be invoked each time a transaction is rolled
  102068. ** back by this database connection.
  102069. */
  102070. SQLITE_API void *sqlite3_rollback_hook(
  102071. sqlite3 *db, /* Attach the hook to this database */
  102072. void (*xCallback)(void*), /* Callback function */
  102073. void *pArg /* Argument to the function */
  102074. ){
  102075. void *pRet;
  102076. sqlite3_mutex_enter(db->mutex);
  102077. pRet = db->pRollbackArg;
  102078. db->xRollbackCallback = xCallback;
  102079. db->pRollbackArg = pArg;
  102080. sqlite3_mutex_leave(db->mutex);
  102081. return pRet;
  102082. }
  102083. #ifndef SQLITE_OMIT_WAL
  102084. /*
  102085. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  102086. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  102087. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  102088. ** wal_autocheckpoint()).
  102089. */
  102090. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  102091. void *pClientData, /* Argument */
  102092. sqlite3 *db, /* Connection */
  102093. const char *zDb, /* Database */
  102094. int nFrame /* Size of WAL */
  102095. ){
  102096. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  102097. sqlite3BeginBenignMalloc();
  102098. sqlite3_wal_checkpoint(db, zDb);
  102099. sqlite3EndBenignMalloc();
  102100. }
  102101. return SQLITE_OK;
  102102. }
  102103. #endif /* SQLITE_OMIT_WAL */
  102104. /*
  102105. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  102106. ** a database after committing a transaction if there are nFrame or
  102107. ** more frames in the log file. Passing zero or a negative value as the
  102108. ** nFrame parameter disables automatic checkpoints entirely.
  102109. **
  102110. ** The callback registered by this function replaces any existing callback
  102111. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  102112. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  102113. ** configured by this function.
  102114. */
  102115. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  102116. #ifdef SQLITE_OMIT_WAL
  102117. UNUSED_PARAMETER(db);
  102118. UNUSED_PARAMETER(nFrame);
  102119. #else
  102120. if( nFrame>0 ){
  102121. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  102122. }else{
  102123. sqlite3_wal_hook(db, 0, 0);
  102124. }
  102125. #endif
  102126. return SQLITE_OK;
  102127. }
  102128. /*
  102129. ** Register a callback to be invoked each time a transaction is written
  102130. ** into the write-ahead-log by this database connection.
  102131. */
  102132. SQLITE_API void *sqlite3_wal_hook(
  102133. sqlite3 *db, /* Attach the hook to this db handle */
  102134. int(*xCallback)(void *, sqlite3*, const char*, int),
  102135. void *pArg /* First argument passed to xCallback() */
  102136. ){
  102137. #ifndef SQLITE_OMIT_WAL
  102138. void *pRet;
  102139. sqlite3_mutex_enter(db->mutex);
  102140. pRet = db->pWalArg;
  102141. db->xWalCallback = xCallback;
  102142. db->pWalArg = pArg;
  102143. sqlite3_mutex_leave(db->mutex);
  102144. return pRet;
  102145. #else
  102146. return 0;
  102147. #endif
  102148. }
  102149. /*
  102150. ** Checkpoint database zDb.
  102151. */
  102152. SQLITE_API int sqlite3_wal_checkpoint_v2(
  102153. sqlite3 *db, /* Database handle */
  102154. const char *zDb, /* Name of attached database (or NULL) */
  102155. int eMode, /* SQLITE_CHECKPOINT_* value */
  102156. int *pnLog, /* OUT: Size of WAL log in frames */
  102157. int *pnCkpt /* OUT: Total number of frames checkpointed */
  102158. ){
  102159. #ifdef SQLITE_OMIT_WAL
  102160. return SQLITE_OK;
  102161. #else
  102162. int rc; /* Return code */
  102163. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  102164. /* Initialize the output variables to -1 in case an error occurs. */
  102165. if( pnLog ) *pnLog = -1;
  102166. if( pnCkpt ) *pnCkpt = -1;
  102167. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  102168. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  102169. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  102170. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  102171. return SQLITE_MISUSE;
  102172. }
  102173. sqlite3_mutex_enter(db->mutex);
  102174. if( zDb && zDb[0] ){
  102175. iDb = sqlite3FindDbName(db, zDb);
  102176. }
  102177. if( iDb<0 ){
  102178. rc = SQLITE_ERROR;
  102179. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  102180. }else{
  102181. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  102182. sqlite3Error(db, rc, 0);
  102183. }
  102184. rc = sqlite3ApiExit(db, rc);
  102185. sqlite3_mutex_leave(db->mutex);
  102186. return rc;
  102187. #endif
  102188. }
  102189. /*
  102190. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  102191. ** to contains a zero-length string, all attached databases are
  102192. ** checkpointed.
  102193. */
  102194. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  102195. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  102196. }
  102197. #ifndef SQLITE_OMIT_WAL
  102198. /*
  102199. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  102200. ** not currently open in WAL mode.
  102201. **
  102202. ** If a transaction is open on the database being checkpointed, this
  102203. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  102204. ** an error occurs while running the checkpoint, an SQLite error code is
  102205. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  102206. **
  102207. ** The mutex on database handle db should be held by the caller. The mutex
  102208. ** associated with the specific b-tree being checkpointed is taken by
  102209. ** this function while the checkpoint is running.
  102210. **
  102211. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  102212. ** checkpointed. If an error is encountered it is returned immediately -
  102213. ** no attempt is made to checkpoint any remaining databases.
  102214. **
  102215. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  102216. */
  102217. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  102218. int rc = SQLITE_OK; /* Return code */
  102219. int i; /* Used to iterate through attached dbs */
  102220. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  102221. assert( sqlite3_mutex_held(db->mutex) );
  102222. assert( !pnLog || *pnLog==-1 );
  102223. assert( !pnCkpt || *pnCkpt==-1 );
  102224. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  102225. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  102226. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  102227. pnLog = 0;
  102228. pnCkpt = 0;
  102229. if( rc==SQLITE_BUSY ){
  102230. bBusy = 1;
  102231. rc = SQLITE_OK;
  102232. }
  102233. }
  102234. }
  102235. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  102236. }
  102237. #endif /* SQLITE_OMIT_WAL */
  102238. /*
  102239. ** This function returns true if main-memory should be used instead of
  102240. ** a temporary file for transient pager files and statement journals.
  102241. ** The value returned depends on the value of db->temp_store (runtime
  102242. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  102243. ** following table describes the relationship between these two values
  102244. ** and this functions return value.
  102245. **
  102246. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  102247. ** ----------------- -------------- ------------------------------
  102248. ** 0 any file (return 0)
  102249. ** 1 1 file (return 0)
  102250. ** 1 2 memory (return 1)
  102251. ** 1 0 file (return 0)
  102252. ** 2 1 file (return 0)
  102253. ** 2 2 memory (return 1)
  102254. ** 2 0 memory (return 1)
  102255. ** 3 any memory (return 1)
  102256. */
  102257. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  102258. #if SQLITE_TEMP_STORE==1
  102259. return ( db->temp_store==2 );
  102260. #endif
  102261. #if SQLITE_TEMP_STORE==2
  102262. return ( db->temp_store!=1 );
  102263. #endif
  102264. #if SQLITE_TEMP_STORE==3
  102265. return 1;
  102266. #endif
  102267. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  102268. return 0;
  102269. #endif
  102270. }
  102271. /*
  102272. ** Return UTF-8 encoded English language explanation of the most recent
  102273. ** error.
  102274. */
  102275. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  102276. const char *z;
  102277. if( !db ){
  102278. return sqlite3ErrStr(SQLITE_NOMEM);
  102279. }
  102280. if( !sqlite3SafetyCheckSickOrOk(db) ){
  102281. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  102282. }
  102283. sqlite3_mutex_enter(db->mutex);
  102284. if( db->mallocFailed ){
  102285. z = sqlite3ErrStr(SQLITE_NOMEM);
  102286. }else{
  102287. z = (char*)sqlite3_value_text(db->pErr);
  102288. assert( !db->mallocFailed );
  102289. if( z==0 ){
  102290. z = sqlite3ErrStr(db->errCode);
  102291. }
  102292. }
  102293. sqlite3_mutex_leave(db->mutex);
  102294. return z;
  102295. }
  102296. #ifndef SQLITE_OMIT_UTF16
  102297. /*
  102298. ** Return UTF-16 encoded English language explanation of the most recent
  102299. ** error.
  102300. */
  102301. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  102302. static const u16 outOfMem[] = {
  102303. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  102304. };
  102305. static const u16 misuse[] = {
  102306. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  102307. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  102308. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  102309. 'o', 'u', 't', ' ',
  102310. 'o', 'f', ' ',
  102311. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  102312. };
  102313. const void *z;
  102314. if( !db ){
  102315. return (void *)outOfMem;
  102316. }
  102317. if( !sqlite3SafetyCheckSickOrOk(db) ){
  102318. return (void *)misuse;
  102319. }
  102320. sqlite3_mutex_enter(db->mutex);
  102321. if( db->mallocFailed ){
  102322. z = (void *)outOfMem;
  102323. }else{
  102324. z = sqlite3_value_text16(db->pErr);
  102325. if( z==0 ){
  102326. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  102327. SQLITE_UTF8, SQLITE_STATIC);
  102328. z = sqlite3_value_text16(db->pErr);
  102329. }
  102330. /* A malloc() may have failed within the call to sqlite3_value_text16()
  102331. ** above. If this is the case, then the db->mallocFailed flag needs to
  102332. ** be cleared before returning. Do this directly, instead of via
  102333. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  102334. */
  102335. db->mallocFailed = 0;
  102336. }
  102337. sqlite3_mutex_leave(db->mutex);
  102338. return z;
  102339. }
  102340. #endif /* SQLITE_OMIT_UTF16 */
  102341. /*
  102342. ** Return the most recent error code generated by an SQLite routine. If NULL is
  102343. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  102344. */
  102345. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  102346. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  102347. return SQLITE_MISUSE_BKPT;
  102348. }
  102349. if( !db || db->mallocFailed ){
  102350. return SQLITE_NOMEM;
  102351. }
  102352. return db->errCode & db->errMask;
  102353. }
  102354. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  102355. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  102356. return SQLITE_MISUSE_BKPT;
  102357. }
  102358. if( !db || db->mallocFailed ){
  102359. return SQLITE_NOMEM;
  102360. }
  102361. return db->errCode;
  102362. }
  102363. /*
  102364. ** Return a string that describes the kind of error specified in the
  102365. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  102366. ** function.
  102367. */
  102368. SQLITE_API const char *sqlite3_errstr(int rc){
  102369. return sqlite3ErrStr(rc);
  102370. }
  102371. /*
  102372. ** Create a new collating function for database "db". The name is zName
  102373. ** and the encoding is enc.
  102374. */
  102375. static int createCollation(
  102376. sqlite3* db,
  102377. const char *zName,
  102378. u8 enc,
  102379. void* pCtx,
  102380. int(*xCompare)(void*,int,const void*,int,const void*),
  102381. void(*xDel)(void*)
  102382. ){
  102383. CollSeq *pColl;
  102384. int enc2;
  102385. int nName = sqlite3Strlen30(zName);
  102386. assert( sqlite3_mutex_held(db->mutex) );
  102387. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  102388. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  102389. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  102390. */
  102391. enc2 = enc;
  102392. testcase( enc2==SQLITE_UTF16 );
  102393. testcase( enc2==SQLITE_UTF16_ALIGNED );
  102394. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  102395. enc2 = SQLITE_UTF16NATIVE;
  102396. }
  102397. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  102398. return SQLITE_MISUSE_BKPT;
  102399. }
  102400. /* Check if this call is removing or replacing an existing collation
  102401. ** sequence. If so, and there are active VMs, return busy. If there
  102402. ** are no active VMs, invalidate any pre-compiled statements.
  102403. */
  102404. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  102405. if( pColl && pColl->xCmp ){
  102406. if( db->nVdbeActive ){
  102407. sqlite3Error(db, SQLITE_BUSY,
  102408. "unable to delete/modify collation sequence due to active statements");
  102409. return SQLITE_BUSY;
  102410. }
  102411. sqlite3ExpirePreparedStatements(db);
  102412. /* If collation sequence pColl was created directly by a call to
  102413. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  102414. ** then any copies made by synthCollSeq() need to be invalidated.
  102415. ** Also, collation destructor - CollSeq.xDel() - function may need
  102416. ** to be called.
  102417. */
  102418. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  102419. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  102420. int j;
  102421. for(j=0; j<3; j++){
  102422. CollSeq *p = &aColl[j];
  102423. if( p->enc==pColl->enc ){
  102424. if( p->xDel ){
  102425. p->xDel(p->pUser);
  102426. }
  102427. p->xCmp = 0;
  102428. }
  102429. }
  102430. }
  102431. }
  102432. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  102433. if( pColl==0 ) return SQLITE_NOMEM;
  102434. pColl->xCmp = xCompare;
  102435. pColl->pUser = pCtx;
  102436. pColl->xDel = xDel;
  102437. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  102438. sqlite3Error(db, SQLITE_OK, 0);
  102439. return SQLITE_OK;
  102440. }
  102441. /*
  102442. ** This array defines hard upper bounds on limit values. The
  102443. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  102444. ** #defines in sqlite3.h.
  102445. */
  102446. static const int aHardLimit[] = {
  102447. SQLITE_MAX_LENGTH,
  102448. SQLITE_MAX_SQL_LENGTH,
  102449. SQLITE_MAX_COLUMN,
  102450. SQLITE_MAX_EXPR_DEPTH,
  102451. SQLITE_MAX_COMPOUND_SELECT,
  102452. SQLITE_MAX_VDBE_OP,
  102453. SQLITE_MAX_FUNCTION_ARG,
  102454. SQLITE_MAX_ATTACHED,
  102455. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  102456. SQLITE_MAX_VARIABLE_NUMBER,
  102457. SQLITE_MAX_TRIGGER_DEPTH,
  102458. };
  102459. /*
  102460. ** Make sure the hard limits are set to reasonable values
  102461. */
  102462. #if SQLITE_MAX_LENGTH<100
  102463. # error SQLITE_MAX_LENGTH must be at least 100
  102464. #endif
  102465. #if SQLITE_MAX_SQL_LENGTH<100
  102466. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  102467. #endif
  102468. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  102469. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  102470. #endif
  102471. #if SQLITE_MAX_COMPOUND_SELECT<2
  102472. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  102473. #endif
  102474. #if SQLITE_MAX_VDBE_OP<40
  102475. # error SQLITE_MAX_VDBE_OP must be at least 40
  102476. #endif
  102477. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  102478. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  102479. #endif
  102480. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  102481. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  102482. #endif
  102483. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  102484. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  102485. #endif
  102486. #if SQLITE_MAX_COLUMN>32767
  102487. # error SQLITE_MAX_COLUMN must not exceed 32767
  102488. #endif
  102489. #if SQLITE_MAX_TRIGGER_DEPTH<1
  102490. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  102491. #endif
  102492. /*
  102493. ** Change the value of a limit. Report the old value.
  102494. ** If an invalid limit index is supplied, report -1.
  102495. ** Make no changes but still report the old value if the
  102496. ** new limit is negative.
  102497. **
  102498. ** A new lower limit does not shrink existing constructs.
  102499. ** It merely prevents new constructs that exceed the limit
  102500. ** from forming.
  102501. */
  102502. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  102503. int oldLimit;
  102504. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  102505. ** there is a hard upper bound set at compile-time by a C preprocessor
  102506. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  102507. ** "_MAX_".)
  102508. */
  102509. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  102510. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  102511. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  102512. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  102513. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  102514. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  102515. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  102516. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  102517. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  102518. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  102519. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  102520. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  102521. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  102522. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  102523. return -1;
  102524. }
  102525. oldLimit = db->aLimit[limitId];
  102526. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  102527. if( newLimit>aHardLimit[limitId] ){
  102528. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  102529. }
  102530. db->aLimit[limitId] = newLimit;
  102531. }
  102532. return oldLimit; /* IMP: R-53341-35419 */
  102533. }
  102534. /*
  102535. ** This function is used to parse both URIs and non-URI filenames passed by the
  102536. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  102537. ** URIs specified as part of ATTACH statements.
  102538. **
  102539. ** The first argument to this function is the name of the VFS to use (or
  102540. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  102541. ** query parameter. The second argument contains the URI (or non-URI filename)
  102542. ** itself. When this function is called the *pFlags variable should contain
  102543. ** the default flags to open the database handle with. The value stored in
  102544. ** *pFlags may be updated before returning if the URI filename contains
  102545. ** "cache=xxx" or "mode=xxx" query parameters.
  102546. **
  102547. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  102548. ** the VFS that should be used to open the database file. *pzFile is set to
  102549. ** point to a buffer containing the name of the file to open. It is the
  102550. ** responsibility of the caller to eventually call sqlite3_free() to release
  102551. ** this buffer.
  102552. **
  102553. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  102554. ** may be set to point to a buffer containing an English language error
  102555. ** message. It is the responsibility of the caller to eventually release
  102556. ** this buffer by calling sqlite3_free().
  102557. */
  102558. SQLITE_PRIVATE int sqlite3ParseUri(
  102559. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  102560. const char *zUri, /* Nul-terminated URI to parse */
  102561. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  102562. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  102563. char **pzFile, /* OUT: Filename component of URI */
  102564. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  102565. ){
  102566. int rc = SQLITE_OK;
  102567. unsigned int flags = *pFlags;
  102568. const char *zVfs = zDefaultVfs;
  102569. char *zFile;
  102570. char c;
  102571. int nUri = sqlite3Strlen30(zUri);
  102572. assert( *pzErrMsg==0 );
  102573. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  102574. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  102575. ){
  102576. char *zOpt;
  102577. int eState; /* Parser state when parsing URI */
  102578. int iIn; /* Input character index */
  102579. int iOut = 0; /* Output character index */
  102580. int nByte = nUri+2; /* Bytes of space to allocate */
  102581. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  102582. ** method that there may be extra parameters following the file-name. */
  102583. flags |= SQLITE_OPEN_URI;
  102584. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  102585. zFile = sqlite3_malloc(nByte);
  102586. if( !zFile ) return SQLITE_NOMEM;
  102587. iIn = 5;
  102588. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  102589. /* Discard the scheme and authority segments of the URI. */
  102590. if( zUri[5]=='/' && zUri[6]=='/' ){
  102591. iIn = 7;
  102592. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  102593. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  102594. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  102595. iIn-7, &zUri[7]);
  102596. rc = SQLITE_ERROR;
  102597. goto parse_uri_out;
  102598. }
  102599. }
  102600. #endif
  102601. /* Copy the filename and any query parameters into the zFile buffer.
  102602. ** Decode %HH escape codes along the way.
  102603. **
  102604. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  102605. ** on the parsing context. As follows:
  102606. **
  102607. ** 0: Parsing file-name.
  102608. ** 1: Parsing name section of a name=value query parameter.
  102609. ** 2: Parsing value section of a name=value query parameter.
  102610. */
  102611. eState = 0;
  102612. while( (c = zUri[iIn])!=0 && c!='#' ){
  102613. iIn++;
  102614. if( c=='%'
  102615. && sqlite3Isxdigit(zUri[iIn])
  102616. && sqlite3Isxdigit(zUri[iIn+1])
  102617. ){
  102618. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  102619. octet += sqlite3HexToInt(zUri[iIn++]);
  102620. assert( octet>=0 && octet<256 );
  102621. if( octet==0 ){
  102622. /* This branch is taken when "%00" appears within the URI. In this
  102623. ** case we ignore all text in the remainder of the path, name or
  102624. ** value currently being parsed. So ignore the current character
  102625. ** and skip to the next "?", "=" or "&", as appropriate. */
  102626. while( (c = zUri[iIn])!=0 && c!='#'
  102627. && (eState!=0 || c!='?')
  102628. && (eState!=1 || (c!='=' && c!='&'))
  102629. && (eState!=2 || c!='&')
  102630. ){
  102631. iIn++;
  102632. }
  102633. continue;
  102634. }
  102635. c = octet;
  102636. }else if( eState==1 && (c=='&' || c=='=') ){
  102637. if( zFile[iOut-1]==0 ){
  102638. /* An empty option name. Ignore this option altogether. */
  102639. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  102640. continue;
  102641. }
  102642. if( c=='&' ){
  102643. zFile[iOut++] = '\0';
  102644. }else{
  102645. eState = 2;
  102646. }
  102647. c = 0;
  102648. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  102649. c = 0;
  102650. eState = 1;
  102651. }
  102652. zFile[iOut++] = c;
  102653. }
  102654. if( eState==1 ) zFile[iOut++] = '\0';
  102655. zFile[iOut++] = '\0';
  102656. zFile[iOut++] = '\0';
  102657. /* Check if there were any options specified that should be interpreted
  102658. ** here. Options that are interpreted here include "vfs" and those that
  102659. ** correspond to flags that may be passed to the sqlite3_open_v2()
  102660. ** method. */
  102661. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  102662. while( zOpt[0] ){
  102663. int nOpt = sqlite3Strlen30(zOpt);
  102664. char *zVal = &zOpt[nOpt+1];
  102665. int nVal = sqlite3Strlen30(zVal);
  102666. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  102667. zVfs = zVal;
  102668. }else{
  102669. struct OpenMode {
  102670. const char *z;
  102671. int mode;
  102672. } *aMode = 0;
  102673. char *zModeType = 0;
  102674. int mask = 0;
  102675. int limit = 0;
  102676. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  102677. static struct OpenMode aCacheMode[] = {
  102678. { "shared", SQLITE_OPEN_SHAREDCACHE },
  102679. { "private", SQLITE_OPEN_PRIVATECACHE },
  102680. { 0, 0 }
  102681. };
  102682. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  102683. aMode = aCacheMode;
  102684. limit = mask;
  102685. zModeType = "cache";
  102686. }
  102687. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  102688. static struct OpenMode aOpenMode[] = {
  102689. { "ro", SQLITE_OPEN_READONLY },
  102690. { "rw", SQLITE_OPEN_READWRITE },
  102691. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  102692. { "memory", SQLITE_OPEN_MEMORY },
  102693. { 0, 0 }
  102694. };
  102695. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  102696. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  102697. aMode = aOpenMode;
  102698. limit = mask & flags;
  102699. zModeType = "access";
  102700. }
  102701. if( aMode ){
  102702. int i;
  102703. int mode = 0;
  102704. for(i=0; aMode[i].z; i++){
  102705. const char *z = aMode[i].z;
  102706. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  102707. mode = aMode[i].mode;
  102708. break;
  102709. }
  102710. }
  102711. if( mode==0 ){
  102712. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  102713. rc = SQLITE_ERROR;
  102714. goto parse_uri_out;
  102715. }
  102716. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  102717. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  102718. zModeType, zVal);
  102719. rc = SQLITE_PERM;
  102720. goto parse_uri_out;
  102721. }
  102722. flags = (flags & ~mask) | mode;
  102723. }
  102724. }
  102725. zOpt = &zVal[nVal+1];
  102726. }
  102727. }else{
  102728. zFile = sqlite3_malloc(nUri+2);
  102729. if( !zFile ) return SQLITE_NOMEM;
  102730. memcpy(zFile, zUri, nUri);
  102731. zFile[nUri] = '\0';
  102732. zFile[nUri+1] = '\0';
  102733. flags &= ~SQLITE_OPEN_URI;
  102734. }
  102735. *ppVfs = sqlite3_vfs_find(zVfs);
  102736. if( *ppVfs==0 ){
  102737. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  102738. rc = SQLITE_ERROR;
  102739. }
  102740. parse_uri_out:
  102741. if( rc!=SQLITE_OK ){
  102742. sqlite3_free(zFile);
  102743. zFile = 0;
  102744. }
  102745. *pFlags = flags;
  102746. *pzFile = zFile;
  102747. return rc;
  102748. }
  102749. /*
  102750. ** This routine does the work of opening a database on behalf of
  102751. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  102752. ** is UTF-8 encoded.
  102753. */
  102754. static int openDatabase(
  102755. const char *zFilename, /* Database filename UTF-8 encoded */
  102756. sqlite3 **ppDb, /* OUT: Returned database handle */
  102757. unsigned int flags, /* Operational flags */
  102758. const char *zVfs /* Name of the VFS to use */
  102759. ){
  102760. sqlite3 *db; /* Store allocated handle here */
  102761. int rc; /* Return code */
  102762. int isThreadsafe; /* True for threadsafe connections */
  102763. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  102764. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  102765. *ppDb = 0;
  102766. #ifndef SQLITE_OMIT_AUTOINIT
  102767. rc = sqlite3_initialize();
  102768. if( rc ) return rc;
  102769. #endif
  102770. /* Only allow sensible combinations of bits in the flags argument.
  102771. ** Throw an error if any non-sense combination is used. If we
  102772. ** do not block illegal combinations here, it could trigger
  102773. ** assert() statements in deeper layers. Sensible combinations
  102774. ** are:
  102775. **
  102776. ** 1: SQLITE_OPEN_READONLY
  102777. ** 2: SQLITE_OPEN_READWRITE
  102778. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  102779. */
  102780. assert( SQLITE_OPEN_READONLY == 0x01 );
  102781. assert( SQLITE_OPEN_READWRITE == 0x02 );
  102782. assert( SQLITE_OPEN_CREATE == 0x04 );
  102783. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  102784. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  102785. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  102786. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  102787. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  102788. isThreadsafe = 0;
  102789. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  102790. isThreadsafe = 0;
  102791. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  102792. isThreadsafe = 1;
  102793. }else{
  102794. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  102795. }
  102796. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  102797. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  102798. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  102799. flags |= SQLITE_OPEN_SHAREDCACHE;
  102800. }
  102801. /* Remove harmful bits from the flags parameter
  102802. **
  102803. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  102804. ** dealt with in the previous code block. Besides these, the only
  102805. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  102806. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  102807. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  102808. ** off all other flags.
  102809. */
  102810. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  102811. SQLITE_OPEN_EXCLUSIVE |
  102812. SQLITE_OPEN_MAIN_DB |
  102813. SQLITE_OPEN_TEMP_DB |
  102814. SQLITE_OPEN_TRANSIENT_DB |
  102815. SQLITE_OPEN_MAIN_JOURNAL |
  102816. SQLITE_OPEN_TEMP_JOURNAL |
  102817. SQLITE_OPEN_SUBJOURNAL |
  102818. SQLITE_OPEN_MASTER_JOURNAL |
  102819. SQLITE_OPEN_NOMUTEX |
  102820. SQLITE_OPEN_FULLMUTEX |
  102821. SQLITE_OPEN_WAL
  102822. );
  102823. /* Allocate the sqlite data structure */
  102824. db = sqlite3MallocZero( sizeof(sqlite3) );
  102825. if( db==0 ) goto opendb_out;
  102826. if( isThreadsafe ){
  102827. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  102828. if( db->mutex==0 ){
  102829. sqlite3_free(db);
  102830. db = 0;
  102831. goto opendb_out;
  102832. }
  102833. }
  102834. sqlite3_mutex_enter(db->mutex);
  102835. db->errMask = 0xff;
  102836. db->nDb = 2;
  102837. db->magic = SQLITE_MAGIC_BUSY;
  102838. db->aDb = db->aDbStatic;
  102839. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  102840. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  102841. db->autoCommit = 1;
  102842. db->nextAutovac = -1;
  102843. db->szMmap = sqlite3GlobalConfig.szMmap;
  102844. db->nextPagesize = 0;
  102845. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  102846. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  102847. | SQLITE_AutoIndex
  102848. #endif
  102849. #if SQLITE_DEFAULT_FILE_FORMAT<4
  102850. | SQLITE_LegacyFileFmt
  102851. #endif
  102852. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  102853. | SQLITE_LoadExtension
  102854. #endif
  102855. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  102856. | SQLITE_RecTriggers
  102857. #endif
  102858. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  102859. | SQLITE_ForeignKeys
  102860. #endif
  102861. ;
  102862. sqlite3HashInit(&db->aCollSeq);
  102863. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102864. sqlite3HashInit(&db->aModule);
  102865. #endif
  102866. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  102867. ** and UTF-16, so add a version for each to avoid any unnecessary
  102868. ** conversions. The only error that can occur here is a malloc() failure.
  102869. */
  102870. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  102871. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  102872. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  102873. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  102874. if( db->mallocFailed ){
  102875. goto opendb_out;
  102876. }
  102877. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  102878. assert( db->pDfltColl!=0 );
  102879. /* Also add a UTF-8 case-insensitive collation sequence. */
  102880. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  102881. /* Parse the filename/URI argument. */
  102882. db->openFlags = flags;
  102883. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  102884. if( rc!=SQLITE_OK ){
  102885. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  102886. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  102887. sqlite3_free(zErrMsg);
  102888. goto opendb_out;
  102889. }
  102890. /* Open the backend database driver */
  102891. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  102892. flags | SQLITE_OPEN_MAIN_DB);
  102893. if( rc!=SQLITE_OK ){
  102894. if( rc==SQLITE_IOERR_NOMEM ){
  102895. rc = SQLITE_NOMEM;
  102896. }
  102897. sqlite3Error(db, rc, 0);
  102898. goto opendb_out;
  102899. }
  102900. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  102901. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  102902. /* The default safety_level for the main database is 'full'; for the temp
  102903. ** database it is 'NONE'. This matches the pager layer defaults.
  102904. */
  102905. db->aDb[0].zName = "main";
  102906. db->aDb[0].safety_level = 3;
  102907. db->aDb[1].zName = "temp";
  102908. db->aDb[1].safety_level = 1;
  102909. db->magic = SQLITE_MAGIC_OPEN;
  102910. if( db->mallocFailed ){
  102911. goto opendb_out;
  102912. }
  102913. /* Register all built-in functions, but do not attempt to read the
  102914. ** database schema yet. This is delayed until the first time the database
  102915. ** is accessed.
  102916. */
  102917. sqlite3Error(db, SQLITE_OK, 0);
  102918. sqlite3RegisterBuiltinFunctions(db);
  102919. /* Load automatic extensions - extensions that have been registered
  102920. ** using the sqlite3_automatic_extension() API.
  102921. */
  102922. rc = sqlite3_errcode(db);
  102923. if( rc==SQLITE_OK ){
  102924. sqlite3AutoLoadExtensions(db);
  102925. rc = sqlite3_errcode(db);
  102926. if( rc!=SQLITE_OK ){
  102927. goto opendb_out;
  102928. }
  102929. }
  102930. #ifdef SQLITE_ENABLE_FTS1
  102931. if( !db->mallocFailed ){
  102932. extern int sqlite3Fts1Init(sqlite3*);
  102933. rc = sqlite3Fts1Init(db);
  102934. }
  102935. #endif
  102936. #ifdef SQLITE_ENABLE_FTS2
  102937. if( !db->mallocFailed && rc==SQLITE_OK ){
  102938. extern int sqlite3Fts2Init(sqlite3*);
  102939. rc = sqlite3Fts2Init(db);
  102940. }
  102941. #endif
  102942. #ifdef SQLITE_ENABLE_FTS3
  102943. if( !db->mallocFailed && rc==SQLITE_OK ){
  102944. rc = sqlite3Fts3Init(db);
  102945. }
  102946. #endif
  102947. #ifdef SQLITE_ENABLE_ICU
  102948. if( !db->mallocFailed && rc==SQLITE_OK ){
  102949. rc = sqlite3IcuInit(db);
  102950. }
  102951. #endif
  102952. #ifdef SQLITE_ENABLE_RTREE
  102953. if( !db->mallocFailed && rc==SQLITE_OK){
  102954. rc = sqlite3RtreeInit(db);
  102955. }
  102956. #endif
  102957. sqlite3Error(db, rc, 0);
  102958. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  102959. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  102960. ** mode. Doing nothing at all also makes NORMAL the default.
  102961. */
  102962. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  102963. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  102964. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  102965. SQLITE_DEFAULT_LOCKING_MODE);
  102966. #endif
  102967. /* Enable the lookaside-malloc subsystem */
  102968. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  102969. sqlite3GlobalConfig.nLookaside);
  102970. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  102971. opendb_out:
  102972. sqlite3_free(zOpen);
  102973. if( db ){
  102974. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  102975. sqlite3_mutex_leave(db->mutex);
  102976. }
  102977. rc = sqlite3_errcode(db);
  102978. assert( db!=0 || rc==SQLITE_NOMEM );
  102979. if( rc==SQLITE_NOMEM ){
  102980. sqlite3_close(db);
  102981. db = 0;
  102982. }else if( rc!=SQLITE_OK ){
  102983. db->magic = SQLITE_MAGIC_SICK;
  102984. }
  102985. *ppDb = db;
  102986. #ifdef SQLITE_ENABLE_SQLLOG
  102987. if( sqlite3GlobalConfig.xSqllog ){
  102988. /* Opening a db handle. Fourth parameter is passed 0. */
  102989. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  102990. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  102991. }
  102992. #endif
  102993. return sqlite3ApiExit(0, rc);
  102994. }
  102995. /*
  102996. ** Open a new database handle.
  102997. */
  102998. SQLITE_API int sqlite3_open(
  102999. const char *zFilename,
  103000. sqlite3 **ppDb
  103001. ){
  103002. return openDatabase(zFilename, ppDb,
  103003. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  103004. }
  103005. SQLITE_API int sqlite3_open_v2(
  103006. const char *filename, /* Database filename (UTF-8) */
  103007. sqlite3 **ppDb, /* OUT: SQLite db handle */
  103008. int flags, /* Flags */
  103009. const char *zVfs /* Name of VFS module to use */
  103010. ){
  103011. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  103012. }
  103013. #ifndef SQLITE_OMIT_UTF16
  103014. /*
  103015. ** Open a new database handle.
  103016. */
  103017. SQLITE_API int sqlite3_open16(
  103018. const void *zFilename,
  103019. sqlite3 **ppDb
  103020. ){
  103021. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  103022. sqlite3_value *pVal;
  103023. int rc;
  103024. assert( zFilename );
  103025. assert( ppDb );
  103026. *ppDb = 0;
  103027. #ifndef SQLITE_OMIT_AUTOINIT
  103028. rc = sqlite3_initialize();
  103029. if( rc ) return rc;
  103030. #endif
  103031. pVal = sqlite3ValueNew(0);
  103032. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  103033. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  103034. if( zFilename8 ){
  103035. rc = openDatabase(zFilename8, ppDb,
  103036. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  103037. assert( *ppDb || rc==SQLITE_NOMEM );
  103038. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  103039. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  103040. }
  103041. }else{
  103042. rc = SQLITE_NOMEM;
  103043. }
  103044. sqlite3ValueFree(pVal);
  103045. return sqlite3ApiExit(0, rc);
  103046. }
  103047. #endif /* SQLITE_OMIT_UTF16 */
  103048. /*
  103049. ** Register a new collation sequence with the database handle db.
  103050. */
  103051. SQLITE_API int sqlite3_create_collation(
  103052. sqlite3* db,
  103053. const char *zName,
  103054. int enc,
  103055. void* pCtx,
  103056. int(*xCompare)(void*,int,const void*,int,const void*)
  103057. ){
  103058. int rc;
  103059. sqlite3_mutex_enter(db->mutex);
  103060. assert( !db->mallocFailed );
  103061. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  103062. rc = sqlite3ApiExit(db, rc);
  103063. sqlite3_mutex_leave(db->mutex);
  103064. return rc;
  103065. }
  103066. /*
  103067. ** Register a new collation sequence with the database handle db.
  103068. */
  103069. SQLITE_API int sqlite3_create_collation_v2(
  103070. sqlite3* db,
  103071. const char *zName,
  103072. int enc,
  103073. void* pCtx,
  103074. int(*xCompare)(void*,int,const void*,int,const void*),
  103075. void(*xDel)(void*)
  103076. ){
  103077. int rc;
  103078. sqlite3_mutex_enter(db->mutex);
  103079. assert( !db->mallocFailed );
  103080. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  103081. rc = sqlite3ApiExit(db, rc);
  103082. sqlite3_mutex_leave(db->mutex);
  103083. return rc;
  103084. }
  103085. #ifndef SQLITE_OMIT_UTF16
  103086. /*
  103087. ** Register a new collation sequence with the database handle db.
  103088. */
  103089. SQLITE_API int sqlite3_create_collation16(
  103090. sqlite3* db,
  103091. const void *zName,
  103092. int enc,
  103093. void* pCtx,
  103094. int(*xCompare)(void*,int,const void*,int,const void*)
  103095. ){
  103096. int rc = SQLITE_OK;
  103097. char *zName8;
  103098. sqlite3_mutex_enter(db->mutex);
  103099. assert( !db->mallocFailed );
  103100. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  103101. if( zName8 ){
  103102. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  103103. sqlite3DbFree(db, zName8);
  103104. }
  103105. rc = sqlite3ApiExit(db, rc);
  103106. sqlite3_mutex_leave(db->mutex);
  103107. return rc;
  103108. }
  103109. #endif /* SQLITE_OMIT_UTF16 */
  103110. /*
  103111. ** Register a collation sequence factory callback with the database handle
  103112. ** db. Replace any previously installed collation sequence factory.
  103113. */
  103114. SQLITE_API int sqlite3_collation_needed(
  103115. sqlite3 *db,
  103116. void *pCollNeededArg,
  103117. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  103118. ){
  103119. sqlite3_mutex_enter(db->mutex);
  103120. db->xCollNeeded = xCollNeeded;
  103121. db->xCollNeeded16 = 0;
  103122. db->pCollNeededArg = pCollNeededArg;
  103123. sqlite3_mutex_leave(db->mutex);
  103124. return SQLITE_OK;
  103125. }
  103126. #ifndef SQLITE_OMIT_UTF16
  103127. /*
  103128. ** Register a collation sequence factory callback with the database handle
  103129. ** db. Replace any previously installed collation sequence factory.
  103130. */
  103131. SQLITE_API int sqlite3_collation_needed16(
  103132. sqlite3 *db,
  103133. void *pCollNeededArg,
  103134. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  103135. ){
  103136. sqlite3_mutex_enter(db->mutex);
  103137. db->xCollNeeded = 0;
  103138. db->xCollNeeded16 = xCollNeeded16;
  103139. db->pCollNeededArg = pCollNeededArg;
  103140. sqlite3_mutex_leave(db->mutex);
  103141. return SQLITE_OK;
  103142. }
  103143. #endif /* SQLITE_OMIT_UTF16 */
  103144. #ifndef SQLITE_OMIT_DEPRECATED
  103145. /*
  103146. ** This function is now an anachronism. It used to be used to recover from a
  103147. ** malloc() failure, but SQLite now does this automatically.
  103148. */
  103149. SQLITE_API int sqlite3_global_recover(void){
  103150. return SQLITE_OK;
  103151. }
  103152. #endif
  103153. /*
  103154. ** Test to see whether or not the database connection is in autocommit
  103155. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  103156. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  103157. ** by the next COMMIT or ROLLBACK.
  103158. */
  103159. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  103160. return db->autoCommit;
  103161. }
  103162. /*
  103163. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  103164. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  103165. ** constants. They server two purposes:
  103166. **
  103167. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  103168. ** to detect when version error conditions occurs.
  103169. **
  103170. ** 2. Invoke sqlite3_log() to provide the source code location where
  103171. ** a low-level error is first detected.
  103172. */
  103173. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  103174. testcase( sqlite3GlobalConfig.xLog!=0 );
  103175. sqlite3_log(SQLITE_CORRUPT,
  103176. "database corruption at line %d of [%.10s]",
  103177. lineno, 20+sqlite3_sourceid());
  103178. return SQLITE_CORRUPT;
  103179. }
  103180. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  103181. testcase( sqlite3GlobalConfig.xLog!=0 );
  103182. sqlite3_log(SQLITE_MISUSE,
  103183. "misuse at line %d of [%.10s]",
  103184. lineno, 20+sqlite3_sourceid());
  103185. return SQLITE_MISUSE;
  103186. }
  103187. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  103188. testcase( sqlite3GlobalConfig.xLog!=0 );
  103189. sqlite3_log(SQLITE_CANTOPEN,
  103190. "cannot open file at line %d of [%.10s]",
  103191. lineno, 20+sqlite3_sourceid());
  103192. return SQLITE_CANTOPEN;
  103193. }
  103194. #ifndef SQLITE_OMIT_DEPRECATED
  103195. /*
  103196. ** This is a convenience routine that makes sure that all thread-specific
  103197. ** data for this thread has been deallocated.
  103198. **
  103199. ** SQLite no longer uses thread-specific data so this routine is now a
  103200. ** no-op. It is retained for historical compatibility.
  103201. */
  103202. SQLITE_API void sqlite3_thread_cleanup(void){
  103203. }
  103204. #endif
  103205. /*
  103206. ** Return meta information about a specific column of a database table.
  103207. ** See comment in sqlite3.h (sqlite.h.in) for details.
  103208. */
  103209. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103210. SQLITE_API int sqlite3_table_column_metadata(
  103211. sqlite3 *db, /* Connection handle */
  103212. const char *zDbName, /* Database name or NULL */
  103213. const char *zTableName, /* Table name */
  103214. const char *zColumnName, /* Column name */
  103215. char const **pzDataType, /* OUTPUT: Declared data type */
  103216. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  103217. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  103218. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  103219. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  103220. ){
  103221. int rc;
  103222. char *zErrMsg = 0;
  103223. Table *pTab = 0;
  103224. Column *pCol = 0;
  103225. int iCol;
  103226. char const *zDataType = 0;
  103227. char const *zCollSeq = 0;
  103228. int notnull = 0;
  103229. int primarykey = 0;
  103230. int autoinc = 0;
  103231. /* Ensure the database schema has been loaded */
  103232. sqlite3_mutex_enter(db->mutex);
  103233. sqlite3BtreeEnterAll(db);
  103234. rc = sqlite3Init(db, &zErrMsg);
  103235. if( SQLITE_OK!=rc ){
  103236. goto error_out;
  103237. }
  103238. /* Locate the table in question */
  103239. pTab = sqlite3FindTable(db, zTableName, zDbName);
  103240. if( !pTab || pTab->pSelect ){
  103241. pTab = 0;
  103242. goto error_out;
  103243. }
  103244. /* Find the column for which info is requested */
  103245. if( sqlite3IsRowid(zColumnName) ){
  103246. iCol = pTab->iPKey;
  103247. if( iCol>=0 ){
  103248. pCol = &pTab->aCol[iCol];
  103249. }
  103250. }else{
  103251. for(iCol=0; iCol<pTab->nCol; iCol++){
  103252. pCol = &pTab->aCol[iCol];
  103253. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  103254. break;
  103255. }
  103256. }
  103257. if( iCol==pTab->nCol ){
  103258. pTab = 0;
  103259. goto error_out;
  103260. }
  103261. }
  103262. /* The following block stores the meta information that will be returned
  103263. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  103264. ** and autoinc. At this point there are two possibilities:
  103265. **
  103266. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  103267. ** and there is no explicitly declared IPK column.
  103268. **
  103269. ** 2. The table is not a view and the column name identified an
  103270. ** explicitly declared column. Copy meta information from *pCol.
  103271. */
  103272. if( pCol ){
  103273. zDataType = pCol->zType;
  103274. zCollSeq = pCol->zColl;
  103275. notnull = pCol->notNull!=0;
  103276. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  103277. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  103278. }else{
  103279. zDataType = "INTEGER";
  103280. primarykey = 1;
  103281. }
  103282. if( !zCollSeq ){
  103283. zCollSeq = "BINARY";
  103284. }
  103285. error_out:
  103286. sqlite3BtreeLeaveAll(db);
  103287. /* Whether the function call succeeded or failed, set the output parameters
  103288. ** to whatever their local counterparts contain. If an error did occur,
  103289. ** this has the effect of zeroing all output parameters.
  103290. */
  103291. if( pzDataType ) *pzDataType = zDataType;
  103292. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  103293. if( pNotNull ) *pNotNull = notnull;
  103294. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  103295. if( pAutoinc ) *pAutoinc = autoinc;
  103296. if( SQLITE_OK==rc && !pTab ){
  103297. sqlite3DbFree(db, zErrMsg);
  103298. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  103299. zColumnName);
  103300. rc = SQLITE_ERROR;
  103301. }
  103302. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  103303. sqlite3DbFree(db, zErrMsg);
  103304. rc = sqlite3ApiExit(db, rc);
  103305. sqlite3_mutex_leave(db->mutex);
  103306. return rc;
  103307. }
  103308. #endif
  103309. /*
  103310. ** Sleep for a little while. Return the amount of time slept.
  103311. */
  103312. SQLITE_API int sqlite3_sleep(int ms){
  103313. sqlite3_vfs *pVfs;
  103314. int rc;
  103315. pVfs = sqlite3_vfs_find(0);
  103316. if( pVfs==0 ) return 0;
  103317. /* This function works in milliseconds, but the underlying OsSleep()
  103318. ** API uses microseconds. Hence the 1000's.
  103319. */
  103320. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  103321. return rc;
  103322. }
  103323. /*
  103324. ** Enable or disable the extended result codes.
  103325. */
  103326. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  103327. sqlite3_mutex_enter(db->mutex);
  103328. db->errMask = onoff ? 0xffffffff : 0xff;
  103329. sqlite3_mutex_leave(db->mutex);
  103330. return SQLITE_OK;
  103331. }
  103332. /*
  103333. ** Invoke the xFileControl method on a particular database.
  103334. */
  103335. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  103336. int rc = SQLITE_ERROR;
  103337. Btree *pBtree;
  103338. sqlite3_mutex_enter(db->mutex);
  103339. pBtree = sqlite3DbNameToBtree(db, zDbName);
  103340. if( pBtree ){
  103341. Pager *pPager;
  103342. sqlite3_file *fd;
  103343. sqlite3BtreeEnter(pBtree);
  103344. pPager = sqlite3BtreePager(pBtree);
  103345. assert( pPager!=0 );
  103346. fd = sqlite3PagerFile(pPager);
  103347. assert( fd!=0 );
  103348. if( op==SQLITE_FCNTL_FILE_POINTER ){
  103349. *(sqlite3_file**)pArg = fd;
  103350. rc = SQLITE_OK;
  103351. }else if( fd->pMethods ){
  103352. rc = sqlite3OsFileControl(fd, op, pArg);
  103353. }else{
  103354. rc = SQLITE_NOTFOUND;
  103355. }
  103356. sqlite3BtreeLeave(pBtree);
  103357. }
  103358. sqlite3_mutex_leave(db->mutex);
  103359. return rc;
  103360. }
  103361. /*
  103362. ** Interface to the testing logic.
  103363. */
  103364. SQLITE_API int sqlite3_test_control(int op, ...){
  103365. int rc = 0;
  103366. #ifndef SQLITE_OMIT_BUILTIN_TEST
  103367. va_list ap;
  103368. va_start(ap, op);
  103369. switch( op ){
  103370. /*
  103371. ** Save the current state of the PRNG.
  103372. */
  103373. case SQLITE_TESTCTRL_PRNG_SAVE: {
  103374. sqlite3PrngSaveState();
  103375. break;
  103376. }
  103377. /*
  103378. ** Restore the state of the PRNG to the last state saved using
  103379. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  103380. ** this verb acts like PRNG_RESET.
  103381. */
  103382. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  103383. sqlite3PrngRestoreState();
  103384. break;
  103385. }
  103386. /*
  103387. ** Reset the PRNG back to its uninitialized state. The next call
  103388. ** to sqlite3_randomness() will reseed the PRNG using a single call
  103389. ** to the xRandomness method of the default VFS.
  103390. */
  103391. case SQLITE_TESTCTRL_PRNG_RESET: {
  103392. sqlite3PrngResetState();
  103393. break;
  103394. }
  103395. /*
  103396. ** sqlite3_test_control(BITVEC_TEST, size, program)
  103397. **
  103398. ** Run a test against a Bitvec object of size. The program argument
  103399. ** is an array of integers that defines the test. Return -1 on a
  103400. ** memory allocation error, 0 on success, or non-zero for an error.
  103401. ** See the sqlite3BitvecBuiltinTest() for additional information.
  103402. */
  103403. case SQLITE_TESTCTRL_BITVEC_TEST: {
  103404. int sz = va_arg(ap, int);
  103405. int *aProg = va_arg(ap, int*);
  103406. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  103407. break;
  103408. }
  103409. /*
  103410. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  103411. **
  103412. ** Register hooks to call to indicate which malloc() failures
  103413. ** are benign.
  103414. */
  103415. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  103416. typedef void (*void_function)(void);
  103417. void_function xBenignBegin;
  103418. void_function xBenignEnd;
  103419. xBenignBegin = va_arg(ap, void_function);
  103420. xBenignEnd = va_arg(ap, void_function);
  103421. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  103422. break;
  103423. }
  103424. /*
  103425. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  103426. **
  103427. ** Set the PENDING byte to the value in the argument, if X>0.
  103428. ** Make no changes if X==0. Return the value of the pending byte
  103429. ** as it existing before this routine was called.
  103430. **
  103431. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  103432. ** an incompatible database file format. Changing the PENDING byte
  103433. ** while any database connection is open results in undefined and
  103434. ** dileterious behavior.
  103435. */
  103436. case SQLITE_TESTCTRL_PENDING_BYTE: {
  103437. rc = PENDING_BYTE;
  103438. #ifndef SQLITE_OMIT_WSD
  103439. {
  103440. unsigned int newVal = va_arg(ap, unsigned int);
  103441. if( newVal ) sqlite3PendingByte = newVal;
  103442. }
  103443. #endif
  103444. break;
  103445. }
  103446. /*
  103447. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  103448. **
  103449. ** This action provides a run-time test to see whether or not
  103450. ** assert() was enabled at compile-time. If X is true and assert()
  103451. ** is enabled, then the return value is true. If X is true and
  103452. ** assert() is disabled, then the return value is zero. If X is
  103453. ** false and assert() is enabled, then the assertion fires and the
  103454. ** process aborts. If X is false and assert() is disabled, then the
  103455. ** return value is zero.
  103456. */
  103457. case SQLITE_TESTCTRL_ASSERT: {
  103458. volatile int x = 0;
  103459. assert( (x = va_arg(ap,int))!=0 );
  103460. rc = x;
  103461. break;
  103462. }
  103463. /*
  103464. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  103465. **
  103466. ** This action provides a run-time test to see how the ALWAYS and
  103467. ** NEVER macros were defined at compile-time.
  103468. **
  103469. ** The return value is ALWAYS(X).
  103470. **
  103471. ** The recommended test is X==2. If the return value is 2, that means
  103472. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  103473. ** default setting. If the return value is 1, then ALWAYS() is either
  103474. ** hard-coded to true or else it asserts if its argument is false.
  103475. ** The first behavior (hard-coded to true) is the case if
  103476. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  103477. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  103478. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  103479. **
  103480. ** The run-time test procedure might look something like this:
  103481. **
  103482. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  103483. ** // ALWAYS() and NEVER() are no-op pass-through macros
  103484. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  103485. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  103486. ** }else{
  103487. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  103488. ** }
  103489. */
  103490. case SQLITE_TESTCTRL_ALWAYS: {
  103491. int x = va_arg(ap,int);
  103492. rc = ALWAYS(x);
  103493. break;
  103494. }
  103495. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  103496. **
  103497. ** Set the nReserve size to N for the main database on the database
  103498. ** connection db.
  103499. */
  103500. case SQLITE_TESTCTRL_RESERVE: {
  103501. sqlite3 *db = va_arg(ap, sqlite3*);
  103502. int x = va_arg(ap,int);
  103503. sqlite3_mutex_enter(db->mutex);
  103504. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  103505. sqlite3_mutex_leave(db->mutex);
  103506. break;
  103507. }
  103508. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  103509. **
  103510. ** Enable or disable various optimizations for testing purposes. The
  103511. ** argument N is a bitmask of optimizations to be disabled. For normal
  103512. ** operation N should be 0. The idea is that a test program (like the
  103513. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  103514. ** with various optimizations disabled to verify that the same answer
  103515. ** is obtained in every case.
  103516. */
  103517. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  103518. sqlite3 *db = va_arg(ap, sqlite3*);
  103519. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  103520. break;
  103521. }
  103522. #ifdef SQLITE_N_KEYWORD
  103523. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  103524. **
  103525. ** If zWord is a keyword recognized by the parser, then return the
  103526. ** number of keywords. Or if zWord is not a keyword, return 0.
  103527. **
  103528. ** This test feature is only available in the amalgamation since
  103529. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  103530. ** is built using separate source files.
  103531. */
  103532. case SQLITE_TESTCTRL_ISKEYWORD: {
  103533. const char *zWord = va_arg(ap, const char*);
  103534. int n = sqlite3Strlen30(zWord);
  103535. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  103536. break;
  103537. }
  103538. #endif
  103539. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  103540. **
  103541. ** Pass pFree into sqlite3ScratchFree().
  103542. ** If sz>0 then allocate a scratch buffer into pNew.
  103543. */
  103544. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  103545. void *pFree, **ppNew;
  103546. int sz;
  103547. sz = va_arg(ap, int);
  103548. ppNew = va_arg(ap, void**);
  103549. pFree = va_arg(ap, void*);
  103550. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  103551. sqlite3ScratchFree(pFree);
  103552. break;
  103553. }
  103554. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  103555. **
  103556. ** If parameter onoff is non-zero, configure the wrappers so that all
  103557. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  103558. ** undo this setting.
  103559. */
  103560. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  103561. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  103562. break;
  103563. }
  103564. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  103565. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  103566. ** sqlite3_stmt*,const char**);
  103567. **
  103568. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  103569. ** a string that describes the optimized parse tree. This test-control
  103570. ** returns a pointer to that string.
  103571. */
  103572. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  103573. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  103574. const char **pzRet = va_arg(ap, const char**);
  103575. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  103576. break;
  103577. }
  103578. #endif
  103579. }
  103580. va_end(ap);
  103581. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  103582. return rc;
  103583. }
  103584. /*
  103585. ** This is a utility routine, useful to VFS implementations, that checks
  103586. ** to see if a database file was a URI that contained a specific query
  103587. ** parameter, and if so obtains the value of the query parameter.
  103588. **
  103589. ** The zFilename argument is the filename pointer passed into the xOpen()
  103590. ** method of a VFS implementation. The zParam argument is the name of the
  103591. ** query parameter we seek. This routine returns the value of the zParam
  103592. ** parameter if it exists. If the parameter does not exist, this routine
  103593. ** returns a NULL pointer.
  103594. */
  103595. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  103596. if( zFilename==0 ) return 0;
  103597. zFilename += sqlite3Strlen30(zFilename) + 1;
  103598. while( zFilename[0] ){
  103599. int x = strcmp(zFilename, zParam);
  103600. zFilename += sqlite3Strlen30(zFilename) + 1;
  103601. if( x==0 ) return zFilename;
  103602. zFilename += sqlite3Strlen30(zFilename) + 1;
  103603. }
  103604. return 0;
  103605. }
  103606. /*
  103607. ** Return a boolean value for a query parameter.
  103608. */
  103609. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  103610. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  103611. bDflt = bDflt!=0;
  103612. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  103613. }
  103614. /*
  103615. ** Return a 64-bit integer value for a query parameter.
  103616. */
  103617. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  103618. const char *zFilename, /* Filename as passed to xOpen */
  103619. const char *zParam, /* URI parameter sought */
  103620. sqlite3_int64 bDflt /* return if parameter is missing */
  103621. ){
  103622. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  103623. sqlite3_int64 v;
  103624. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  103625. bDflt = v;
  103626. }
  103627. return bDflt;
  103628. }
  103629. /*
  103630. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  103631. */
  103632. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  103633. int i;
  103634. for(i=0; i<db->nDb; i++){
  103635. if( db->aDb[i].pBt
  103636. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  103637. ){
  103638. return db->aDb[i].pBt;
  103639. }
  103640. }
  103641. return 0;
  103642. }
  103643. /*
  103644. ** Return the filename of the database associated with a database
  103645. ** connection.
  103646. */
  103647. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  103648. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  103649. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  103650. }
  103651. /*
  103652. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  103653. ** no such database exists.
  103654. */
  103655. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  103656. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  103657. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  103658. }
  103659. /************** End of main.c ************************************************/
  103660. /************** Begin file notify.c ******************************************/
  103661. /*
  103662. ** 2009 March 3
  103663. **
  103664. ** The author disclaims copyright to this source code. In place of
  103665. ** a legal notice, here is a blessing:
  103666. **
  103667. ** May you do good and not evil.
  103668. ** May you find forgiveness for yourself and forgive others.
  103669. ** May you share freely, never taking more than you give.
  103670. **
  103671. *************************************************************************
  103672. **
  103673. ** This file contains the implementation of the sqlite3_unlock_notify()
  103674. ** API method and its associated functionality.
  103675. */
  103676. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  103677. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  103678. /*
  103679. ** Public interfaces:
  103680. **
  103681. ** sqlite3ConnectionBlocked()
  103682. ** sqlite3ConnectionUnlocked()
  103683. ** sqlite3ConnectionClosed()
  103684. ** sqlite3_unlock_notify()
  103685. */
  103686. #define assertMutexHeld() \
  103687. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  103688. /*
  103689. ** Head of a linked list of all sqlite3 objects created by this process
  103690. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  103691. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  103692. ** mutex is held.
  103693. */
  103694. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  103695. #ifndef NDEBUG
  103696. /*
  103697. ** This function is a complex assert() that verifies the following
  103698. ** properties of the blocked connections list:
  103699. **
  103700. ** 1) Each entry in the list has a non-NULL value for either
  103701. ** pUnlockConnection or pBlockingConnection, or both.
  103702. **
  103703. ** 2) All entries in the list that share a common value for
  103704. ** xUnlockNotify are grouped together.
  103705. **
  103706. ** 3) If the argument db is not NULL, then none of the entries in the
  103707. ** blocked connections list have pUnlockConnection or pBlockingConnection
  103708. ** set to db. This is used when closing connection db.
  103709. */
  103710. static void checkListProperties(sqlite3 *db){
  103711. sqlite3 *p;
  103712. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  103713. int seen = 0;
  103714. sqlite3 *p2;
  103715. /* Verify property (1) */
  103716. assert( p->pUnlockConnection || p->pBlockingConnection );
  103717. /* Verify property (2) */
  103718. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  103719. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  103720. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  103721. assert( db==0 || p->pUnlockConnection!=db );
  103722. assert( db==0 || p->pBlockingConnection!=db );
  103723. }
  103724. }
  103725. }
  103726. #else
  103727. # define checkListProperties(x)
  103728. #endif
  103729. /*
  103730. ** Remove connection db from the blocked connections list. If connection
  103731. ** db is not currently a part of the list, this function is a no-op.
  103732. */
  103733. static void removeFromBlockedList(sqlite3 *db){
  103734. sqlite3 **pp;
  103735. assertMutexHeld();
  103736. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  103737. if( *pp==db ){
  103738. *pp = (*pp)->pNextBlocked;
  103739. break;
  103740. }
  103741. }
  103742. }
  103743. /*
  103744. ** Add connection db to the blocked connections list. It is assumed
  103745. ** that it is not already a part of the list.
  103746. */
  103747. static void addToBlockedList(sqlite3 *db){
  103748. sqlite3 **pp;
  103749. assertMutexHeld();
  103750. for(
  103751. pp=&sqlite3BlockedList;
  103752. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  103753. pp=&(*pp)->pNextBlocked
  103754. );
  103755. db->pNextBlocked = *pp;
  103756. *pp = db;
  103757. }
  103758. /*
  103759. ** Obtain the STATIC_MASTER mutex.
  103760. */
  103761. static void enterMutex(void){
  103762. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  103763. checkListProperties(0);
  103764. }
  103765. /*
  103766. ** Release the STATIC_MASTER mutex.
  103767. */
  103768. static void leaveMutex(void){
  103769. assertMutexHeld();
  103770. checkListProperties(0);
  103771. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  103772. }
  103773. /*
  103774. ** Register an unlock-notify callback.
  103775. **
  103776. ** This is called after connection "db" has attempted some operation
  103777. ** but has received an SQLITE_LOCKED error because another connection
  103778. ** (call it pOther) in the same process was busy using the same shared
  103779. ** cache. pOther is found by looking at db->pBlockingConnection.
  103780. **
  103781. ** If there is no blocking connection, the callback is invoked immediately,
  103782. ** before this routine returns.
  103783. **
  103784. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  103785. ** a deadlock.
  103786. **
  103787. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  103788. ** its locks.
  103789. **
  103790. ** Each call to this routine overrides any prior callbacks registered
  103791. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  103792. ** cancelled.
  103793. */
  103794. SQLITE_API int sqlite3_unlock_notify(
  103795. sqlite3 *db,
  103796. void (*xNotify)(void **, int),
  103797. void *pArg
  103798. ){
  103799. int rc = SQLITE_OK;
  103800. sqlite3_mutex_enter(db->mutex);
  103801. enterMutex();
  103802. if( xNotify==0 ){
  103803. removeFromBlockedList(db);
  103804. db->pBlockingConnection = 0;
  103805. db->pUnlockConnection = 0;
  103806. db->xUnlockNotify = 0;
  103807. db->pUnlockArg = 0;
  103808. }else if( 0==db->pBlockingConnection ){
  103809. /* The blocking transaction has been concluded. Or there never was a
  103810. ** blocking transaction. In either case, invoke the notify callback
  103811. ** immediately.
  103812. */
  103813. xNotify(&pArg, 1);
  103814. }else{
  103815. sqlite3 *p;
  103816. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  103817. if( p ){
  103818. rc = SQLITE_LOCKED; /* Deadlock detected. */
  103819. }else{
  103820. db->pUnlockConnection = db->pBlockingConnection;
  103821. db->xUnlockNotify = xNotify;
  103822. db->pUnlockArg = pArg;
  103823. removeFromBlockedList(db);
  103824. addToBlockedList(db);
  103825. }
  103826. }
  103827. leaveMutex();
  103828. assert( !db->mallocFailed );
  103829. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  103830. sqlite3_mutex_leave(db->mutex);
  103831. return rc;
  103832. }
  103833. /*
  103834. ** This function is called while stepping or preparing a statement
  103835. ** associated with connection db. The operation will return SQLITE_LOCKED
  103836. ** to the user because it requires a lock that will not be available
  103837. ** until connection pBlocker concludes its current transaction.
  103838. */
  103839. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  103840. enterMutex();
  103841. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  103842. addToBlockedList(db);
  103843. }
  103844. db->pBlockingConnection = pBlocker;
  103845. leaveMutex();
  103846. }
  103847. /*
  103848. ** This function is called when
  103849. ** the transaction opened by database db has just finished. Locks held
  103850. ** by database connection db have been released.
  103851. **
  103852. ** This function loops through each entry in the blocked connections
  103853. ** list and does the following:
  103854. **
  103855. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  103856. ** set to db, then set pBlockingConnection=0.
  103857. **
  103858. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  103859. ** set to db, then invoke the configured unlock-notify callback and
  103860. ** set pUnlockConnection=0.
  103861. **
  103862. ** 3) If the two steps above mean that pBlockingConnection==0 and
  103863. ** pUnlockConnection==0, remove the entry from the blocked connections
  103864. ** list.
  103865. */
  103866. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  103867. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  103868. int nArg = 0; /* Number of entries in aArg[] */
  103869. sqlite3 **pp; /* Iterator variable */
  103870. void **aArg; /* Arguments to the unlock callback */
  103871. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  103872. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  103873. aArg = aStatic;
  103874. enterMutex(); /* Enter STATIC_MASTER mutex */
  103875. /* This loop runs once for each entry in the blocked-connections list. */
  103876. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  103877. sqlite3 *p = *pp;
  103878. /* Step 1. */
  103879. if( p->pBlockingConnection==db ){
  103880. p->pBlockingConnection = 0;
  103881. }
  103882. /* Step 2. */
  103883. if( p->pUnlockConnection==db ){
  103884. assert( p->xUnlockNotify );
  103885. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  103886. xUnlockNotify(aArg, nArg);
  103887. nArg = 0;
  103888. }
  103889. sqlite3BeginBenignMalloc();
  103890. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  103891. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  103892. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  103893. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  103894. ){
  103895. /* The aArg[] array needs to grow. */
  103896. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  103897. if( pNew ){
  103898. memcpy(pNew, aArg, nArg*sizeof(void *));
  103899. sqlite3_free(aDyn);
  103900. aDyn = aArg = pNew;
  103901. }else{
  103902. /* This occurs when the array of context pointers that need to
  103903. ** be passed to the unlock-notify callback is larger than the
  103904. ** aStatic[] array allocated on the stack and the attempt to
  103905. ** allocate a larger array from the heap has failed.
  103906. **
  103907. ** This is a difficult situation to handle. Returning an error
  103908. ** code to the caller is insufficient, as even if an error code
  103909. ** is returned the transaction on connection db will still be
  103910. ** closed and the unlock-notify callbacks on blocked connections
  103911. ** will go unissued. This might cause the application to wait
  103912. ** indefinitely for an unlock-notify callback that will never
  103913. ** arrive.
  103914. **
  103915. ** Instead, invoke the unlock-notify callback with the context
  103916. ** array already accumulated. We can then clear the array and
  103917. ** begin accumulating any further context pointers without
  103918. ** requiring any dynamic allocation. This is sub-optimal because
  103919. ** it means that instead of one callback with a large array of
  103920. ** context pointers the application will receive two or more
  103921. ** callbacks with smaller arrays of context pointers, which will
  103922. ** reduce the applications ability to prioritize multiple
  103923. ** connections. But it is the best that can be done under the
  103924. ** circumstances.
  103925. */
  103926. xUnlockNotify(aArg, nArg);
  103927. nArg = 0;
  103928. }
  103929. }
  103930. sqlite3EndBenignMalloc();
  103931. aArg[nArg++] = p->pUnlockArg;
  103932. xUnlockNotify = p->xUnlockNotify;
  103933. p->pUnlockConnection = 0;
  103934. p->xUnlockNotify = 0;
  103935. p->pUnlockArg = 0;
  103936. }
  103937. /* Step 3. */
  103938. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  103939. /* Remove connection p from the blocked connections list. */
  103940. *pp = p->pNextBlocked;
  103941. p->pNextBlocked = 0;
  103942. }else{
  103943. pp = &p->pNextBlocked;
  103944. }
  103945. }
  103946. if( nArg!=0 ){
  103947. xUnlockNotify(aArg, nArg);
  103948. }
  103949. sqlite3_free(aDyn);
  103950. leaveMutex(); /* Leave STATIC_MASTER mutex */
  103951. }
  103952. /*
  103953. ** This is called when the database connection passed as an argument is
  103954. ** being closed. The connection is removed from the blocked list.
  103955. */
  103956. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  103957. sqlite3ConnectionUnlocked(db);
  103958. enterMutex();
  103959. removeFromBlockedList(db);
  103960. checkListProperties(db);
  103961. leaveMutex();
  103962. }
  103963. #endif
  103964. /************** End of notify.c **********************************************/
  103965. /************** Begin file fts3.c ********************************************/
  103966. /*
  103967. ** 2006 Oct 10
  103968. **
  103969. ** The author disclaims copyright to this source code. In place of
  103970. ** a legal notice, here is a blessing:
  103971. **
  103972. ** May you do good and not evil.
  103973. ** May you find forgiveness for yourself and forgive others.
  103974. ** May you share freely, never taking more than you give.
  103975. **
  103976. ******************************************************************************
  103977. **
  103978. ** This is an SQLite module implementing full-text search.
  103979. */
  103980. /*
  103981. ** The code in this file is only compiled if:
  103982. **
  103983. ** * The FTS3 module is being built as an extension
  103984. ** (in which case SQLITE_CORE is not defined), or
  103985. **
  103986. ** * The FTS3 module is being built into the core of
  103987. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  103988. */
  103989. /* The full-text index is stored in a series of b+tree (-like)
  103990. ** structures called segments which map terms to doclists. The
  103991. ** structures are like b+trees in layout, but are constructed from the
  103992. ** bottom up in optimal fashion and are not updatable. Since trees
  103993. ** are built from the bottom up, things will be described from the
  103994. ** bottom up.
  103995. **
  103996. **
  103997. **** Varints ****
  103998. ** The basic unit of encoding is a variable-length integer called a
  103999. ** varint. We encode variable-length integers in little-endian order
  104000. ** using seven bits * per byte as follows:
  104001. **
  104002. ** KEY:
  104003. ** A = 0xxxxxxx 7 bits of data and one flag bit
  104004. ** B = 1xxxxxxx 7 bits of data and one flag bit
  104005. **
  104006. ** 7 bits - A
  104007. ** 14 bits - BA
  104008. ** 21 bits - BBA
  104009. ** and so on.
  104010. **
  104011. ** This is similar in concept to how sqlite encodes "varints" but
  104012. ** the encoding is not the same. SQLite varints are big-endian
  104013. ** are are limited to 9 bytes in length whereas FTS3 varints are
  104014. ** little-endian and can be up to 10 bytes in length (in theory).
  104015. **
  104016. ** Example encodings:
  104017. **
  104018. ** 1: 0x01
  104019. ** 127: 0x7f
  104020. ** 128: 0x81 0x00
  104021. **
  104022. **
  104023. **** Document lists ****
  104024. ** A doclist (document list) holds a docid-sorted list of hits for a
  104025. ** given term. Doclists hold docids and associated token positions.
  104026. ** A docid is the unique integer identifier for a single document.
  104027. ** A position is the index of a word within the document. The first
  104028. ** word of the document has a position of 0.
  104029. **
  104030. ** FTS3 used to optionally store character offsets using a compile-time
  104031. ** option. But that functionality is no longer supported.
  104032. **
  104033. ** A doclist is stored like this:
  104034. **
  104035. ** array {
  104036. ** varint docid; (delta from previous doclist)
  104037. ** array { (position list for column 0)
  104038. ** varint position; (2 more than the delta from previous position)
  104039. ** }
  104040. ** array {
  104041. ** varint POS_COLUMN; (marks start of position list for new column)
  104042. ** varint column; (index of new column)
  104043. ** array {
  104044. ** varint position; (2 more than the delta from previous position)
  104045. ** }
  104046. ** }
  104047. ** varint POS_END; (marks end of positions for this document.
  104048. ** }
  104049. **
  104050. ** Here, array { X } means zero or more occurrences of X, adjacent in
  104051. ** memory. A "position" is an index of a token in the token stream
  104052. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  104053. ** in the same logical place as the position element, and act as sentinals
  104054. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  104055. ** The positions numbers are not stored literally but rather as two more
  104056. ** than the difference from the prior position, or the just the position plus
  104057. ** 2 for the first position. Example:
  104058. **
  104059. ** label: A B C D E F G H I J K
  104060. ** value: 123 5 9 1 1 14 35 0 234 72 0
  104061. **
  104062. ** The 123 value is the first docid. For column zero in this document
  104063. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  104064. ** at D signals the start of a new column; the 1 at E indicates that the
  104065. ** new column is column number 1. There are two positions at 12 and 45
  104066. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  104067. ** 234 at I is the delta to next docid (357). It has one position 70
  104068. ** (72-2) and then terminates with the 0 at K.
  104069. **
  104070. ** A "position-list" is the list of positions for multiple columns for
  104071. ** a single docid. A "column-list" is the set of positions for a single
  104072. ** column. Hence, a position-list consists of one or more column-lists,
  104073. ** a document record consists of a docid followed by a position-list and
  104074. ** a doclist consists of one or more document records.
  104075. **
  104076. ** A bare doclist omits the position information, becoming an
  104077. ** array of varint-encoded docids.
  104078. **
  104079. **** Segment leaf nodes ****
  104080. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  104081. ** nodes are written using LeafWriter, and read using LeafReader (to
  104082. ** iterate through a single leaf node's data) and LeavesReader (to
  104083. ** iterate through a segment's entire leaf layer). Leaf nodes have
  104084. ** the format:
  104085. **
  104086. ** varint iHeight; (height from leaf level, always 0)
  104087. ** varint nTerm; (length of first term)
  104088. ** char pTerm[nTerm]; (content of first term)
  104089. ** varint nDoclist; (length of term's associated doclist)
  104090. ** char pDoclist[nDoclist]; (content of doclist)
  104091. ** array {
  104092. ** (further terms are delta-encoded)
  104093. ** varint nPrefix; (length of prefix shared with previous term)
  104094. ** varint nSuffix; (length of unshared suffix)
  104095. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  104096. ** varint nDoclist; (length of term's associated doclist)
  104097. ** char pDoclist[nDoclist]; (content of doclist)
  104098. ** }
  104099. **
  104100. ** Here, array { X } means zero or more occurrences of X, adjacent in
  104101. ** memory.
  104102. **
  104103. ** Leaf nodes are broken into blocks which are stored contiguously in
  104104. ** the %_segments table in sorted order. This means that when the end
  104105. ** of a node is reached, the next term is in the node with the next
  104106. ** greater node id.
  104107. **
  104108. ** New data is spilled to a new leaf node when the current node
  104109. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  104110. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  104111. ** node (a leaf node with a single term and doclist). The goal of
  104112. ** these settings is to pack together groups of small doclists while
  104113. ** making it efficient to directly access large doclists. The
  104114. ** assumption is that large doclists represent terms which are more
  104115. ** likely to be query targets.
  104116. **
  104117. ** TODO(shess) It may be useful for blocking decisions to be more
  104118. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  104119. ** node rather than splitting into 2k and .5k nodes. My intuition is
  104120. ** that this might extend through 2x or 4x the pagesize.
  104121. **
  104122. **
  104123. **** Segment interior nodes ****
  104124. ** Segment interior nodes store blockids for subtree nodes and terms
  104125. ** to describe what data is stored by the each subtree. Interior
  104126. ** nodes are written using InteriorWriter, and read using
  104127. ** InteriorReader. InteriorWriters are created as needed when
  104128. ** SegmentWriter creates new leaf nodes, or when an interior node
  104129. ** itself grows too big and must be split. The format of interior
  104130. ** nodes:
  104131. **
  104132. ** varint iHeight; (height from leaf level, always >0)
  104133. ** varint iBlockid; (block id of node's leftmost subtree)
  104134. ** optional {
  104135. ** varint nTerm; (length of first term)
  104136. ** char pTerm[nTerm]; (content of first term)
  104137. ** array {
  104138. ** (further terms are delta-encoded)
  104139. ** varint nPrefix; (length of shared prefix with previous term)
  104140. ** varint nSuffix; (length of unshared suffix)
  104141. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  104142. ** }
  104143. ** }
  104144. **
  104145. ** Here, optional { X } means an optional element, while array { X }
  104146. ** means zero or more occurrences of X, adjacent in memory.
  104147. **
  104148. ** An interior node encodes n terms separating n+1 subtrees. The
  104149. ** subtree blocks are contiguous, so only the first subtree's blockid
  104150. ** is encoded. The subtree at iBlockid will contain all terms less
  104151. ** than the first term encoded (or all terms if no term is encoded).
  104152. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  104153. ** than pTerm[i+1], the subtree for that term will be rooted at
  104154. ** iBlockid+i. Interior nodes only store enough term data to
  104155. ** distinguish adjacent children (if the rightmost term of the left
  104156. ** child is "something", and the leftmost term of the right child is
  104157. ** "wicked", only "w" is stored).
  104158. **
  104159. ** New data is spilled to a new interior node at the same height when
  104160. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  104161. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  104162. ** interior nodes and making the tree too skinny. The interior nodes
  104163. ** at a given height are naturally tracked by interior nodes at
  104164. ** height+1, and so on.
  104165. **
  104166. **
  104167. **** Segment directory ****
  104168. ** The segment directory in table %_segdir stores meta-information for
  104169. ** merging and deleting segments, and also the root node of the
  104170. ** segment's tree.
  104171. **
  104172. ** The root node is the top node of the segment's tree after encoding
  104173. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  104174. ** This could be either a leaf node or an interior node. If the top
  104175. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  104176. ** and a new root interior node is generated (which should always fit
  104177. ** within ROOT_MAX because it only needs space for 2 varints, the
  104178. ** height and the blockid of the previous root).
  104179. **
  104180. ** The meta-information in the segment directory is:
  104181. ** level - segment level (see below)
  104182. ** idx - index within level
  104183. ** - (level,idx uniquely identify a segment)
  104184. ** start_block - first leaf node
  104185. ** leaves_end_block - last leaf node
  104186. ** end_block - last block (including interior nodes)
  104187. ** root - contents of root node
  104188. **
  104189. ** If the root node is a leaf node, then start_block,
  104190. ** leaves_end_block, and end_block are all 0.
  104191. **
  104192. **
  104193. **** Segment merging ****
  104194. ** To amortize update costs, segments are grouped into levels and
  104195. ** merged in batches. Each increase in level represents exponentially
  104196. ** more documents.
  104197. **
  104198. ** New documents (actually, document updates) are tokenized and
  104199. ** written individually (using LeafWriter) to a level 0 segment, with
  104200. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  104201. ** level 0 segments are merged into a single level 1 segment. Level 1
  104202. ** is populated like level 0, and eventually MERGE_COUNT level 1
  104203. ** segments are merged to a single level 2 segment (representing
  104204. ** MERGE_COUNT^2 updates), and so on.
  104205. **
  104206. ** A segment merge traverses all segments at a given level in
  104207. ** parallel, performing a straightforward sorted merge. Since segment
  104208. ** leaf nodes are written in to the %_segments table in order, this
  104209. ** merge traverses the underlying sqlite disk structures efficiently.
  104210. ** After the merge, all segment blocks from the merged level are
  104211. ** deleted.
  104212. **
  104213. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  104214. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  104215. ** very similar performance numbers to 16 on insertion, though they're
  104216. ** a tiny bit slower (perhaps due to more overhead in merge-time
  104217. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  104218. ** 16, 2 about 66% slower than 16.
  104219. **
  104220. ** At query time, high MERGE_COUNT increases the number of segments
  104221. ** which need to be scanned and merged. For instance, with 100k docs
  104222. ** inserted:
  104223. **
  104224. ** MERGE_COUNT segments
  104225. ** 16 25
  104226. ** 8 12
  104227. ** 4 10
  104228. ** 2 6
  104229. **
  104230. ** This appears to have only a moderate impact on queries for very
  104231. ** frequent terms (which are somewhat dominated by segment merge
  104232. ** costs), and infrequent and non-existent terms still seem to be fast
  104233. ** even with many segments.
  104234. **
  104235. ** TODO(shess) That said, it would be nice to have a better query-side
  104236. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  104237. ** optimizations to things like doclist merging will swing the sweet
  104238. ** spot around.
  104239. **
  104240. **
  104241. **
  104242. **** Handling of deletions and updates ****
  104243. ** Since we're using a segmented structure, with no docid-oriented
  104244. ** index into the term index, we clearly cannot simply update the term
  104245. ** index when a document is deleted or updated. For deletions, we
  104246. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  104247. ** we simply write the new doclist. Segment merges overwrite older
  104248. ** data for a particular docid with newer data, so deletes or updates
  104249. ** will eventually overtake the earlier data and knock it out. The
  104250. ** query logic likewise merges doclists so that newer data knocks out
  104251. ** older data.
  104252. */
  104253. /************** Include fts3Int.h in the middle of fts3.c ********************/
  104254. /************** Begin file fts3Int.h *****************************************/
  104255. /*
  104256. ** 2009 Nov 12
  104257. **
  104258. ** The author disclaims copyright to this source code. In place of
  104259. ** a legal notice, here is a blessing:
  104260. **
  104261. ** May you do good and not evil.
  104262. ** May you find forgiveness for yourself and forgive others.
  104263. ** May you share freely, never taking more than you give.
  104264. **
  104265. ******************************************************************************
  104266. **
  104267. */
  104268. #ifndef _FTSINT_H
  104269. #define _FTSINT_H
  104270. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  104271. # define NDEBUG 1
  104272. #endif
  104273. /*
  104274. ** FTS4 is really an extension for FTS3. It is enabled using the
  104275. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  104276. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  104277. */
  104278. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  104279. # define SQLITE_ENABLE_FTS3
  104280. #endif
  104281. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  104282. /* If not building as part of the core, include sqlite3ext.h. */
  104283. #ifndef SQLITE_CORE
  104284. SQLITE_EXTENSION_INIT3
  104285. #endif
  104286. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  104287. /************** Begin file fts3_tokenizer.h **********************************/
  104288. /*
  104289. ** 2006 July 10
  104290. **
  104291. ** The author disclaims copyright to this source code.
  104292. **
  104293. *************************************************************************
  104294. ** Defines the interface to tokenizers used by fulltext-search. There
  104295. ** are three basic components:
  104296. **
  104297. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  104298. ** interface functions. This is essentially the class structure for
  104299. ** tokenizers.
  104300. **
  104301. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  104302. ** including customization information defined at creation time.
  104303. **
  104304. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  104305. ** tokens from a particular input.
  104306. */
  104307. #ifndef _FTS3_TOKENIZER_H_
  104308. #define _FTS3_TOKENIZER_H_
  104309. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  104310. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  104311. ** we will need a way to register the API consistently.
  104312. */
  104313. /*
  104314. ** Structures used by the tokenizer interface. When a new tokenizer
  104315. ** implementation is registered, the caller provides a pointer to
  104316. ** an sqlite3_tokenizer_module containing pointers to the callback
  104317. ** functions that make up an implementation.
  104318. **
  104319. ** When an fts3 table is created, it passes any arguments passed to
  104320. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  104321. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  104322. ** implementation. The xCreate() function in turn returns an
  104323. ** sqlite3_tokenizer structure representing the specific tokenizer to
  104324. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  104325. **
  104326. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  104327. ** method is called. It returns an sqlite3_tokenizer_cursor object
  104328. ** that may be used to tokenize a specific input buffer based on
  104329. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  104330. ** object.
  104331. */
  104332. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  104333. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  104334. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  104335. struct sqlite3_tokenizer_module {
  104336. /*
  104337. ** Structure version. Should always be set to 0 or 1.
  104338. */
  104339. int iVersion;
  104340. /*
  104341. ** Create a new tokenizer. The values in the argv[] array are the
  104342. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  104343. ** TABLE statement that created the fts3 table. For example, if
  104344. ** the following SQL is executed:
  104345. **
  104346. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  104347. **
  104348. ** then argc is set to 2, and the argv[] array contains pointers
  104349. ** to the strings "arg1" and "arg2".
  104350. **
  104351. ** This method should return either SQLITE_OK (0), or an SQLite error
  104352. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  104353. ** to point at the newly created tokenizer structure. The generic
  104354. ** sqlite3_tokenizer.pModule variable should not be initialized by
  104355. ** this callback. The caller will do so.
  104356. */
  104357. int (*xCreate)(
  104358. int argc, /* Size of argv array */
  104359. const char *const*argv, /* Tokenizer argument strings */
  104360. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  104361. );
  104362. /*
  104363. ** Destroy an existing tokenizer. The fts3 module calls this method
  104364. ** exactly once for each successful call to xCreate().
  104365. */
  104366. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  104367. /*
  104368. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  104369. ** is responsible for ensuring that the input buffer remains valid
  104370. ** until the cursor is closed (using the xClose() method).
  104371. */
  104372. int (*xOpen)(
  104373. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  104374. const char *pInput, int nBytes, /* Input buffer */
  104375. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  104376. );
  104377. /*
  104378. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  104379. ** method exactly once for each successful call to xOpen().
  104380. */
  104381. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  104382. /*
  104383. ** Retrieve the next token from the tokenizer cursor pCursor. This
  104384. ** method should either return SQLITE_OK and set the values of the
  104385. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  104386. ** the end of the buffer has been reached, or an SQLite error code.
  104387. **
  104388. ** *ppToken should be set to point at a buffer containing the
  104389. ** normalized version of the token (i.e. after any case-folding and/or
  104390. ** stemming has been performed). *pnBytes should be set to the length
  104391. ** of this buffer in bytes. The input text that generated the token is
  104392. ** identified by the byte offsets returned in *piStartOffset and
  104393. ** *piEndOffset. *piStartOffset should be set to the index of the first
  104394. ** byte of the token in the input buffer. *piEndOffset should be set
  104395. ** to the index of the first byte just past the end of the token in
  104396. ** the input buffer.
  104397. **
  104398. ** The buffer *ppToken is set to point at is managed by the tokenizer
  104399. ** implementation. It is only required to be valid until the next call
  104400. ** to xNext() or xClose().
  104401. */
  104402. /* TODO(shess) current implementation requires pInput to be
  104403. ** nul-terminated. This should either be fixed, or pInput/nBytes
  104404. ** should be converted to zInput.
  104405. */
  104406. int (*xNext)(
  104407. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  104408. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  104409. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  104410. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  104411. int *piPosition /* OUT: Number of tokens returned before this one */
  104412. );
  104413. /***********************************************************************
  104414. ** Methods below this point are only available if iVersion>=1.
  104415. */
  104416. /*
  104417. ** Configure the language id of a tokenizer cursor.
  104418. */
  104419. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  104420. };
  104421. struct sqlite3_tokenizer {
  104422. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  104423. /* Tokenizer implementations will typically add additional fields */
  104424. };
  104425. struct sqlite3_tokenizer_cursor {
  104426. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  104427. /* Tokenizer implementations will typically add additional fields */
  104428. };
  104429. int fts3_global_term_cnt(int iTerm, int iCol);
  104430. int fts3_term_cnt(int iTerm, int iCol);
  104431. #endif /* _FTS3_TOKENIZER_H_ */
  104432. /************** End of fts3_tokenizer.h **************************************/
  104433. /************** Continuing where we left off in fts3Int.h ********************/
  104434. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  104435. /************** Begin file fts3_hash.h ***************************************/
  104436. /*
  104437. ** 2001 September 22
  104438. **
  104439. ** The author disclaims copyright to this source code. In place of
  104440. ** a legal notice, here is a blessing:
  104441. **
  104442. ** May you do good and not evil.
  104443. ** May you find forgiveness for yourself and forgive others.
  104444. ** May you share freely, never taking more than you give.
  104445. **
  104446. *************************************************************************
  104447. ** This is the header file for the generic hash-table implementation
  104448. ** used in SQLite. We've modified it slightly to serve as a standalone
  104449. ** hash table implementation for the full-text indexing module.
  104450. **
  104451. */
  104452. #ifndef _FTS3_HASH_H_
  104453. #define _FTS3_HASH_H_
  104454. /* Forward declarations of structures. */
  104455. typedef struct Fts3Hash Fts3Hash;
  104456. typedef struct Fts3HashElem Fts3HashElem;
  104457. /* A complete hash table is an instance of the following structure.
  104458. ** The internals of this structure are intended to be opaque -- client
  104459. ** code should not attempt to access or modify the fields of this structure
  104460. ** directly. Change this structure only by using the routines below.
  104461. ** However, many of the "procedures" and "functions" for modifying and
  104462. ** accessing this structure are really macros, so we can't really make
  104463. ** this structure opaque.
  104464. */
  104465. struct Fts3Hash {
  104466. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  104467. char copyKey; /* True if copy of key made on insert */
  104468. int count; /* Number of entries in this table */
  104469. Fts3HashElem *first; /* The first element of the array */
  104470. int htsize; /* Number of buckets in the hash table */
  104471. struct _fts3ht { /* the hash table */
  104472. int count; /* Number of entries with this hash */
  104473. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  104474. } *ht;
  104475. };
  104476. /* Each element in the hash table is an instance of the following
  104477. ** structure. All elements are stored on a single doubly-linked list.
  104478. **
  104479. ** Again, this structure is intended to be opaque, but it can't really
  104480. ** be opaque because it is used by macros.
  104481. */
  104482. struct Fts3HashElem {
  104483. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  104484. void *data; /* Data associated with this element */
  104485. void *pKey; int nKey; /* Key associated with this element */
  104486. };
  104487. /*
  104488. ** There are 2 different modes of operation for a hash table:
  104489. **
  104490. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  104491. ** (including the null-terminator, if any). Case
  104492. ** is respected in comparisons.
  104493. **
  104494. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  104495. ** memcmp() is used to compare keys.
  104496. **
  104497. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  104498. */
  104499. #define FTS3_HASH_STRING 1
  104500. #define FTS3_HASH_BINARY 2
  104501. /*
  104502. ** Access routines. To delete, insert a NULL pointer.
  104503. */
  104504. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  104505. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  104506. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  104507. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  104508. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  104509. /*
  104510. ** Shorthand for the functions above
  104511. */
  104512. #define fts3HashInit sqlite3Fts3HashInit
  104513. #define fts3HashInsert sqlite3Fts3HashInsert
  104514. #define fts3HashFind sqlite3Fts3HashFind
  104515. #define fts3HashClear sqlite3Fts3HashClear
  104516. #define fts3HashFindElem sqlite3Fts3HashFindElem
  104517. /*
  104518. ** Macros for looping over all elements of a hash table. The idiom is
  104519. ** like this:
  104520. **
  104521. ** Fts3Hash h;
  104522. ** Fts3HashElem *p;
  104523. ** ...
  104524. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  104525. ** SomeStructure *pData = fts3HashData(p);
  104526. ** // do something with pData
  104527. ** }
  104528. */
  104529. #define fts3HashFirst(H) ((H)->first)
  104530. #define fts3HashNext(E) ((E)->next)
  104531. #define fts3HashData(E) ((E)->data)
  104532. #define fts3HashKey(E) ((E)->pKey)
  104533. #define fts3HashKeysize(E) ((E)->nKey)
  104534. /*
  104535. ** Number of entries in a hash table
  104536. */
  104537. #define fts3HashCount(H) ((H)->count)
  104538. #endif /* _FTS3_HASH_H_ */
  104539. /************** End of fts3_hash.h *******************************************/
  104540. /************** Continuing where we left off in fts3Int.h ********************/
  104541. /*
  104542. ** This constant determines the maximum depth of an FTS expression tree
  104543. ** that the library will create and use. FTS uses recursion to perform
  104544. ** various operations on the query tree, so the disadvantage of a large
  104545. ** limit is that it may allow very large queries to use large amounts
  104546. ** of stack space (perhaps causing a stack overflow).
  104547. */
  104548. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  104549. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  104550. #endif
  104551. /*
  104552. ** This constant controls how often segments are merged. Once there are
  104553. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  104554. ** segment of level N+1.
  104555. */
  104556. #define FTS3_MERGE_COUNT 16
  104557. /*
  104558. ** This is the maximum amount of data (in bytes) to store in the
  104559. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  104560. ** populated as documents are inserted/updated/deleted in a transaction
  104561. ** and used to create a new segment when the transaction is committed.
  104562. ** However if this limit is reached midway through a transaction, a new
  104563. ** segment is created and the hash table cleared immediately.
  104564. */
  104565. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  104566. /*
  104567. ** Macro to return the number of elements in an array. SQLite has a
  104568. ** similar macro called ArraySize(). Use a different name to avoid
  104569. ** a collision when building an amalgamation with built-in FTS3.
  104570. */
  104571. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  104572. #ifndef MIN
  104573. # define MIN(x,y) ((x)<(y)?(x):(y))
  104574. #endif
  104575. #ifndef MAX
  104576. # define MAX(x,y) ((x)>(y)?(x):(y))
  104577. #endif
  104578. /*
  104579. ** Maximum length of a varint encoded integer. The varint format is different
  104580. ** from that used by SQLite, so the maximum length is 10, not 9.
  104581. */
  104582. #define FTS3_VARINT_MAX 10
  104583. /*
  104584. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  104585. ** in the document set and zero or more prefix indexes. All indexes are stored
  104586. ** as one or more b+-trees in the %_segments and %_segdir tables.
  104587. **
  104588. ** It is possible to determine which index a b+-tree belongs to based on the
  104589. ** value stored in the "%_segdir.level" column. Given this value L, the index
  104590. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  104591. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  104592. ** between 1024 and 2047 to index 1, and so on.
  104593. **
  104594. ** It is considered impossible for an index to use more than 1024 levels. In
  104595. ** theory though this may happen, but only after at least
  104596. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  104597. */
  104598. #define FTS3_SEGDIR_MAXLEVEL 1024
  104599. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  104600. /*
  104601. ** The testcase() macro is only used by the amalgamation. If undefined,
  104602. ** make it a no-op.
  104603. */
  104604. #ifndef testcase
  104605. # define testcase(X)
  104606. #endif
  104607. /*
  104608. ** Terminator values for position-lists and column-lists.
  104609. */
  104610. #define POS_COLUMN (1) /* Column-list terminator */
  104611. #define POS_END (0) /* Position-list terminator */
  104612. /*
  104613. ** This section provides definitions to allow the
  104614. ** FTS3 extension to be compiled outside of the
  104615. ** amalgamation.
  104616. */
  104617. #ifndef SQLITE_AMALGAMATION
  104618. /*
  104619. ** Macros indicating that conditional expressions are always true or
  104620. ** false.
  104621. */
  104622. #ifdef SQLITE_COVERAGE_TEST
  104623. # define ALWAYS(x) (1)
  104624. # define NEVER(X) (0)
  104625. #else
  104626. # define ALWAYS(x) (x)
  104627. # define NEVER(x) (x)
  104628. #endif
  104629. /*
  104630. ** Internal types used by SQLite.
  104631. */
  104632. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  104633. typedef short int i16; /* 2-byte (or larger) signed integer */
  104634. typedef unsigned int u32; /* 4-byte unsigned integer */
  104635. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  104636. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  104637. /*
  104638. ** Macro used to suppress compiler warnings for unused parameters.
  104639. */
  104640. #define UNUSED_PARAMETER(x) (void)(x)
  104641. /*
  104642. ** Activate assert() only if SQLITE_TEST is enabled.
  104643. */
  104644. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  104645. # define NDEBUG 1
  104646. #endif
  104647. /*
  104648. ** The TESTONLY macro is used to enclose variable declarations or
  104649. ** other bits of code that are needed to support the arguments
  104650. ** within testcase() and assert() macros.
  104651. */
  104652. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  104653. # define TESTONLY(X) X
  104654. #else
  104655. # define TESTONLY(X)
  104656. #endif
  104657. #endif /* SQLITE_AMALGAMATION */
  104658. #ifdef SQLITE_DEBUG
  104659. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  104660. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  104661. #else
  104662. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  104663. #endif
  104664. typedef struct Fts3Table Fts3Table;
  104665. typedef struct Fts3Cursor Fts3Cursor;
  104666. typedef struct Fts3Expr Fts3Expr;
  104667. typedef struct Fts3Phrase Fts3Phrase;
  104668. typedef struct Fts3PhraseToken Fts3PhraseToken;
  104669. typedef struct Fts3Doclist Fts3Doclist;
  104670. typedef struct Fts3SegFilter Fts3SegFilter;
  104671. typedef struct Fts3DeferredToken Fts3DeferredToken;
  104672. typedef struct Fts3SegReader Fts3SegReader;
  104673. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  104674. /*
  104675. ** A connection to a fulltext index is an instance of the following
  104676. ** structure. The xCreate and xConnect methods create an instance
  104677. ** of this structure and xDestroy and xDisconnect free that instance.
  104678. ** All other methods receive a pointer to the structure as one of their
  104679. ** arguments.
  104680. */
  104681. struct Fts3Table {
  104682. sqlite3_vtab base; /* Base class used by SQLite core */
  104683. sqlite3 *db; /* The database connection */
  104684. const char *zDb; /* logical database name */
  104685. const char *zName; /* virtual table name */
  104686. int nColumn; /* number of named columns in virtual table */
  104687. char **azColumn; /* column names. malloced */
  104688. u8 *abNotindexed; /* True for 'notindexed' columns */
  104689. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  104690. char *zContentTbl; /* content=xxx option, or NULL */
  104691. char *zLanguageid; /* languageid=xxx option, or NULL */
  104692. u8 bAutoincrmerge; /* True if automerge=1 */
  104693. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  104694. /* Precompiled statements used by the implementation. Each of these
  104695. ** statements is run and reset within a single virtual table API call.
  104696. */
  104697. sqlite3_stmt *aStmt[37];
  104698. char *zReadExprlist;
  104699. char *zWriteExprlist;
  104700. int nNodeSize; /* Soft limit for node size */
  104701. u8 bFts4; /* True for FTS4, false for FTS3 */
  104702. u8 bHasStat; /* True if %_stat table exists */
  104703. u8 bHasDocsize; /* True if %_docsize table exists */
  104704. u8 bDescIdx; /* True if doclists are in reverse order */
  104705. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  104706. int nPgsz; /* Page size for host database */
  104707. char *zSegmentsTbl; /* Name of %_segments table */
  104708. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  104709. /*
  104710. ** The following array of hash tables is used to buffer pending index
  104711. ** updates during transactions. All pending updates buffered at any one
  104712. ** time must share a common language-id (see the FTS4 langid= feature).
  104713. ** The current language id is stored in variable iPrevLangid.
  104714. **
  104715. ** A single FTS4 table may have multiple full-text indexes. For each index
  104716. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  104717. ** terms that appear in the document set. Each subsequent index in aIndex[]
  104718. ** is an index of prefixes of a specific length.
  104719. **
  104720. ** Variable nPendingData contains an estimate the memory consumed by the
  104721. ** pending data structures, including hash table overhead, but not including
  104722. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  104723. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  104724. ** recently inserted record.
  104725. */
  104726. int nIndex; /* Size of aIndex[] */
  104727. struct Fts3Index {
  104728. int nPrefix; /* Prefix length (0 for main terms index) */
  104729. Fts3Hash hPending; /* Pending terms table for this index */
  104730. } *aIndex;
  104731. int nMaxPendingData; /* Max pending data before flush to disk */
  104732. int nPendingData; /* Current bytes of pending data */
  104733. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  104734. int iPrevLangid; /* Langid of recently inserted document */
  104735. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  104736. /* State variables used for validating that the transaction control
  104737. ** methods of the virtual table are called at appropriate times. These
  104738. ** values do not contribute to FTS functionality; they are used for
  104739. ** verifying the operation of the SQLite core.
  104740. */
  104741. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  104742. int mxSavepoint; /* Largest valid xSavepoint integer */
  104743. #endif
  104744. #ifdef SQLITE_TEST
  104745. /* True to disable the incremental doclist optimization. This is controled
  104746. ** by special insert command 'test-no-incr-doclist'. */
  104747. int bNoIncrDoclist;
  104748. #endif
  104749. };
  104750. /*
  104751. ** When the core wants to read from the virtual table, it creates a
  104752. ** virtual table cursor (an instance of the following structure) using
  104753. ** the xOpen method. Cursors are destroyed using the xClose method.
  104754. */
  104755. struct Fts3Cursor {
  104756. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  104757. i16 eSearch; /* Search strategy (see below) */
  104758. u8 isEof; /* True if at End Of Results */
  104759. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  104760. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  104761. Fts3Expr *pExpr; /* Parsed MATCH query string */
  104762. int iLangid; /* Language being queried for */
  104763. int nPhrase; /* Number of matchable phrases in query */
  104764. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  104765. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  104766. char *pNextId; /* Pointer into the body of aDoclist */
  104767. char *aDoclist; /* List of docids for full-text queries */
  104768. int nDoclist; /* Size of buffer at aDoclist */
  104769. u8 bDesc; /* True to sort in descending order */
  104770. int eEvalmode; /* An FTS3_EVAL_XX constant */
  104771. int nRowAvg; /* Average size of database rows, in pages */
  104772. sqlite3_int64 nDoc; /* Documents in table */
  104773. i64 iMinDocid; /* Minimum docid to return */
  104774. i64 iMaxDocid; /* Maximum docid to return */
  104775. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  104776. u32 *aMatchinfo; /* Information about most recent match */
  104777. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  104778. char *zMatchinfo; /* Matchinfo specification */
  104779. };
  104780. #define FTS3_EVAL_FILTER 0
  104781. #define FTS3_EVAL_NEXT 1
  104782. #define FTS3_EVAL_MATCHINFO 2
  104783. /*
  104784. ** The Fts3Cursor.eSearch member is always set to one of the following.
  104785. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  104786. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  104787. ** of the column to be searched. For example, in
  104788. **
  104789. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  104790. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  104791. **
  104792. ** Because the LHS of the MATCH operator is 2nd column "b",
  104793. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  104794. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  104795. ** indicating that all columns should be searched,
  104796. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  104797. */
  104798. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  104799. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  104800. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  104801. /*
  104802. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  104803. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  104804. ** above. The upper 16-bits contain a combination of the following
  104805. ** bits, used to describe extra constraints on full-text searches.
  104806. */
  104807. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  104808. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  104809. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  104810. struct Fts3Doclist {
  104811. char *aAll; /* Array containing doclist (or NULL) */
  104812. int nAll; /* Size of a[] in bytes */
  104813. char *pNextDocid; /* Pointer to next docid */
  104814. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  104815. int bFreeList; /* True if pList should be sqlite3_free()d */
  104816. char *pList; /* Pointer to position list following iDocid */
  104817. int nList; /* Length of position list */
  104818. };
  104819. /*
  104820. ** A "phrase" is a sequence of one or more tokens that must match in
  104821. ** sequence. A single token is the base case and the most common case.
  104822. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  104823. ** nToken will be the number of tokens in the string.
  104824. */
  104825. struct Fts3PhraseToken {
  104826. char *z; /* Text of the token */
  104827. int n; /* Number of bytes in buffer z */
  104828. int isPrefix; /* True if token ends with a "*" character */
  104829. int bFirst; /* True if token must appear at position 0 */
  104830. /* Variables above this point are populated when the expression is
  104831. ** parsed (by code in fts3_expr.c). Below this point the variables are
  104832. ** used when evaluating the expression. */
  104833. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  104834. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  104835. };
  104836. struct Fts3Phrase {
  104837. /* Cache of doclist for this phrase. */
  104838. Fts3Doclist doclist;
  104839. int bIncr; /* True if doclist is loaded incrementally */
  104840. int iDoclistToken;
  104841. /* Variables below this point are populated by fts3_expr.c when parsing
  104842. ** a MATCH expression. Everything above is part of the evaluation phase.
  104843. */
  104844. int nToken; /* Number of tokens in the phrase */
  104845. int iColumn; /* Index of column this phrase must match */
  104846. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  104847. };
  104848. /*
  104849. ** A tree of these objects forms the RHS of a MATCH operator.
  104850. **
  104851. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  104852. ** points to a malloced buffer, size nDoclist bytes, containing the results
  104853. ** of this phrase query in FTS3 doclist format. As usual, the initial
  104854. ** "Length" field found in doclists stored on disk is omitted from this
  104855. ** buffer.
  104856. **
  104857. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  104858. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  104859. ** where nCol is the number of columns in the queried FTS table. The array
  104860. ** is populated as follows:
  104861. **
  104862. ** aMI[iCol*3 + 0] = Undefined
  104863. ** aMI[iCol*3 + 1] = Number of occurrences
  104864. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  104865. **
  104866. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  104867. ** when the expression node is.
  104868. */
  104869. struct Fts3Expr {
  104870. int eType; /* One of the FTSQUERY_XXX values defined below */
  104871. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  104872. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  104873. Fts3Expr *pLeft; /* Left operand */
  104874. Fts3Expr *pRight; /* Right operand */
  104875. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  104876. /* The following are used by the fts3_eval.c module. */
  104877. sqlite3_int64 iDocid; /* Current docid */
  104878. u8 bEof; /* True this expression is at EOF already */
  104879. u8 bStart; /* True if iDocid is valid */
  104880. u8 bDeferred; /* True if this expression is entirely deferred */
  104881. u32 *aMI;
  104882. };
  104883. /*
  104884. ** Candidate values for Fts3Query.eType. Note that the order of the first
  104885. ** four values is in order of precedence when parsing expressions. For
  104886. ** example, the following:
  104887. **
  104888. ** "a OR b AND c NOT d NEAR e"
  104889. **
  104890. ** is equivalent to:
  104891. **
  104892. ** "a OR (b AND (c NOT (d NEAR e)))"
  104893. */
  104894. #define FTSQUERY_NEAR 1
  104895. #define FTSQUERY_NOT 2
  104896. #define FTSQUERY_AND 3
  104897. #define FTSQUERY_OR 4
  104898. #define FTSQUERY_PHRASE 5
  104899. /* fts3_write.c */
  104900. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  104901. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  104902. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  104903. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  104904. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  104905. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  104906. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  104907. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  104908. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  104909. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  104910. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  104911. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  104912. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  104913. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  104914. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  104915. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  104916. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  104917. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  104918. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  104919. #else
  104920. # define sqlite3Fts3FreeDeferredTokens(x)
  104921. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  104922. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  104923. # define sqlite3Fts3FreeDeferredDoclists(x)
  104924. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  104925. #endif
  104926. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  104927. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  104928. /* Special values interpreted by sqlite3SegReaderCursor() */
  104929. #define FTS3_SEGCURSOR_PENDING -1
  104930. #define FTS3_SEGCURSOR_ALL -2
  104931. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  104932. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  104933. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  104934. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  104935. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  104936. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  104937. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  104938. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  104939. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  104940. #define FTS3_SEGMENT_PREFIX 0x00000008
  104941. #define FTS3_SEGMENT_SCAN 0x00000010
  104942. #define FTS3_SEGMENT_FIRST 0x00000020
  104943. /* Type passed as 4th argument to SegmentReaderIterate() */
  104944. struct Fts3SegFilter {
  104945. const char *zTerm;
  104946. int nTerm;
  104947. int iCol;
  104948. int flags;
  104949. };
  104950. struct Fts3MultiSegReader {
  104951. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  104952. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  104953. int nSegment; /* Size of apSegment array */
  104954. int nAdvance; /* How many seg-readers to advance */
  104955. Fts3SegFilter *pFilter; /* Pointer to filter object */
  104956. char *aBuffer; /* Buffer to merge doclists in */
  104957. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  104958. int iColFilter; /* If >=0, filter for this column */
  104959. int bRestart;
  104960. /* Used by fts3.c only. */
  104961. int nCost; /* Cost of running iterator */
  104962. int bLookup; /* True if a lookup of a single entry. */
  104963. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  104964. char *zTerm; /* Pointer to term buffer */
  104965. int nTerm; /* Size of zTerm in bytes */
  104966. char *aDoclist; /* Pointer to doclist buffer */
  104967. int nDoclist; /* Size of aDoclist[] in bytes */
  104968. };
  104969. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  104970. /* fts3.c */
  104971. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  104972. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  104973. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  104974. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  104975. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  104976. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  104977. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  104978. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  104979. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  104980. /* fts3_tokenizer.c */
  104981. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  104982. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  104983. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  104984. sqlite3_tokenizer **, char **
  104985. );
  104986. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  104987. /* fts3_snippet.c */
  104988. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  104989. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  104990. const char *, const char *, int, int
  104991. );
  104992. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  104993. /* fts3_expr.c */
  104994. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  104995. char **, int, int, int, const char *, int, Fts3Expr **, char **
  104996. );
  104997. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  104998. #ifdef SQLITE_TEST
  104999. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  105000. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  105001. #endif
  105002. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  105003. sqlite3_tokenizer_cursor **
  105004. );
  105005. /* fts3_aux.c */
  105006. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  105007. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  105008. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  105009. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  105010. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  105011. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  105012. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  105013. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  105014. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  105015. /* fts3_tokenize_vtab.c */
  105016. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  105017. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  105018. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  105019. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  105020. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  105021. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  105022. #endif
  105023. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  105024. #endif /* _FTSINT_H */
  105025. /************** End of fts3Int.h *********************************************/
  105026. /************** Continuing where we left off in fts3.c ***********************/
  105027. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  105028. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  105029. # define SQLITE_CORE 1
  105030. #endif
  105031. /* #include <assert.h> */
  105032. /* #include <stdlib.h> */
  105033. /* #include <stddef.h> */
  105034. /* #include <stdio.h> */
  105035. /* #include <string.h> */
  105036. /* #include <stdarg.h> */
  105037. #ifndef SQLITE_CORE
  105038. SQLITE_EXTENSION_INIT1
  105039. #endif
  105040. static int fts3EvalNext(Fts3Cursor *pCsr);
  105041. static int fts3EvalStart(Fts3Cursor *pCsr);
  105042. static int fts3TermSegReaderCursor(
  105043. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  105044. /*
  105045. ** Write a 64-bit variable-length integer to memory starting at p[0].
  105046. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  105047. ** The number of bytes written is returned.
  105048. */
  105049. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  105050. unsigned char *q = (unsigned char *) p;
  105051. sqlite_uint64 vu = v;
  105052. do{
  105053. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  105054. vu >>= 7;
  105055. }while( vu!=0 );
  105056. q[-1] &= 0x7f; /* turn off high bit in final byte */
  105057. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  105058. return (int) (q - (unsigned char *)p);
  105059. }
  105060. /*
  105061. ** Read a 64-bit variable-length integer from memory starting at p[0].
  105062. ** Return the number of bytes read, or 0 on error.
  105063. ** The value is stored in *v.
  105064. */
  105065. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  105066. const unsigned char *q = (const unsigned char *) p;
  105067. sqlite_uint64 x = 0, y = 1;
  105068. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  105069. x += y * (*q++ & 0x7f);
  105070. y <<= 7;
  105071. }
  105072. x += y * (*q++);
  105073. *v = (sqlite_int64) x;
  105074. return (int) (q - (unsigned char *)p);
  105075. }
  105076. /*
  105077. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  105078. ** 32-bit integer before it is returned.
  105079. */
  105080. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  105081. sqlite_int64 i;
  105082. int ret = sqlite3Fts3GetVarint(p, &i);
  105083. *pi = (int) i;
  105084. return ret;
  105085. }
  105086. /*
  105087. ** Return the number of bytes required to encode v as a varint
  105088. */
  105089. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  105090. int i = 0;
  105091. do{
  105092. i++;
  105093. v >>= 7;
  105094. }while( v!=0 );
  105095. return i;
  105096. }
  105097. /*
  105098. ** Convert an SQL-style quoted string into a normal string by removing
  105099. ** the quote characters. The conversion is done in-place. If the
  105100. ** input does not begin with a quote character, then this routine
  105101. ** is a no-op.
  105102. **
  105103. ** Examples:
  105104. **
  105105. ** "abc" becomes abc
  105106. ** 'xyz' becomes xyz
  105107. ** [pqr] becomes pqr
  105108. ** `mno` becomes mno
  105109. **
  105110. */
  105111. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  105112. char quote; /* Quote character (if any ) */
  105113. quote = z[0];
  105114. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  105115. int iIn = 1; /* Index of next byte to read from input */
  105116. int iOut = 0; /* Index of next byte to write to output */
  105117. /* If the first byte was a '[', then the close-quote character is a ']' */
  105118. if( quote=='[' ) quote = ']';
  105119. while( ALWAYS(z[iIn]) ){
  105120. if( z[iIn]==quote ){
  105121. if( z[iIn+1]!=quote ) break;
  105122. z[iOut++] = quote;
  105123. iIn += 2;
  105124. }else{
  105125. z[iOut++] = z[iIn++];
  105126. }
  105127. }
  105128. z[iOut] = '\0';
  105129. }
  105130. }
  105131. /*
  105132. ** Read a single varint from the doclist at *pp and advance *pp to point
  105133. ** to the first byte past the end of the varint. Add the value of the varint
  105134. ** to *pVal.
  105135. */
  105136. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  105137. sqlite3_int64 iVal;
  105138. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  105139. *pVal += iVal;
  105140. }
  105141. /*
  105142. ** When this function is called, *pp points to the first byte following a
  105143. ** varint that is part of a doclist (or position-list, or any other list
  105144. ** of varints). This function moves *pp to point to the start of that varint,
  105145. ** and sets *pVal by the varint value.
  105146. **
  105147. ** Argument pStart points to the first byte of the doclist that the
  105148. ** varint is part of.
  105149. */
  105150. static void fts3GetReverseVarint(
  105151. char **pp,
  105152. char *pStart,
  105153. sqlite3_int64 *pVal
  105154. ){
  105155. sqlite3_int64 iVal;
  105156. char *p;
  105157. /* Pointer p now points at the first byte past the varint we are
  105158. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  105159. ** clear on character p[-1]. */
  105160. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  105161. p++;
  105162. *pp = p;
  105163. sqlite3Fts3GetVarint(p, &iVal);
  105164. *pVal = iVal;
  105165. }
  105166. /*
  105167. ** The xDisconnect() virtual table method.
  105168. */
  105169. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  105170. Fts3Table *p = (Fts3Table *)pVtab;
  105171. int i;
  105172. assert( p->nPendingData==0 );
  105173. assert( p->pSegments==0 );
  105174. /* Free any prepared statements held */
  105175. for(i=0; i<SizeofArray(p->aStmt); i++){
  105176. sqlite3_finalize(p->aStmt[i]);
  105177. }
  105178. sqlite3_free(p->zSegmentsTbl);
  105179. sqlite3_free(p->zReadExprlist);
  105180. sqlite3_free(p->zWriteExprlist);
  105181. sqlite3_free(p->zContentTbl);
  105182. sqlite3_free(p->zLanguageid);
  105183. /* Invoke the tokenizer destructor to free the tokenizer. */
  105184. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  105185. sqlite3_free(p);
  105186. return SQLITE_OK;
  105187. }
  105188. /*
  105189. ** Construct one or more SQL statements from the format string given
  105190. ** and then evaluate those statements. The success code is written
  105191. ** into *pRc.
  105192. **
  105193. ** If *pRc is initially non-zero then this routine is a no-op.
  105194. */
  105195. static void fts3DbExec(
  105196. int *pRc, /* Success code */
  105197. sqlite3 *db, /* Database in which to run SQL */
  105198. const char *zFormat, /* Format string for SQL */
  105199. ... /* Arguments to the format string */
  105200. ){
  105201. va_list ap;
  105202. char *zSql;
  105203. if( *pRc ) return;
  105204. va_start(ap, zFormat);
  105205. zSql = sqlite3_vmprintf(zFormat, ap);
  105206. va_end(ap);
  105207. if( zSql==0 ){
  105208. *pRc = SQLITE_NOMEM;
  105209. }else{
  105210. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  105211. sqlite3_free(zSql);
  105212. }
  105213. }
  105214. /*
  105215. ** The xDestroy() virtual table method.
  105216. */
  105217. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  105218. Fts3Table *p = (Fts3Table *)pVtab;
  105219. int rc = SQLITE_OK; /* Return code */
  105220. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  105221. sqlite3 *db = p->db; /* Database handle */
  105222. /* Drop the shadow tables */
  105223. if( p->zContentTbl==0 ){
  105224. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  105225. }
  105226. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  105227. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  105228. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  105229. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  105230. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  105231. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  105232. ** Otherwise, return an SQLite error code.
  105233. */
  105234. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  105235. }
  105236. /*
  105237. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  105238. ** passed as the first argument. This is done as part of the xConnect()
  105239. ** and xCreate() methods.
  105240. **
  105241. ** If *pRc is non-zero when this function is called, it is a no-op.
  105242. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  105243. ** before returning.
  105244. */
  105245. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  105246. if( *pRc==SQLITE_OK ){
  105247. int i; /* Iterator variable */
  105248. int rc; /* Return code */
  105249. char *zSql; /* SQL statement passed to declare_vtab() */
  105250. char *zCols; /* List of user defined columns */
  105251. const char *zLanguageid;
  105252. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  105253. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  105254. /* Create a list of user columns for the virtual table */
  105255. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  105256. for(i=1; zCols && i<p->nColumn; i++){
  105257. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  105258. }
  105259. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  105260. zSql = sqlite3_mprintf(
  105261. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  105262. zCols, p->zName, zLanguageid
  105263. );
  105264. if( !zCols || !zSql ){
  105265. rc = SQLITE_NOMEM;
  105266. }else{
  105267. rc = sqlite3_declare_vtab(p->db, zSql);
  105268. }
  105269. sqlite3_free(zSql);
  105270. sqlite3_free(zCols);
  105271. *pRc = rc;
  105272. }
  105273. }
  105274. /*
  105275. ** Create the %_stat table if it does not already exist.
  105276. */
  105277. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  105278. fts3DbExec(pRc, p->db,
  105279. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  105280. "(id INTEGER PRIMARY KEY, value BLOB);",
  105281. p->zDb, p->zName
  105282. );
  105283. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  105284. }
  105285. /*
  105286. ** Create the backing store tables (%_content, %_segments and %_segdir)
  105287. ** required by the FTS3 table passed as the only argument. This is done
  105288. ** as part of the vtab xCreate() method.
  105289. **
  105290. ** If the p->bHasDocsize boolean is true (indicating that this is an
  105291. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  105292. ** %_stat tables required by FTS4.
  105293. */
  105294. static int fts3CreateTables(Fts3Table *p){
  105295. int rc = SQLITE_OK; /* Return code */
  105296. int i; /* Iterator variable */
  105297. sqlite3 *db = p->db; /* The database connection */
  105298. if( p->zContentTbl==0 ){
  105299. const char *zLanguageid = p->zLanguageid;
  105300. char *zContentCols; /* Columns of %_content table */
  105301. /* Create a list of user columns for the content table */
  105302. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  105303. for(i=0; zContentCols && i<p->nColumn; i++){
  105304. char *z = p->azColumn[i];
  105305. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  105306. }
  105307. if( zLanguageid && zContentCols ){
  105308. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  105309. }
  105310. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  105311. /* Create the content table */
  105312. fts3DbExec(&rc, db,
  105313. "CREATE TABLE %Q.'%q_content'(%s)",
  105314. p->zDb, p->zName, zContentCols
  105315. );
  105316. sqlite3_free(zContentCols);
  105317. }
  105318. /* Create other tables */
  105319. fts3DbExec(&rc, db,
  105320. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  105321. p->zDb, p->zName
  105322. );
  105323. fts3DbExec(&rc, db,
  105324. "CREATE TABLE %Q.'%q_segdir'("
  105325. "level INTEGER,"
  105326. "idx INTEGER,"
  105327. "start_block INTEGER,"
  105328. "leaves_end_block INTEGER,"
  105329. "end_block INTEGER,"
  105330. "root BLOB,"
  105331. "PRIMARY KEY(level, idx)"
  105332. ");",
  105333. p->zDb, p->zName
  105334. );
  105335. if( p->bHasDocsize ){
  105336. fts3DbExec(&rc, db,
  105337. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  105338. p->zDb, p->zName
  105339. );
  105340. }
  105341. assert( p->bHasStat==p->bFts4 );
  105342. if( p->bHasStat ){
  105343. sqlite3Fts3CreateStatTable(&rc, p);
  105344. }
  105345. return rc;
  105346. }
  105347. /*
  105348. ** Store the current database page-size in bytes in p->nPgsz.
  105349. **
  105350. ** If *pRc is non-zero when this function is called, it is a no-op.
  105351. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  105352. ** before returning.
  105353. */
  105354. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  105355. if( *pRc==SQLITE_OK ){
  105356. int rc; /* Return code */
  105357. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  105358. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  105359. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  105360. if( !zSql ){
  105361. rc = SQLITE_NOMEM;
  105362. }else{
  105363. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  105364. if( rc==SQLITE_OK ){
  105365. sqlite3_step(pStmt);
  105366. p->nPgsz = sqlite3_column_int(pStmt, 0);
  105367. rc = sqlite3_finalize(pStmt);
  105368. }else if( rc==SQLITE_AUTH ){
  105369. p->nPgsz = 1024;
  105370. rc = SQLITE_OK;
  105371. }
  105372. }
  105373. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  105374. sqlite3_free(zSql);
  105375. *pRc = rc;
  105376. }
  105377. }
  105378. /*
  105379. ** "Special" FTS4 arguments are column specifications of the following form:
  105380. **
  105381. ** <key> = <value>
  105382. **
  105383. ** There may not be whitespace surrounding the "=" character. The <value>
  105384. ** term may be quoted, but the <key> may not.
  105385. */
  105386. static int fts3IsSpecialColumn(
  105387. const char *z,
  105388. int *pnKey,
  105389. char **pzValue
  105390. ){
  105391. char *zValue;
  105392. const char *zCsr = z;
  105393. while( *zCsr!='=' ){
  105394. if( *zCsr=='\0' ) return 0;
  105395. zCsr++;
  105396. }
  105397. *pnKey = (int)(zCsr-z);
  105398. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  105399. if( zValue ){
  105400. sqlite3Fts3Dequote(zValue);
  105401. }
  105402. *pzValue = zValue;
  105403. return 1;
  105404. }
  105405. /*
  105406. ** Append the output of a printf() style formatting to an existing string.
  105407. */
  105408. static void fts3Appendf(
  105409. int *pRc, /* IN/OUT: Error code */
  105410. char **pz, /* IN/OUT: Pointer to string buffer */
  105411. const char *zFormat, /* Printf format string to append */
  105412. ... /* Arguments for printf format string */
  105413. ){
  105414. if( *pRc==SQLITE_OK ){
  105415. va_list ap;
  105416. char *z;
  105417. va_start(ap, zFormat);
  105418. z = sqlite3_vmprintf(zFormat, ap);
  105419. va_end(ap);
  105420. if( z && *pz ){
  105421. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  105422. sqlite3_free(z);
  105423. z = z2;
  105424. }
  105425. if( z==0 ) *pRc = SQLITE_NOMEM;
  105426. sqlite3_free(*pz);
  105427. *pz = z;
  105428. }
  105429. }
  105430. /*
  105431. ** Return a copy of input string zInput enclosed in double-quotes (") and
  105432. ** with all double quote characters escaped. For example:
  105433. **
  105434. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  105435. **
  105436. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  105437. ** is the callers responsibility to call sqlite3_free() to release this
  105438. ** memory.
  105439. */
  105440. static char *fts3QuoteId(char const *zInput){
  105441. int nRet;
  105442. char *zRet;
  105443. nRet = 2 + (int)strlen(zInput)*2 + 1;
  105444. zRet = sqlite3_malloc(nRet);
  105445. if( zRet ){
  105446. int i;
  105447. char *z = zRet;
  105448. *(z++) = '"';
  105449. for(i=0; zInput[i]; i++){
  105450. if( zInput[i]=='"' ) *(z++) = '"';
  105451. *(z++) = zInput[i];
  105452. }
  105453. *(z++) = '"';
  105454. *(z++) = '\0';
  105455. }
  105456. return zRet;
  105457. }
  105458. /*
  105459. ** Return a list of comma separated SQL expressions and a FROM clause that
  105460. ** could be used in a SELECT statement such as the following:
  105461. **
  105462. ** SELECT <list of expressions> FROM %_content AS x ...
  105463. **
  105464. ** to return the docid, followed by each column of text data in order
  105465. ** from left to write. If parameter zFunc is not NULL, then instead of
  105466. ** being returned directly each column of text data is passed to an SQL
  105467. ** function named zFunc first. For example, if zFunc is "unzip" and the
  105468. ** table has the three user-defined columns "a", "b", and "c", the following
  105469. ** string is returned:
  105470. **
  105471. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  105472. **
  105473. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  105474. ** is the responsibility of the caller to eventually free it.
  105475. **
  105476. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  105477. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  105478. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  105479. ** no error occurs, *pRc is left unmodified.
  105480. */
  105481. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  105482. char *zRet = 0;
  105483. char *zFree = 0;
  105484. char *zFunction;
  105485. int i;
  105486. if( p->zContentTbl==0 ){
  105487. if( !zFunc ){
  105488. zFunction = "";
  105489. }else{
  105490. zFree = zFunction = fts3QuoteId(zFunc);
  105491. }
  105492. fts3Appendf(pRc, &zRet, "docid");
  105493. for(i=0; i<p->nColumn; i++){
  105494. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  105495. }
  105496. if( p->zLanguageid ){
  105497. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  105498. }
  105499. sqlite3_free(zFree);
  105500. }else{
  105501. fts3Appendf(pRc, &zRet, "rowid");
  105502. for(i=0; i<p->nColumn; i++){
  105503. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  105504. }
  105505. if( p->zLanguageid ){
  105506. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  105507. }
  105508. }
  105509. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  105510. p->zDb,
  105511. (p->zContentTbl ? p->zContentTbl : p->zName),
  105512. (p->zContentTbl ? "" : "_content")
  105513. );
  105514. return zRet;
  105515. }
  105516. /*
  105517. ** Return a list of N comma separated question marks, where N is the number
  105518. ** of columns in the %_content table (one for the docid plus one for each
  105519. ** user-defined text column).
  105520. **
  105521. ** If argument zFunc is not NULL, then all but the first question mark
  105522. ** is preceded by zFunc and an open bracket, and followed by a closed
  105523. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  105524. ** user-defined text columns, the following string is returned:
  105525. **
  105526. ** "?, zip(?), zip(?), zip(?)"
  105527. **
  105528. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  105529. ** is the responsibility of the caller to eventually free it.
  105530. **
  105531. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  105532. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  105533. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  105534. ** no error occurs, *pRc is left unmodified.
  105535. */
  105536. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  105537. char *zRet = 0;
  105538. char *zFree = 0;
  105539. char *zFunction;
  105540. int i;
  105541. if( !zFunc ){
  105542. zFunction = "";
  105543. }else{
  105544. zFree = zFunction = fts3QuoteId(zFunc);
  105545. }
  105546. fts3Appendf(pRc, &zRet, "?");
  105547. for(i=0; i<p->nColumn; i++){
  105548. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  105549. }
  105550. if( p->zLanguageid ){
  105551. fts3Appendf(pRc, &zRet, ", ?");
  105552. }
  105553. sqlite3_free(zFree);
  105554. return zRet;
  105555. }
  105556. /*
  105557. ** This function interprets the string at (*pp) as a non-negative integer
  105558. ** value. It reads the integer and sets *pnOut to the value read, then
  105559. ** sets *pp to point to the byte immediately following the last byte of
  105560. ** the integer value.
  105561. **
  105562. ** Only decimal digits ('0'..'9') may be part of an integer value.
  105563. **
  105564. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  105565. ** the output value undefined. Otherwise SQLITE_OK is returned.
  105566. **
  105567. ** This function is used when parsing the "prefix=" FTS4 parameter.
  105568. */
  105569. static int fts3GobbleInt(const char **pp, int *pnOut){
  105570. const char *p; /* Iterator pointer */
  105571. int nInt = 0; /* Output value */
  105572. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  105573. nInt = nInt * 10 + (p[0] - '0');
  105574. }
  105575. if( p==*pp ) return SQLITE_ERROR;
  105576. *pnOut = nInt;
  105577. *pp = p;
  105578. return SQLITE_OK;
  105579. }
  105580. /*
  105581. ** This function is called to allocate an array of Fts3Index structures
  105582. ** representing the indexes maintained by the current FTS table. FTS tables
  105583. ** always maintain the main "terms" index, but may also maintain one or
  105584. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  105585. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  105586. **
  105587. ** Argument zParam is passed the value of the "prefix=" option if one was
  105588. ** specified, or NULL otherwise.
  105589. **
  105590. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  105591. ** the allocated array. *pnIndex is set to the number of elements in the
  105592. ** array. If an error does occur, an SQLite error code is returned.
  105593. **
  105594. ** Regardless of whether or not an error is returned, it is the responsibility
  105595. ** of the caller to call sqlite3_free() on the output array to free it.
  105596. */
  105597. static int fts3PrefixParameter(
  105598. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  105599. int *pnIndex, /* OUT: size of *apIndex[] array */
  105600. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  105601. ){
  105602. struct Fts3Index *aIndex; /* Allocated array */
  105603. int nIndex = 1; /* Number of entries in array */
  105604. if( zParam && zParam[0] ){
  105605. const char *p;
  105606. nIndex++;
  105607. for(p=zParam; *p; p++){
  105608. if( *p==',' ) nIndex++;
  105609. }
  105610. }
  105611. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  105612. *apIndex = aIndex;
  105613. *pnIndex = nIndex;
  105614. if( !aIndex ){
  105615. return SQLITE_NOMEM;
  105616. }
  105617. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  105618. if( zParam ){
  105619. const char *p = zParam;
  105620. int i;
  105621. for(i=1; i<nIndex; i++){
  105622. int nPrefix;
  105623. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  105624. aIndex[i].nPrefix = nPrefix;
  105625. p++;
  105626. }
  105627. }
  105628. return SQLITE_OK;
  105629. }
  105630. /*
  105631. ** This function is called when initializing an FTS4 table that uses the
  105632. ** content=xxx option. It determines the number of and names of the columns
  105633. ** of the new FTS4 table.
  105634. **
  105635. ** The third argument passed to this function is the value passed to the
  105636. ** config=xxx option (i.e. "xxx"). This function queries the database for
  105637. ** a table of that name. If found, the output variables are populated
  105638. ** as follows:
  105639. **
  105640. ** *pnCol: Set to the number of columns table xxx has,
  105641. **
  105642. ** *pnStr: Set to the total amount of space required to store a copy
  105643. ** of each columns name, including the nul-terminator.
  105644. **
  105645. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  105646. ** the name of the corresponding column in table xxx. The array
  105647. ** and its contents are allocated using a single allocation. It
  105648. ** is the responsibility of the caller to free this allocation
  105649. ** by eventually passing the *pazCol value to sqlite3_free().
  105650. **
  105651. ** If the table cannot be found, an error code is returned and the output
  105652. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  105653. ** returned (and the output variables are undefined).
  105654. */
  105655. static int fts3ContentColumns(
  105656. sqlite3 *db, /* Database handle */
  105657. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  105658. const char *zTbl, /* Name of content table */
  105659. const char ***pazCol, /* OUT: Malloc'd array of column names */
  105660. int *pnCol, /* OUT: Size of array *pazCol */
  105661. int *pnStr /* OUT: Bytes of string content */
  105662. ){
  105663. int rc = SQLITE_OK; /* Return code */
  105664. char *zSql; /* "SELECT *" statement on zTbl */
  105665. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  105666. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  105667. if( !zSql ){
  105668. rc = SQLITE_NOMEM;
  105669. }else{
  105670. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  105671. }
  105672. sqlite3_free(zSql);
  105673. if( rc==SQLITE_OK ){
  105674. const char **azCol; /* Output array */
  105675. int nStr = 0; /* Size of all column names (incl. 0x00) */
  105676. int nCol; /* Number of table columns */
  105677. int i; /* Used to iterate through columns */
  105678. /* Loop through the returned columns. Set nStr to the number of bytes of
  105679. ** space required to store a copy of each column name, including the
  105680. ** nul-terminator byte. */
  105681. nCol = sqlite3_column_count(pStmt);
  105682. for(i=0; i<nCol; i++){
  105683. const char *zCol = sqlite3_column_name(pStmt, i);
  105684. nStr += (int)strlen(zCol) + 1;
  105685. }
  105686. /* Allocate and populate the array to return. */
  105687. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  105688. if( azCol==0 ){
  105689. rc = SQLITE_NOMEM;
  105690. }else{
  105691. char *p = (char *)&azCol[nCol];
  105692. for(i=0; i<nCol; i++){
  105693. const char *zCol = sqlite3_column_name(pStmt, i);
  105694. int n = (int)strlen(zCol)+1;
  105695. memcpy(p, zCol, n);
  105696. azCol[i] = p;
  105697. p += n;
  105698. }
  105699. }
  105700. sqlite3_finalize(pStmt);
  105701. /* Set the output variables. */
  105702. *pnCol = nCol;
  105703. *pnStr = nStr;
  105704. *pazCol = azCol;
  105705. }
  105706. return rc;
  105707. }
  105708. /*
  105709. ** This function is the implementation of both the xConnect and xCreate
  105710. ** methods of the FTS3 virtual table.
  105711. **
  105712. ** The argv[] array contains the following:
  105713. **
  105714. ** argv[0] -> module name ("fts3" or "fts4")
  105715. ** argv[1] -> database name
  105716. ** argv[2] -> table name
  105717. ** argv[...] -> "column name" and other module argument fields.
  105718. */
  105719. static int fts3InitVtab(
  105720. int isCreate, /* True for xCreate, false for xConnect */
  105721. sqlite3 *db, /* The SQLite database connection */
  105722. void *pAux, /* Hash table containing tokenizers */
  105723. int argc, /* Number of elements in argv array */
  105724. const char * const *argv, /* xCreate/xConnect argument array */
  105725. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  105726. char **pzErr /* Write any error message here */
  105727. ){
  105728. Fts3Hash *pHash = (Fts3Hash *)pAux;
  105729. Fts3Table *p = 0; /* Pointer to allocated vtab */
  105730. int rc = SQLITE_OK; /* Return code */
  105731. int i; /* Iterator variable */
  105732. int nByte; /* Size of allocation used for *p */
  105733. int iCol; /* Column index */
  105734. int nString = 0; /* Bytes required to hold all column names */
  105735. int nCol = 0; /* Number of columns in the FTS table */
  105736. char *zCsr; /* Space for holding column names */
  105737. int nDb; /* Bytes required to hold database name */
  105738. int nName; /* Bytes required to hold table name */
  105739. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  105740. const char **aCol; /* Array of column names */
  105741. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  105742. int nIndex; /* Size of aIndex[] array */
  105743. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  105744. /* The results of parsing supported FTS4 key=value options: */
  105745. int bNoDocsize = 0; /* True to omit %_docsize table */
  105746. int bDescIdx = 0; /* True to store descending indexes */
  105747. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  105748. char *zCompress = 0; /* compress=? parameter (or NULL) */
  105749. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  105750. char *zContent = 0; /* content=? parameter (or NULL) */
  105751. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  105752. char **azNotindexed = 0; /* The set of notindexed= columns */
  105753. int nNotindexed = 0; /* Size of azNotindexed[] array */
  105754. assert( strlen(argv[0])==4 );
  105755. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  105756. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  105757. );
  105758. nDb = (int)strlen(argv[1]) + 1;
  105759. nName = (int)strlen(argv[2]) + 1;
  105760. nByte = sizeof(const char *) * (argc-2);
  105761. aCol = (const char **)sqlite3_malloc(nByte);
  105762. if( aCol ){
  105763. memset((void*)aCol, 0, nByte);
  105764. azNotindexed = (char **)sqlite3_malloc(nByte);
  105765. }
  105766. if( azNotindexed ){
  105767. memset(azNotindexed, 0, nByte);
  105768. }
  105769. if( !aCol || !azNotindexed ){
  105770. rc = SQLITE_NOMEM;
  105771. goto fts3_init_out;
  105772. }
  105773. /* Loop through all of the arguments passed by the user to the FTS3/4
  105774. ** module (i.e. all the column names and special arguments). This loop
  105775. ** does the following:
  105776. **
  105777. ** + Figures out the number of columns the FTSX table will have, and
  105778. ** the number of bytes of space that must be allocated to store copies
  105779. ** of the column names.
  105780. **
  105781. ** + If there is a tokenizer specification included in the arguments,
  105782. ** initializes the tokenizer pTokenizer.
  105783. */
  105784. for(i=3; rc==SQLITE_OK && i<argc; i++){
  105785. char const *z = argv[i];
  105786. int nKey;
  105787. char *zVal;
  105788. /* Check if this is a tokenizer specification */
  105789. if( !pTokenizer
  105790. && strlen(z)>8
  105791. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  105792. && 0==sqlite3Fts3IsIdChar(z[8])
  105793. ){
  105794. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  105795. }
  105796. /* Check if it is an FTS4 special argument. */
  105797. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  105798. struct Fts4Option {
  105799. const char *zOpt;
  105800. int nOpt;
  105801. } aFts4Opt[] = {
  105802. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  105803. { "prefix", 6 }, /* 1 -> PREFIX */
  105804. { "compress", 8 }, /* 2 -> COMPRESS */
  105805. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  105806. { "order", 5 }, /* 4 -> ORDER */
  105807. { "content", 7 }, /* 5 -> CONTENT */
  105808. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  105809. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  105810. };
  105811. int iOpt;
  105812. if( !zVal ){
  105813. rc = SQLITE_NOMEM;
  105814. }else{
  105815. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  105816. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  105817. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  105818. break;
  105819. }
  105820. }
  105821. if( iOpt==SizeofArray(aFts4Opt) ){
  105822. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  105823. rc = SQLITE_ERROR;
  105824. }else{
  105825. switch( iOpt ){
  105826. case 0: /* MATCHINFO */
  105827. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  105828. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  105829. rc = SQLITE_ERROR;
  105830. }
  105831. bNoDocsize = 1;
  105832. break;
  105833. case 1: /* PREFIX */
  105834. sqlite3_free(zPrefix);
  105835. zPrefix = zVal;
  105836. zVal = 0;
  105837. break;
  105838. case 2: /* COMPRESS */
  105839. sqlite3_free(zCompress);
  105840. zCompress = zVal;
  105841. zVal = 0;
  105842. break;
  105843. case 3: /* UNCOMPRESS */
  105844. sqlite3_free(zUncompress);
  105845. zUncompress = zVal;
  105846. zVal = 0;
  105847. break;
  105848. case 4: /* ORDER */
  105849. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  105850. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  105851. ){
  105852. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  105853. rc = SQLITE_ERROR;
  105854. }
  105855. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  105856. break;
  105857. case 5: /* CONTENT */
  105858. sqlite3_free(zContent);
  105859. zContent = zVal;
  105860. zVal = 0;
  105861. break;
  105862. case 6: /* LANGUAGEID */
  105863. assert( iOpt==6 );
  105864. sqlite3_free(zLanguageid);
  105865. zLanguageid = zVal;
  105866. zVal = 0;
  105867. break;
  105868. case 7: /* NOTINDEXED */
  105869. azNotindexed[nNotindexed++] = zVal;
  105870. zVal = 0;
  105871. break;
  105872. }
  105873. }
  105874. sqlite3_free(zVal);
  105875. }
  105876. }
  105877. /* Otherwise, the argument is a column name. */
  105878. else {
  105879. nString += (int)(strlen(z) + 1);
  105880. aCol[nCol++] = z;
  105881. }
  105882. }
  105883. /* If a content=xxx option was specified, the following:
  105884. **
  105885. ** 1. Ignore any compress= and uncompress= options.
  105886. **
  105887. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  105888. ** TABLE statement, use all columns from the content table.
  105889. */
  105890. if( rc==SQLITE_OK && zContent ){
  105891. sqlite3_free(zCompress);
  105892. sqlite3_free(zUncompress);
  105893. zCompress = 0;
  105894. zUncompress = 0;
  105895. if( nCol==0 ){
  105896. sqlite3_free((void*)aCol);
  105897. aCol = 0;
  105898. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  105899. /* If a languageid= option was specified, remove the language id
  105900. ** column from the aCol[] array. */
  105901. if( rc==SQLITE_OK && zLanguageid ){
  105902. int j;
  105903. for(j=0; j<nCol; j++){
  105904. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  105905. int k;
  105906. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  105907. nCol--;
  105908. break;
  105909. }
  105910. }
  105911. }
  105912. }
  105913. }
  105914. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105915. if( nCol==0 ){
  105916. assert( nString==0 );
  105917. aCol[0] = "content";
  105918. nString = 8;
  105919. nCol = 1;
  105920. }
  105921. if( pTokenizer==0 ){
  105922. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  105923. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105924. }
  105925. assert( pTokenizer );
  105926. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  105927. if( rc==SQLITE_ERROR ){
  105928. assert( zPrefix );
  105929. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  105930. }
  105931. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105932. /* Allocate and populate the Fts3Table structure. */
  105933. nByte = sizeof(Fts3Table) + /* Fts3Table */
  105934. nCol * sizeof(char *) + /* azColumn */
  105935. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  105936. nCol * sizeof(u8) + /* abNotindexed */
  105937. nName + /* zName */
  105938. nDb + /* zDb */
  105939. nString; /* Space for azColumn strings */
  105940. p = (Fts3Table*)sqlite3_malloc(nByte);
  105941. if( p==0 ){
  105942. rc = SQLITE_NOMEM;
  105943. goto fts3_init_out;
  105944. }
  105945. memset(p, 0, nByte);
  105946. p->db = db;
  105947. p->nColumn = nCol;
  105948. p->nPendingData = 0;
  105949. p->azColumn = (char **)&p[1];
  105950. p->pTokenizer = pTokenizer;
  105951. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  105952. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  105953. p->bHasStat = isFts4;
  105954. p->bFts4 = isFts4;
  105955. p->bDescIdx = bDescIdx;
  105956. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  105957. p->zContentTbl = zContent;
  105958. p->zLanguageid = zLanguageid;
  105959. zContent = 0;
  105960. zLanguageid = 0;
  105961. TESTONLY( p->inTransaction = -1 );
  105962. TESTONLY( p->mxSavepoint = -1 );
  105963. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  105964. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  105965. p->nIndex = nIndex;
  105966. for(i=0; i<nIndex; i++){
  105967. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  105968. }
  105969. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  105970. /* Fill in the zName and zDb fields of the vtab structure. */
  105971. zCsr = (char *)&p->abNotindexed[nCol];
  105972. p->zName = zCsr;
  105973. memcpy(zCsr, argv[2], nName);
  105974. zCsr += nName;
  105975. p->zDb = zCsr;
  105976. memcpy(zCsr, argv[1], nDb);
  105977. zCsr += nDb;
  105978. /* Fill in the azColumn array */
  105979. for(iCol=0; iCol<nCol; iCol++){
  105980. char *z;
  105981. int n = 0;
  105982. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  105983. memcpy(zCsr, z, n);
  105984. zCsr[n] = '\0';
  105985. sqlite3Fts3Dequote(zCsr);
  105986. p->azColumn[iCol] = zCsr;
  105987. zCsr += n+1;
  105988. assert( zCsr <= &((char *)p)[nByte] );
  105989. }
  105990. /* Fill in the abNotindexed array */
  105991. for(iCol=0; iCol<nCol; iCol++){
  105992. int n = (int)strlen(p->azColumn[iCol]);
  105993. for(i=0; i<nNotindexed; i++){
  105994. char *zNot = azNotindexed[i];
  105995. if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
  105996. p->abNotindexed[iCol] = 1;
  105997. sqlite3_free(zNot);
  105998. azNotindexed[i] = 0;
  105999. }
  106000. }
  106001. }
  106002. for(i=0; i<nNotindexed; i++){
  106003. if( azNotindexed[i] ){
  106004. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  106005. rc = SQLITE_ERROR;
  106006. }
  106007. }
  106008. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  106009. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  106010. rc = SQLITE_ERROR;
  106011. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  106012. }
  106013. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  106014. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  106015. if( rc!=SQLITE_OK ) goto fts3_init_out;
  106016. /* If this is an xCreate call, create the underlying tables in the
  106017. ** database. TODO: For xConnect(), it could verify that said tables exist.
  106018. */
  106019. if( isCreate ){
  106020. rc = fts3CreateTables(p);
  106021. }
  106022. /* Check to see if a legacy fts3 table has been "upgraded" by the
  106023. ** addition of a %_stat table so that it can use incremental merge.
  106024. */
  106025. if( !isFts4 && !isCreate ){
  106026. int rc2 = SQLITE_OK;
  106027. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  106028. p->zDb, p->zName);
  106029. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  106030. }
  106031. /* Figure out the page-size for the database. This is required in order to
  106032. ** estimate the cost of loading large doclists from the database. */
  106033. fts3DatabasePageSize(&rc, p);
  106034. p->nNodeSize = p->nPgsz-35;
  106035. /* Declare the table schema to SQLite. */
  106036. fts3DeclareVtab(&rc, p);
  106037. fts3_init_out:
  106038. sqlite3_free(zPrefix);
  106039. sqlite3_free(aIndex);
  106040. sqlite3_free(zCompress);
  106041. sqlite3_free(zUncompress);
  106042. sqlite3_free(zContent);
  106043. sqlite3_free(zLanguageid);
  106044. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  106045. sqlite3_free((void *)aCol);
  106046. sqlite3_free((void *)azNotindexed);
  106047. if( rc!=SQLITE_OK ){
  106048. if( p ){
  106049. fts3DisconnectMethod((sqlite3_vtab *)p);
  106050. }else if( pTokenizer ){
  106051. pTokenizer->pModule->xDestroy(pTokenizer);
  106052. }
  106053. }else{
  106054. assert( p->pSegments==0 );
  106055. *ppVTab = &p->base;
  106056. }
  106057. return rc;
  106058. }
  106059. /*
  106060. ** The xConnect() and xCreate() methods for the virtual table. All the
  106061. ** work is done in function fts3InitVtab().
  106062. */
  106063. static int fts3ConnectMethod(
  106064. sqlite3 *db, /* Database connection */
  106065. void *pAux, /* Pointer to tokenizer hash table */
  106066. int argc, /* Number of elements in argv array */
  106067. const char * const *argv, /* xCreate/xConnect argument array */
  106068. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  106069. char **pzErr /* OUT: sqlite3_malloc'd error message */
  106070. ){
  106071. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  106072. }
  106073. static int fts3CreateMethod(
  106074. sqlite3 *db, /* Database connection */
  106075. void *pAux, /* Pointer to tokenizer hash table */
  106076. int argc, /* Number of elements in argv array */
  106077. const char * const *argv, /* xCreate/xConnect argument array */
  106078. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  106079. char **pzErr /* OUT: sqlite3_malloc'd error message */
  106080. ){
  106081. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  106082. }
  106083. /*
  106084. ** Implementation of the xBestIndex method for FTS3 tables. There
  106085. ** are three possible strategies, in order of preference:
  106086. **
  106087. ** 1. Direct lookup by rowid or docid.
  106088. ** 2. Full-text search using a MATCH operator on a non-docid column.
  106089. ** 3. Linear scan of %_content table.
  106090. */
  106091. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  106092. Fts3Table *p = (Fts3Table *)pVTab;
  106093. int i; /* Iterator variable */
  106094. int iCons = -1; /* Index of constraint to use */
  106095. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  106096. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  106097. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  106098. int iIdx;
  106099. /* By default use a full table scan. This is an expensive option,
  106100. ** so search through the constraints to see if a more efficient
  106101. ** strategy is possible.
  106102. */
  106103. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  106104. pInfo->estimatedCost = 5000000;
  106105. for(i=0; i<pInfo->nConstraint; i++){
  106106. int bDocid; /* True if this constraint is on docid */
  106107. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  106108. if( pCons->usable==0 ) continue;
  106109. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  106110. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  106111. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  106112. pInfo->idxNum = FTS3_DOCID_SEARCH;
  106113. pInfo->estimatedCost = 1.0;
  106114. iCons = i;
  106115. }
  106116. /* A MATCH constraint. Use a full-text search.
  106117. **
  106118. ** If there is more than one MATCH constraint available, use the first
  106119. ** one encountered. If there is both a MATCH constraint and a direct
  106120. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  106121. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  106122. ** it would lead to an "unable to use function MATCH in the requested
  106123. ** context" error.
  106124. */
  106125. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  106126. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  106127. ){
  106128. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  106129. pInfo->estimatedCost = 2.0;
  106130. iCons = i;
  106131. }
  106132. /* Equality constraint on the langid column */
  106133. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  106134. && pCons->iColumn==p->nColumn + 2
  106135. ){
  106136. iLangidCons = i;
  106137. }
  106138. if( bDocid ){
  106139. switch( pCons->op ){
  106140. case SQLITE_INDEX_CONSTRAINT_GE:
  106141. case SQLITE_INDEX_CONSTRAINT_GT:
  106142. iDocidGe = i;
  106143. break;
  106144. case SQLITE_INDEX_CONSTRAINT_LE:
  106145. case SQLITE_INDEX_CONSTRAINT_LT:
  106146. iDocidLe = i;
  106147. break;
  106148. }
  106149. }
  106150. }
  106151. iIdx = 1;
  106152. if( iCons>=0 ){
  106153. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  106154. pInfo->aConstraintUsage[iCons].omit = 1;
  106155. }
  106156. if( iLangidCons>=0 ){
  106157. pInfo->idxNum |= FTS3_HAVE_LANGID;
  106158. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  106159. }
  106160. if( iDocidGe>=0 ){
  106161. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  106162. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  106163. }
  106164. if( iDocidLe>=0 ){
  106165. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  106166. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  106167. }
  106168. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  106169. ** docid) order. Both ascending and descending are possible.
  106170. */
  106171. if( pInfo->nOrderBy==1 ){
  106172. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  106173. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  106174. if( pOrder->desc ){
  106175. pInfo->idxStr = "DESC";
  106176. }else{
  106177. pInfo->idxStr = "ASC";
  106178. }
  106179. pInfo->orderByConsumed = 1;
  106180. }
  106181. }
  106182. assert( p->pSegments==0 );
  106183. return SQLITE_OK;
  106184. }
  106185. /*
  106186. ** Implementation of xOpen method.
  106187. */
  106188. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  106189. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  106190. UNUSED_PARAMETER(pVTab);
  106191. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  106192. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  106193. ** if the allocation fails, return SQLITE_NOMEM.
  106194. */
  106195. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  106196. if( !pCsr ){
  106197. return SQLITE_NOMEM;
  106198. }
  106199. memset(pCsr, 0, sizeof(Fts3Cursor));
  106200. return SQLITE_OK;
  106201. }
  106202. /*
  106203. ** Close the cursor. For additional information see the documentation
  106204. ** on the xClose method of the virtual table interface.
  106205. */
  106206. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  106207. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  106208. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  106209. sqlite3_finalize(pCsr->pStmt);
  106210. sqlite3Fts3ExprFree(pCsr->pExpr);
  106211. sqlite3Fts3FreeDeferredTokens(pCsr);
  106212. sqlite3_free(pCsr->aDoclist);
  106213. sqlite3_free(pCsr->aMatchinfo);
  106214. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  106215. sqlite3_free(pCsr);
  106216. return SQLITE_OK;
  106217. }
  106218. /*
  106219. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  106220. ** compose and prepare an SQL statement of the form:
  106221. **
  106222. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  106223. **
  106224. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  106225. ** it. If an error occurs, return an SQLite error code.
  106226. **
  106227. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  106228. */
  106229. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  106230. int rc = SQLITE_OK;
  106231. if( pCsr->pStmt==0 ){
  106232. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  106233. char *zSql;
  106234. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  106235. if( !zSql ) return SQLITE_NOMEM;
  106236. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  106237. sqlite3_free(zSql);
  106238. }
  106239. *ppStmt = pCsr->pStmt;
  106240. return rc;
  106241. }
  106242. /*
  106243. ** Position the pCsr->pStmt statement so that it is on the row
  106244. ** of the %_content table that contains the last match. Return
  106245. ** SQLITE_OK on success.
  106246. */
  106247. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  106248. int rc = SQLITE_OK;
  106249. if( pCsr->isRequireSeek ){
  106250. sqlite3_stmt *pStmt = 0;
  106251. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  106252. if( rc==SQLITE_OK ){
  106253. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  106254. pCsr->isRequireSeek = 0;
  106255. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  106256. return SQLITE_OK;
  106257. }else{
  106258. rc = sqlite3_reset(pCsr->pStmt);
  106259. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  106260. /* If no row was found and no error has occurred, then the %_content
  106261. ** table is missing a row that is present in the full-text index.
  106262. ** The data structures are corrupt. */
  106263. rc = FTS_CORRUPT_VTAB;
  106264. pCsr->isEof = 1;
  106265. }
  106266. }
  106267. }
  106268. }
  106269. if( rc!=SQLITE_OK && pContext ){
  106270. sqlite3_result_error_code(pContext, rc);
  106271. }
  106272. return rc;
  106273. }
  106274. /*
  106275. ** This function is used to process a single interior node when searching
  106276. ** a b-tree for a term or term prefix. The node data is passed to this
  106277. ** function via the zNode/nNode parameters. The term to search for is
  106278. ** passed in zTerm/nTerm.
  106279. **
  106280. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  106281. ** of the child node that heads the sub-tree that may contain the term.
  106282. **
  106283. ** If piLast is not NULL, then *piLast is set to the right-most child node
  106284. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  106285. ** a prefix.
  106286. **
  106287. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  106288. */
  106289. static int fts3ScanInteriorNode(
  106290. const char *zTerm, /* Term to select leaves for */
  106291. int nTerm, /* Size of term zTerm in bytes */
  106292. const char *zNode, /* Buffer containing segment interior node */
  106293. int nNode, /* Size of buffer at zNode */
  106294. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  106295. sqlite3_int64 *piLast /* OUT: Selected child node */
  106296. ){
  106297. int rc = SQLITE_OK; /* Return code */
  106298. const char *zCsr = zNode; /* Cursor to iterate through node */
  106299. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  106300. char *zBuffer = 0; /* Buffer to load terms into */
  106301. int nAlloc = 0; /* Size of allocated buffer */
  106302. int isFirstTerm = 1; /* True when processing first term on page */
  106303. sqlite3_int64 iChild; /* Block id of child node to descend to */
  106304. /* Skip over the 'height' varint that occurs at the start of every
  106305. ** interior node. Then load the blockid of the left-child of the b-tree
  106306. ** node into variable iChild.
  106307. **
  106308. ** Even if the data structure on disk is corrupted, this (reading two
  106309. ** varints from the buffer) does not risk an overread. If zNode is a
  106310. ** root node, then the buffer comes from a SELECT statement. SQLite does
  106311. ** not make this guarantee explicitly, but in practice there are always
  106312. ** either more than 20 bytes of allocated space following the nNode bytes of
  106313. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  106314. ** table, then there are always 20 bytes of zeroed padding following the
  106315. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  106316. */
  106317. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  106318. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  106319. if( zCsr>zEnd ){
  106320. return FTS_CORRUPT_VTAB;
  106321. }
  106322. while( zCsr<zEnd && (piFirst || piLast) ){
  106323. int cmp; /* memcmp() result */
  106324. int nSuffix; /* Size of term suffix */
  106325. int nPrefix = 0; /* Size of term prefix */
  106326. int nBuffer; /* Total term size */
  106327. /* Load the next term on the node into zBuffer. Use realloc() to expand
  106328. ** the size of zBuffer if required. */
  106329. if( !isFirstTerm ){
  106330. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  106331. }
  106332. isFirstTerm = 0;
  106333. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  106334. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  106335. rc = FTS_CORRUPT_VTAB;
  106336. goto finish_scan;
  106337. }
  106338. if( nPrefix+nSuffix>nAlloc ){
  106339. char *zNew;
  106340. nAlloc = (nPrefix+nSuffix) * 2;
  106341. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  106342. if( !zNew ){
  106343. rc = SQLITE_NOMEM;
  106344. goto finish_scan;
  106345. }
  106346. zBuffer = zNew;
  106347. }
  106348. assert( zBuffer );
  106349. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  106350. nBuffer = nPrefix + nSuffix;
  106351. zCsr += nSuffix;
  106352. /* Compare the term we are searching for with the term just loaded from
  106353. ** the interior node. If the specified term is greater than or equal
  106354. ** to the term from the interior node, then all terms on the sub-tree
  106355. ** headed by node iChild are smaller than zTerm. No need to search
  106356. ** iChild.
  106357. **
  106358. ** If the interior node term is larger than the specified term, then
  106359. ** the tree headed by iChild may contain the specified term.
  106360. */
  106361. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  106362. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  106363. *piFirst = iChild;
  106364. piFirst = 0;
  106365. }
  106366. if( piLast && cmp<0 ){
  106367. *piLast = iChild;
  106368. piLast = 0;
  106369. }
  106370. iChild++;
  106371. };
  106372. if( piFirst ) *piFirst = iChild;
  106373. if( piLast ) *piLast = iChild;
  106374. finish_scan:
  106375. sqlite3_free(zBuffer);
  106376. return rc;
  106377. }
  106378. /*
  106379. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  106380. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  106381. ** contains a term. This function searches the sub-tree headed by the zNode
  106382. ** node for the range of leaf nodes that may contain the specified term
  106383. ** or terms for which the specified term is a prefix.
  106384. **
  106385. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  106386. ** left-most leaf node in the tree that may contain the specified term.
  106387. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  106388. ** right-most leaf node that may contain a term for which the specified
  106389. ** term is a prefix.
  106390. **
  106391. ** It is possible that the range of returned leaf nodes does not contain
  106392. ** the specified term or any terms for which it is a prefix. However, if the
  106393. ** segment does contain any such terms, they are stored within the identified
  106394. ** range. Because this function only inspects interior segment nodes (and
  106395. ** never loads leaf nodes into memory), it is not possible to be sure.
  106396. **
  106397. ** If an error occurs, an error code other than SQLITE_OK is returned.
  106398. */
  106399. static int fts3SelectLeaf(
  106400. Fts3Table *p, /* Virtual table handle */
  106401. const char *zTerm, /* Term to select leaves for */
  106402. int nTerm, /* Size of term zTerm in bytes */
  106403. const char *zNode, /* Buffer containing segment interior node */
  106404. int nNode, /* Size of buffer at zNode */
  106405. sqlite3_int64 *piLeaf, /* Selected leaf node */
  106406. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  106407. ){
  106408. int rc; /* Return code */
  106409. int iHeight; /* Height of this node in tree */
  106410. assert( piLeaf || piLeaf2 );
  106411. sqlite3Fts3GetVarint32(zNode, &iHeight);
  106412. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  106413. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  106414. if( rc==SQLITE_OK && iHeight>1 ){
  106415. char *zBlob = 0; /* Blob read from %_segments table */
  106416. int nBlob; /* Size of zBlob in bytes */
  106417. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  106418. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  106419. if( rc==SQLITE_OK ){
  106420. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  106421. }
  106422. sqlite3_free(zBlob);
  106423. piLeaf = 0;
  106424. zBlob = 0;
  106425. }
  106426. if( rc==SQLITE_OK ){
  106427. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  106428. }
  106429. if( rc==SQLITE_OK ){
  106430. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  106431. }
  106432. sqlite3_free(zBlob);
  106433. }
  106434. return rc;
  106435. }
  106436. /*
  106437. ** This function is used to create delta-encoded serialized lists of FTS3
  106438. ** varints. Each call to this function appends a single varint to a list.
  106439. */
  106440. static void fts3PutDeltaVarint(
  106441. char **pp, /* IN/OUT: Output pointer */
  106442. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  106443. sqlite3_int64 iVal /* Write this value to the list */
  106444. ){
  106445. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  106446. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  106447. *piPrev = iVal;
  106448. }
  106449. /*
  106450. ** When this function is called, *ppPoslist is assumed to point to the
  106451. ** start of a position-list. After it returns, *ppPoslist points to the
  106452. ** first byte after the position-list.
  106453. **
  106454. ** A position list is list of positions (delta encoded) and columns for
  106455. ** a single document record of a doclist. So, in other words, this
  106456. ** routine advances *ppPoslist so that it points to the next docid in
  106457. ** the doclist, or to the first byte past the end of the doclist.
  106458. **
  106459. ** If pp is not NULL, then the contents of the position list are copied
  106460. ** to *pp. *pp is set to point to the first byte past the last byte copied
  106461. ** before this function returns.
  106462. */
  106463. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  106464. char *pEnd = *ppPoslist;
  106465. char c = 0;
  106466. /* The end of a position list is marked by a zero encoded as an FTS3
  106467. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  106468. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  106469. ** of some other, multi-byte, value.
  106470. **
  106471. ** The following while-loop moves pEnd to point to the first byte that is not
  106472. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  106473. ** pEnd once more so that it points to the byte immediately following the
  106474. ** last byte in the position-list.
  106475. */
  106476. while( *pEnd | c ){
  106477. c = *pEnd++ & 0x80;
  106478. testcase( c!=0 && (*pEnd)==0 );
  106479. }
  106480. pEnd++; /* Advance past the POS_END terminator byte */
  106481. if( pp ){
  106482. int n = (int)(pEnd - *ppPoslist);
  106483. char *p = *pp;
  106484. memcpy(p, *ppPoslist, n);
  106485. p += n;
  106486. *pp = p;
  106487. }
  106488. *ppPoslist = pEnd;
  106489. }
  106490. /*
  106491. ** When this function is called, *ppPoslist is assumed to point to the
  106492. ** start of a column-list. After it returns, *ppPoslist points to the
  106493. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  106494. **
  106495. ** A column-list is list of delta-encoded positions for a single column
  106496. ** within a single document within a doclist.
  106497. **
  106498. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  106499. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  106500. ** the POS_COLUMN or POS_END that terminates the column-list.
  106501. **
  106502. ** If pp is not NULL, then the contents of the column-list are copied
  106503. ** to *pp. *pp is set to point to the first byte past the last byte copied
  106504. ** before this function returns. The POS_COLUMN or POS_END terminator
  106505. ** is not copied into *pp.
  106506. */
  106507. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  106508. char *pEnd = *ppPoslist;
  106509. char c = 0;
  106510. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  106511. ** not part of a multi-byte varint.
  106512. */
  106513. while( 0xFE & (*pEnd | c) ){
  106514. c = *pEnd++ & 0x80;
  106515. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  106516. }
  106517. if( pp ){
  106518. int n = (int)(pEnd - *ppPoslist);
  106519. char *p = *pp;
  106520. memcpy(p, *ppPoslist, n);
  106521. p += n;
  106522. *pp = p;
  106523. }
  106524. *ppPoslist = pEnd;
  106525. }
  106526. /*
  106527. ** Value used to signify the end of an position-list. This is safe because
  106528. ** it is not possible to have a document with 2^31 terms.
  106529. */
  106530. #define POSITION_LIST_END 0x7fffffff
  106531. /*
  106532. ** This function is used to help parse position-lists. When this function is
  106533. ** called, *pp may point to the start of the next varint in the position-list
  106534. ** being parsed, or it may point to 1 byte past the end of the position-list
  106535. ** (in which case **pp will be a terminator bytes POS_END (0) or
  106536. ** (1)).
  106537. **
  106538. ** If *pp points past the end of the current position-list, set *pi to
  106539. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  106540. ** increment the current value of *pi by the value read, and set *pp to
  106541. ** point to the next value before returning.
  106542. **
  106543. ** Before calling this routine *pi must be initialized to the value of
  106544. ** the previous position, or zero if we are reading the first position
  106545. ** in the position-list. Because positions are delta-encoded, the value
  106546. ** of the previous position is needed in order to compute the value of
  106547. ** the next position.
  106548. */
  106549. static void fts3ReadNextPos(
  106550. char **pp, /* IN/OUT: Pointer into position-list buffer */
  106551. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  106552. ){
  106553. if( (**pp)&0xFE ){
  106554. fts3GetDeltaVarint(pp, pi);
  106555. *pi -= 2;
  106556. }else{
  106557. *pi = POSITION_LIST_END;
  106558. }
  106559. }
  106560. /*
  106561. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  106562. ** the value of iCol encoded as a varint to *pp. This will start a new
  106563. ** column list.
  106564. **
  106565. ** Set *pp to point to the byte just after the last byte written before
  106566. ** returning (do not modify it if iCol==0). Return the total number of bytes
  106567. ** written (0 if iCol==0).
  106568. */
  106569. static int fts3PutColNumber(char **pp, int iCol){
  106570. int n = 0; /* Number of bytes written */
  106571. if( iCol ){
  106572. char *p = *pp; /* Output pointer */
  106573. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  106574. *p = 0x01;
  106575. *pp = &p[n];
  106576. }
  106577. return n;
  106578. }
  106579. /*
  106580. ** Compute the union of two position lists. The output written
  106581. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  106582. ** order and with any duplicates removed. All pointers are
  106583. ** updated appropriately. The caller is responsible for insuring
  106584. ** that there is enough space in *pp to hold the complete output.
  106585. */
  106586. static void fts3PoslistMerge(
  106587. char **pp, /* Output buffer */
  106588. char **pp1, /* Left input list */
  106589. char **pp2 /* Right input list */
  106590. ){
  106591. char *p = *pp;
  106592. char *p1 = *pp1;
  106593. char *p2 = *pp2;
  106594. while( *p1 || *p2 ){
  106595. int iCol1; /* The current column index in pp1 */
  106596. int iCol2; /* The current column index in pp2 */
  106597. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  106598. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  106599. else iCol1 = 0;
  106600. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  106601. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  106602. else iCol2 = 0;
  106603. if( iCol1==iCol2 ){
  106604. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  106605. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  106606. sqlite3_int64 iPrev = 0;
  106607. int n = fts3PutColNumber(&p, iCol1);
  106608. p1 += n;
  106609. p2 += n;
  106610. /* At this point, both p1 and p2 point to the start of column-lists
  106611. ** for the same column (the column with index iCol1 and iCol2).
  106612. ** A column-list is a list of non-negative delta-encoded varints, each
  106613. ** incremented by 2 before being stored. Each list is terminated by a
  106614. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  106615. ** and writes the results to buffer p. p is left pointing to the byte
  106616. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  106617. ** written to the output.
  106618. */
  106619. fts3GetDeltaVarint(&p1, &i1);
  106620. fts3GetDeltaVarint(&p2, &i2);
  106621. do {
  106622. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  106623. iPrev -= 2;
  106624. if( i1==i2 ){
  106625. fts3ReadNextPos(&p1, &i1);
  106626. fts3ReadNextPos(&p2, &i2);
  106627. }else if( i1<i2 ){
  106628. fts3ReadNextPos(&p1, &i1);
  106629. }else{
  106630. fts3ReadNextPos(&p2, &i2);
  106631. }
  106632. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  106633. }else if( iCol1<iCol2 ){
  106634. p1 += fts3PutColNumber(&p, iCol1);
  106635. fts3ColumnlistCopy(&p, &p1);
  106636. }else{
  106637. p2 += fts3PutColNumber(&p, iCol2);
  106638. fts3ColumnlistCopy(&p, &p2);
  106639. }
  106640. }
  106641. *p++ = POS_END;
  106642. *pp = p;
  106643. *pp1 = p1 + 1;
  106644. *pp2 = p2 + 1;
  106645. }
  106646. /*
  106647. ** This function is used to merge two position lists into one. When it is
  106648. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  106649. ** the part of a doclist that follows each document id. For example, if a row
  106650. ** contains:
  106651. **
  106652. ** 'a b c'|'x y z'|'a b b a'
  106653. **
  106654. ** Then the position list for this row for token 'b' would consist of:
  106655. **
  106656. ** 0x02 0x01 0x02 0x03 0x03 0x00
  106657. **
  106658. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  106659. ** byte following the 0x00 terminator of their respective position lists.
  106660. **
  106661. ** If isSaveLeft is 0, an entry is added to the output position list for
  106662. ** each position in *pp2 for which there exists one or more positions in
  106663. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  106664. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  106665. ** slots before it.
  106666. **
  106667. ** e.g. nToken==1 searches for adjacent positions.
  106668. */
  106669. static int fts3PoslistPhraseMerge(
  106670. char **pp, /* IN/OUT: Preallocated output buffer */
  106671. int nToken, /* Maximum difference in token positions */
  106672. int isSaveLeft, /* Save the left position */
  106673. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  106674. char **pp1, /* IN/OUT: Left input list */
  106675. char **pp2 /* IN/OUT: Right input list */
  106676. ){
  106677. char *p = *pp;
  106678. char *p1 = *pp1;
  106679. char *p2 = *pp2;
  106680. int iCol1 = 0;
  106681. int iCol2 = 0;
  106682. /* Never set both isSaveLeft and isExact for the same invocation. */
  106683. assert( isSaveLeft==0 || isExact==0 );
  106684. assert( p!=0 && *p1!=0 && *p2!=0 );
  106685. if( *p1==POS_COLUMN ){
  106686. p1++;
  106687. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106688. }
  106689. if( *p2==POS_COLUMN ){
  106690. p2++;
  106691. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106692. }
  106693. while( 1 ){
  106694. if( iCol1==iCol2 ){
  106695. char *pSave = p;
  106696. sqlite3_int64 iPrev = 0;
  106697. sqlite3_int64 iPos1 = 0;
  106698. sqlite3_int64 iPos2 = 0;
  106699. if( iCol1 ){
  106700. *p++ = POS_COLUMN;
  106701. p += sqlite3Fts3PutVarint(p, iCol1);
  106702. }
  106703. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  106704. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  106705. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  106706. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  106707. while( 1 ){
  106708. if( iPos2==iPos1+nToken
  106709. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  106710. ){
  106711. sqlite3_int64 iSave;
  106712. iSave = isSaveLeft ? iPos1 : iPos2;
  106713. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  106714. pSave = 0;
  106715. assert( p );
  106716. }
  106717. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  106718. if( (*p2&0xFE)==0 ) break;
  106719. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  106720. }else{
  106721. if( (*p1&0xFE)==0 ) break;
  106722. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  106723. }
  106724. }
  106725. if( pSave ){
  106726. assert( pp && p );
  106727. p = pSave;
  106728. }
  106729. fts3ColumnlistCopy(0, &p1);
  106730. fts3ColumnlistCopy(0, &p2);
  106731. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  106732. if( 0==*p1 || 0==*p2 ) break;
  106733. p1++;
  106734. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106735. p2++;
  106736. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106737. }
  106738. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  106739. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  106740. ** end of the position list, or the 0x01 that precedes the next
  106741. ** column-number in the position list.
  106742. */
  106743. else if( iCol1<iCol2 ){
  106744. fts3ColumnlistCopy(0, &p1);
  106745. if( 0==*p1 ) break;
  106746. p1++;
  106747. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106748. }else{
  106749. fts3ColumnlistCopy(0, &p2);
  106750. if( 0==*p2 ) break;
  106751. p2++;
  106752. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106753. }
  106754. }
  106755. fts3PoslistCopy(0, &p2);
  106756. fts3PoslistCopy(0, &p1);
  106757. *pp1 = p1;
  106758. *pp2 = p2;
  106759. if( *pp==p ){
  106760. return 0;
  106761. }
  106762. *p++ = 0x00;
  106763. *pp = p;
  106764. return 1;
  106765. }
  106766. /*
  106767. ** Merge two position-lists as required by the NEAR operator. The argument
  106768. ** position lists correspond to the left and right phrases of an expression
  106769. ** like:
  106770. **
  106771. ** "phrase 1" NEAR "phrase number 2"
  106772. **
  106773. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  106774. ** expression and *pp2 to the right. As usual, the indexes in the position
  106775. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  106776. ** in the example above).
  106777. **
  106778. ** The output position list - written to *pp - is a copy of *pp2 with those
  106779. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  106780. */
  106781. static int fts3PoslistNearMerge(
  106782. char **pp, /* Output buffer */
  106783. char *aTmp, /* Temporary buffer space */
  106784. int nRight, /* Maximum difference in token positions */
  106785. int nLeft, /* Maximum difference in token positions */
  106786. char **pp1, /* IN/OUT: Left input list */
  106787. char **pp2 /* IN/OUT: Right input list */
  106788. ){
  106789. char *p1 = *pp1;
  106790. char *p2 = *pp2;
  106791. char *pTmp1 = aTmp;
  106792. char *pTmp2;
  106793. char *aTmp2;
  106794. int res = 1;
  106795. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  106796. aTmp2 = pTmp2 = pTmp1;
  106797. *pp1 = p1;
  106798. *pp2 = p2;
  106799. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  106800. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  106801. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  106802. }else if( pTmp1!=aTmp ){
  106803. fts3PoslistCopy(pp, &aTmp);
  106804. }else if( pTmp2!=aTmp2 ){
  106805. fts3PoslistCopy(pp, &aTmp2);
  106806. }else{
  106807. res = 0;
  106808. }
  106809. return res;
  106810. }
  106811. /*
  106812. ** An instance of this function is used to merge together the (potentially
  106813. ** large number of) doclists for each term that matches a prefix query.
  106814. ** See function fts3TermSelectMerge() for details.
  106815. */
  106816. typedef struct TermSelect TermSelect;
  106817. struct TermSelect {
  106818. char *aaOutput[16]; /* Malloc'd output buffers */
  106819. int anOutput[16]; /* Size each output buffer in bytes */
  106820. };
  106821. /*
  106822. ** This function is used to read a single varint from a buffer. Parameter
  106823. ** pEnd points 1 byte past the end of the buffer. When this function is
  106824. ** called, if *pp points to pEnd or greater, then the end of the buffer
  106825. ** has been reached. In this case *pp is set to 0 and the function returns.
  106826. **
  106827. ** If *pp does not point to or past pEnd, then a single varint is read
  106828. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  106829. **
  106830. ** If bDescIdx is false, the value read is added to *pVal before returning.
  106831. ** If it is true, the value read is subtracted from *pVal before this
  106832. ** function returns.
  106833. */
  106834. static void fts3GetDeltaVarint3(
  106835. char **pp, /* IN/OUT: Point to read varint from */
  106836. char *pEnd, /* End of buffer */
  106837. int bDescIdx, /* True if docids are descending */
  106838. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  106839. ){
  106840. if( *pp>=pEnd ){
  106841. *pp = 0;
  106842. }else{
  106843. sqlite3_int64 iVal;
  106844. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  106845. if( bDescIdx ){
  106846. *pVal -= iVal;
  106847. }else{
  106848. *pVal += iVal;
  106849. }
  106850. }
  106851. }
  106852. /*
  106853. ** This function is used to write a single varint to a buffer. The varint
  106854. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  106855. ** end of the value written.
  106856. **
  106857. ** If *pbFirst is zero when this function is called, the value written to
  106858. ** the buffer is that of parameter iVal.
  106859. **
  106860. ** If *pbFirst is non-zero when this function is called, then the value
  106861. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  106862. ** (if bDescIdx is non-zero).
  106863. **
  106864. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  106865. ** to the value of parameter iVal.
  106866. */
  106867. static void fts3PutDeltaVarint3(
  106868. char **pp, /* IN/OUT: Output pointer */
  106869. int bDescIdx, /* True for descending docids */
  106870. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  106871. int *pbFirst, /* IN/OUT: True after first int written */
  106872. sqlite3_int64 iVal /* Write this value to the list */
  106873. ){
  106874. sqlite3_int64 iWrite;
  106875. if( bDescIdx==0 || *pbFirst==0 ){
  106876. iWrite = iVal - *piPrev;
  106877. }else{
  106878. iWrite = *piPrev - iVal;
  106879. }
  106880. assert( *pbFirst || *piPrev==0 );
  106881. assert( *pbFirst==0 || iWrite>0 );
  106882. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  106883. *piPrev = iVal;
  106884. *pbFirst = 1;
  106885. }
  106886. /*
  106887. ** This macro is used by various functions that merge doclists. The two
  106888. ** arguments are 64-bit docid values. If the value of the stack variable
  106889. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  106890. ** Otherwise, (i2-i1).
  106891. **
  106892. ** Using this makes it easier to write code that can merge doclists that are
  106893. ** sorted in either ascending or descending order.
  106894. */
  106895. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  106896. /*
  106897. ** This function does an "OR" merge of two doclists (output contains all
  106898. ** positions contained in either argument doclist). If the docids in the
  106899. ** input doclists are sorted in ascending order, parameter bDescDoclist
  106900. ** should be false. If they are sorted in ascending order, it should be
  106901. ** passed a non-zero value.
  106902. **
  106903. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  106904. ** containing the output doclist and SQLITE_OK is returned. In this case
  106905. ** *pnOut is set to the number of bytes in the output doclist.
  106906. **
  106907. ** If an error occurs, an SQLite error code is returned. The output values
  106908. ** are undefined in this case.
  106909. */
  106910. static int fts3DoclistOrMerge(
  106911. int bDescDoclist, /* True if arguments are desc */
  106912. char *a1, int n1, /* First doclist */
  106913. char *a2, int n2, /* Second doclist */
  106914. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  106915. ){
  106916. sqlite3_int64 i1 = 0;
  106917. sqlite3_int64 i2 = 0;
  106918. sqlite3_int64 iPrev = 0;
  106919. char *pEnd1 = &a1[n1];
  106920. char *pEnd2 = &a2[n2];
  106921. char *p1 = a1;
  106922. char *p2 = a2;
  106923. char *p;
  106924. char *aOut;
  106925. int bFirstOut = 0;
  106926. *paOut = 0;
  106927. *pnOut = 0;
  106928. /* Allocate space for the output. Both the input and output doclists
  106929. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  106930. ** then the first docid in each list is simply encoded as a varint. For
  106931. ** each subsequent docid, the varint stored is the difference between the
  106932. ** current and previous docid (a positive number - since the list is in
  106933. ** ascending order).
  106934. **
  106935. ** The first docid written to the output is therefore encoded using the
  106936. ** same number of bytes as it is in whichever of the input lists it is
  106937. ** read from. And each subsequent docid read from the same input list
  106938. ** consumes either the same or less bytes as it did in the input (since
  106939. ** the difference between it and the previous value in the output must
  106940. ** be a positive value less than or equal to the delta value read from
  106941. ** the input list). The same argument applies to all but the first docid
  106942. ** read from the 'other' list. And to the contents of all position lists
  106943. ** that will be copied and merged from the input to the output.
  106944. **
  106945. ** However, if the first docid copied to the output is a negative number,
  106946. ** then the encoding of the first docid from the 'other' input list may
  106947. ** be larger in the output than it was in the input (since the delta value
  106948. ** may be a larger positive integer than the actual docid).
  106949. **
  106950. ** The space required to store the output is therefore the sum of the
  106951. ** sizes of the two inputs, plus enough space for exactly one of the input
  106952. ** docids to grow.
  106953. **
  106954. ** A symetric argument may be made if the doclists are in descending
  106955. ** order.
  106956. */
  106957. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  106958. if( !aOut ) return SQLITE_NOMEM;
  106959. p = aOut;
  106960. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  106961. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  106962. while( p1 || p2 ){
  106963. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  106964. if( p2 && p1 && iDiff==0 ){
  106965. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  106966. fts3PoslistMerge(&p, &p1, &p2);
  106967. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  106968. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  106969. }else if( !p2 || (p1 && iDiff<0) ){
  106970. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  106971. fts3PoslistCopy(&p, &p1);
  106972. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  106973. }else{
  106974. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  106975. fts3PoslistCopy(&p, &p2);
  106976. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  106977. }
  106978. }
  106979. *paOut = aOut;
  106980. *pnOut = (int)(p-aOut);
  106981. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  106982. return SQLITE_OK;
  106983. }
  106984. /*
  106985. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  106986. ** the output contains a copy of each position from the right-hand input
  106987. ** doclist for which there is a position in the left-hand input doclist
  106988. ** exactly nDist tokens before it.
  106989. **
  106990. ** If the docids in the input doclists are sorted in ascending order,
  106991. ** parameter bDescDoclist should be false. If they are sorted in ascending
  106992. ** order, it should be passed a non-zero value.
  106993. **
  106994. ** The right-hand input doclist is overwritten by this function.
  106995. */
  106996. static void fts3DoclistPhraseMerge(
  106997. int bDescDoclist, /* True if arguments are desc */
  106998. int nDist, /* Distance from left to right (1=adjacent) */
  106999. char *aLeft, int nLeft, /* Left doclist */
  107000. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  107001. ){
  107002. sqlite3_int64 i1 = 0;
  107003. sqlite3_int64 i2 = 0;
  107004. sqlite3_int64 iPrev = 0;
  107005. char *pEnd1 = &aLeft[nLeft];
  107006. char *pEnd2 = &aRight[*pnRight];
  107007. char *p1 = aLeft;
  107008. char *p2 = aRight;
  107009. char *p;
  107010. int bFirstOut = 0;
  107011. char *aOut = aRight;
  107012. assert( nDist>0 );
  107013. p = aOut;
  107014. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  107015. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  107016. while( p1 && p2 ){
  107017. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  107018. if( iDiff==0 ){
  107019. char *pSave = p;
  107020. sqlite3_int64 iPrevSave = iPrev;
  107021. int bFirstOutSave = bFirstOut;
  107022. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  107023. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  107024. p = pSave;
  107025. iPrev = iPrevSave;
  107026. bFirstOut = bFirstOutSave;
  107027. }
  107028. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  107029. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  107030. }else if( iDiff<0 ){
  107031. fts3PoslistCopy(0, &p1);
  107032. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  107033. }else{
  107034. fts3PoslistCopy(0, &p2);
  107035. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  107036. }
  107037. }
  107038. *pnRight = (int)(p - aOut);
  107039. }
  107040. /*
  107041. ** Argument pList points to a position list nList bytes in size. This
  107042. ** function checks to see if the position list contains any entries for
  107043. ** a token in position 0 (of any column). If so, it writes argument iDelta
  107044. ** to the output buffer pOut, followed by a position list consisting only
  107045. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  107046. ** The value returned is the number of bytes written to pOut (if any).
  107047. */
  107048. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  107049. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  107050. char *pList, /* Position list (no 0x00 term) */
  107051. int nList, /* Size of pList in bytes */
  107052. char *pOut /* Write output here */
  107053. ){
  107054. int nOut = 0;
  107055. int bWritten = 0; /* True once iDelta has been written */
  107056. char *p = pList;
  107057. char *pEnd = &pList[nList];
  107058. if( *p!=0x01 ){
  107059. if( *p==0x02 ){
  107060. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  107061. pOut[nOut++] = 0x02;
  107062. bWritten = 1;
  107063. }
  107064. fts3ColumnlistCopy(0, &p);
  107065. }
  107066. while( p<pEnd && *p==0x01 ){
  107067. sqlite3_int64 iCol;
  107068. p++;
  107069. p += sqlite3Fts3GetVarint(p, &iCol);
  107070. if( *p==0x02 ){
  107071. if( bWritten==0 ){
  107072. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  107073. bWritten = 1;
  107074. }
  107075. pOut[nOut++] = 0x01;
  107076. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  107077. pOut[nOut++] = 0x02;
  107078. }
  107079. fts3ColumnlistCopy(0, &p);
  107080. }
  107081. if( bWritten ){
  107082. pOut[nOut++] = 0x00;
  107083. }
  107084. return nOut;
  107085. }
  107086. /*
  107087. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  107088. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  107089. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  107090. **
  107091. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  107092. ** the responsibility of the caller to free any doclists left in the
  107093. ** TermSelect.aaOutput[] array.
  107094. */
  107095. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  107096. char *aOut = 0;
  107097. int nOut = 0;
  107098. int i;
  107099. /* Loop through the doclists in the aaOutput[] array. Merge them all
  107100. ** into a single doclist.
  107101. */
  107102. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  107103. if( pTS->aaOutput[i] ){
  107104. if( !aOut ){
  107105. aOut = pTS->aaOutput[i];
  107106. nOut = pTS->anOutput[i];
  107107. pTS->aaOutput[i] = 0;
  107108. }else{
  107109. int nNew;
  107110. char *aNew;
  107111. int rc = fts3DoclistOrMerge(p->bDescIdx,
  107112. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  107113. );
  107114. if( rc!=SQLITE_OK ){
  107115. sqlite3_free(aOut);
  107116. return rc;
  107117. }
  107118. sqlite3_free(pTS->aaOutput[i]);
  107119. sqlite3_free(aOut);
  107120. pTS->aaOutput[i] = 0;
  107121. aOut = aNew;
  107122. nOut = nNew;
  107123. }
  107124. }
  107125. }
  107126. pTS->aaOutput[0] = aOut;
  107127. pTS->anOutput[0] = nOut;
  107128. return SQLITE_OK;
  107129. }
  107130. /*
  107131. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  107132. ** as the first argument. The merge is an "OR" merge (see function
  107133. ** fts3DoclistOrMerge() for details).
  107134. **
  107135. ** This function is called with the doclist for each term that matches
  107136. ** a queried prefix. It merges all these doclists into one, the doclist
  107137. ** for the specified prefix. Since there can be a very large number of
  107138. ** doclists to merge, the merging is done pair-wise using the TermSelect
  107139. ** object.
  107140. **
  107141. ** This function returns SQLITE_OK if the merge is successful, or an
  107142. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  107143. */
  107144. static int fts3TermSelectMerge(
  107145. Fts3Table *p, /* FTS table handle */
  107146. TermSelect *pTS, /* TermSelect object to merge into */
  107147. char *aDoclist, /* Pointer to doclist */
  107148. int nDoclist /* Size of aDoclist in bytes */
  107149. ){
  107150. if( pTS->aaOutput[0]==0 ){
  107151. /* If this is the first term selected, copy the doclist to the output
  107152. ** buffer using memcpy(). */
  107153. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  107154. pTS->anOutput[0] = nDoclist;
  107155. if( pTS->aaOutput[0] ){
  107156. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  107157. }else{
  107158. return SQLITE_NOMEM;
  107159. }
  107160. }else{
  107161. char *aMerge = aDoclist;
  107162. int nMerge = nDoclist;
  107163. int iOut;
  107164. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  107165. if( pTS->aaOutput[iOut]==0 ){
  107166. assert( iOut>0 );
  107167. pTS->aaOutput[iOut] = aMerge;
  107168. pTS->anOutput[iOut] = nMerge;
  107169. break;
  107170. }else{
  107171. char *aNew;
  107172. int nNew;
  107173. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  107174. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  107175. );
  107176. if( rc!=SQLITE_OK ){
  107177. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  107178. return rc;
  107179. }
  107180. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  107181. sqlite3_free(pTS->aaOutput[iOut]);
  107182. pTS->aaOutput[iOut] = 0;
  107183. aMerge = aNew;
  107184. nMerge = nNew;
  107185. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  107186. pTS->aaOutput[iOut] = aMerge;
  107187. pTS->anOutput[iOut] = nMerge;
  107188. }
  107189. }
  107190. }
  107191. }
  107192. return SQLITE_OK;
  107193. }
  107194. /*
  107195. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  107196. */
  107197. static int fts3SegReaderCursorAppend(
  107198. Fts3MultiSegReader *pCsr,
  107199. Fts3SegReader *pNew
  107200. ){
  107201. if( (pCsr->nSegment%16)==0 ){
  107202. Fts3SegReader **apNew;
  107203. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  107204. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  107205. if( !apNew ){
  107206. sqlite3Fts3SegReaderFree(pNew);
  107207. return SQLITE_NOMEM;
  107208. }
  107209. pCsr->apSegment = apNew;
  107210. }
  107211. pCsr->apSegment[pCsr->nSegment++] = pNew;
  107212. return SQLITE_OK;
  107213. }
  107214. /*
  107215. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  107216. ** 8th argument.
  107217. **
  107218. ** This function returns SQLITE_OK if successful, or an SQLite error code
  107219. ** otherwise.
  107220. */
  107221. static int fts3SegReaderCursor(
  107222. Fts3Table *p, /* FTS3 table handle */
  107223. int iLangid, /* Language id */
  107224. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  107225. int iLevel, /* Level of segments to scan */
  107226. const char *zTerm, /* Term to query for */
  107227. int nTerm, /* Size of zTerm in bytes */
  107228. int isPrefix, /* True for a prefix search */
  107229. int isScan, /* True to scan from zTerm to EOF */
  107230. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  107231. ){
  107232. int rc = SQLITE_OK; /* Error code */
  107233. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  107234. int rc2; /* Result of sqlite3_reset() */
  107235. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  107236. ** for the pending-terms. If this is a scan, then this call must be being
  107237. ** made by an fts4aux module, not an FTS table. In this case calling
  107238. ** Fts3SegReaderPending might segfault, as the data structures used by
  107239. ** fts4aux are not completely populated. So it's easiest to filter these
  107240. ** calls out here. */
  107241. if( iLevel<0 && p->aIndex ){
  107242. Fts3SegReader *pSeg = 0;
  107243. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  107244. if( rc==SQLITE_OK && pSeg ){
  107245. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  107246. }
  107247. }
  107248. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  107249. if( rc==SQLITE_OK ){
  107250. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  107251. }
  107252. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  107253. Fts3SegReader *pSeg = 0;
  107254. /* Read the values returned by the SELECT into local variables. */
  107255. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  107256. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  107257. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  107258. int nRoot = sqlite3_column_bytes(pStmt, 4);
  107259. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  107260. /* If zTerm is not NULL, and this segment is not stored entirely on its
  107261. ** root node, the range of leaves scanned can be reduced. Do this. */
  107262. if( iStartBlock && zTerm ){
  107263. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  107264. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  107265. if( rc!=SQLITE_OK ) goto finished;
  107266. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  107267. }
  107268. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  107269. (isPrefix==0 && isScan==0),
  107270. iStartBlock, iLeavesEndBlock,
  107271. iEndBlock, zRoot, nRoot, &pSeg
  107272. );
  107273. if( rc!=SQLITE_OK ) goto finished;
  107274. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  107275. }
  107276. }
  107277. finished:
  107278. rc2 = sqlite3_reset(pStmt);
  107279. if( rc==SQLITE_DONE ) rc = rc2;
  107280. return rc;
  107281. }
  107282. /*
  107283. ** Set up a cursor object for iterating through a full-text index or a
  107284. ** single level therein.
  107285. */
  107286. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  107287. Fts3Table *p, /* FTS3 table handle */
  107288. int iLangid, /* Language-id to search */
  107289. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  107290. int iLevel, /* Level of segments to scan */
  107291. const char *zTerm, /* Term to query for */
  107292. int nTerm, /* Size of zTerm in bytes */
  107293. int isPrefix, /* True for a prefix search */
  107294. int isScan, /* True to scan from zTerm to EOF */
  107295. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  107296. ){
  107297. assert( iIndex>=0 && iIndex<p->nIndex );
  107298. assert( iLevel==FTS3_SEGCURSOR_ALL
  107299. || iLevel==FTS3_SEGCURSOR_PENDING
  107300. || iLevel>=0
  107301. );
  107302. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  107303. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  107304. assert( isPrefix==0 || isScan==0 );
  107305. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  107306. return fts3SegReaderCursor(
  107307. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  107308. );
  107309. }
  107310. /*
  107311. ** In addition to its current configuration, have the Fts3MultiSegReader
  107312. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  107313. **
  107314. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  107315. */
  107316. static int fts3SegReaderCursorAddZero(
  107317. Fts3Table *p, /* FTS virtual table handle */
  107318. int iLangid,
  107319. const char *zTerm, /* Term to scan doclist of */
  107320. int nTerm, /* Number of bytes in zTerm */
  107321. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  107322. ){
  107323. return fts3SegReaderCursor(p,
  107324. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  107325. );
  107326. }
  107327. /*
  107328. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  107329. ** if isPrefix is true, to scan the doclist for all terms for which
  107330. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  107331. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  107332. ** an SQLite error code.
  107333. **
  107334. ** It is the responsibility of the caller to free this object by eventually
  107335. ** passing it to fts3SegReaderCursorFree()
  107336. **
  107337. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  107338. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  107339. */
  107340. static int fts3TermSegReaderCursor(
  107341. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  107342. const char *zTerm, /* Term to query for */
  107343. int nTerm, /* Size of zTerm in bytes */
  107344. int isPrefix, /* True for a prefix search */
  107345. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  107346. ){
  107347. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  107348. int rc = SQLITE_NOMEM; /* Return code */
  107349. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  107350. if( pSegcsr ){
  107351. int i;
  107352. int bFound = 0; /* True once an index has been found */
  107353. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  107354. if( isPrefix ){
  107355. for(i=1; bFound==0 && i<p->nIndex; i++){
  107356. if( p->aIndex[i].nPrefix==nTerm ){
  107357. bFound = 1;
  107358. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107359. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  107360. );
  107361. pSegcsr->bLookup = 1;
  107362. }
  107363. }
  107364. for(i=1; bFound==0 && i<p->nIndex; i++){
  107365. if( p->aIndex[i].nPrefix==nTerm+1 ){
  107366. bFound = 1;
  107367. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107368. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  107369. );
  107370. if( rc==SQLITE_OK ){
  107371. rc = fts3SegReaderCursorAddZero(
  107372. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  107373. );
  107374. }
  107375. }
  107376. }
  107377. }
  107378. if( bFound==0 ){
  107379. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107380. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  107381. );
  107382. pSegcsr->bLookup = !isPrefix;
  107383. }
  107384. }
  107385. *ppSegcsr = pSegcsr;
  107386. return rc;
  107387. }
  107388. /*
  107389. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  107390. */
  107391. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  107392. sqlite3Fts3SegReaderFinish(pSegcsr);
  107393. sqlite3_free(pSegcsr);
  107394. }
  107395. /*
  107396. ** This function retrieves the doclist for the specified term (or term
  107397. ** prefix) from the database.
  107398. */
  107399. static int fts3TermSelect(
  107400. Fts3Table *p, /* Virtual table handle */
  107401. Fts3PhraseToken *pTok, /* Token to query for */
  107402. int iColumn, /* Column to query (or -ve for all columns) */
  107403. int *pnOut, /* OUT: Size of buffer at *ppOut */
  107404. char **ppOut /* OUT: Malloced result buffer */
  107405. ){
  107406. int rc; /* Return code */
  107407. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  107408. TermSelect tsc; /* Object for pair-wise doclist merging */
  107409. Fts3SegFilter filter; /* Segment term filter configuration */
  107410. pSegcsr = pTok->pSegcsr;
  107411. memset(&tsc, 0, sizeof(TermSelect));
  107412. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  107413. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  107414. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  107415. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  107416. filter.iCol = iColumn;
  107417. filter.zTerm = pTok->z;
  107418. filter.nTerm = pTok->n;
  107419. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  107420. while( SQLITE_OK==rc
  107421. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  107422. ){
  107423. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  107424. }
  107425. if( rc==SQLITE_OK ){
  107426. rc = fts3TermSelectFinishMerge(p, &tsc);
  107427. }
  107428. if( rc==SQLITE_OK ){
  107429. *ppOut = tsc.aaOutput[0];
  107430. *pnOut = tsc.anOutput[0];
  107431. }else{
  107432. int i;
  107433. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  107434. sqlite3_free(tsc.aaOutput[i]);
  107435. }
  107436. }
  107437. fts3SegReaderCursorFree(pSegcsr);
  107438. pTok->pSegcsr = 0;
  107439. return rc;
  107440. }
  107441. /*
  107442. ** This function counts the total number of docids in the doclist stored
  107443. ** in buffer aList[], size nList bytes.
  107444. **
  107445. ** If the isPoslist argument is true, then it is assumed that the doclist
  107446. ** contains a position-list following each docid. Otherwise, it is assumed
  107447. ** that the doclist is simply a list of docids stored as delta encoded
  107448. ** varints.
  107449. */
  107450. static int fts3DoclistCountDocids(char *aList, int nList){
  107451. int nDoc = 0; /* Return value */
  107452. if( aList ){
  107453. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  107454. char *p = aList; /* Cursor */
  107455. while( p<aEnd ){
  107456. nDoc++;
  107457. while( (*p++)&0x80 ); /* Skip docid varint */
  107458. fts3PoslistCopy(0, &p); /* Skip over position list */
  107459. }
  107460. }
  107461. return nDoc;
  107462. }
  107463. /*
  107464. ** Advance the cursor to the next row in the %_content table that
  107465. ** matches the search criteria. For a MATCH search, this will be
  107466. ** the next row that matches. For a full-table scan, this will be
  107467. ** simply the next row in the %_content table. For a docid lookup,
  107468. ** this routine simply sets the EOF flag.
  107469. **
  107470. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  107471. ** even if we reach end-of-file. The fts3EofMethod() will be called
  107472. ** subsequently to determine whether or not an EOF was hit.
  107473. */
  107474. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  107475. int rc;
  107476. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  107477. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  107478. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  107479. pCsr->isEof = 1;
  107480. rc = sqlite3_reset(pCsr->pStmt);
  107481. }else{
  107482. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  107483. rc = SQLITE_OK;
  107484. }
  107485. }else{
  107486. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  107487. }
  107488. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  107489. return rc;
  107490. }
  107491. /*
  107492. ** The following are copied from sqliteInt.h.
  107493. **
  107494. ** Constants for the largest and smallest possible 64-bit signed integers.
  107495. ** These macros are designed to work correctly on both 32-bit and 64-bit
  107496. ** compilers.
  107497. */
  107498. #ifndef SQLITE_AMALGAMATION
  107499. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  107500. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  107501. #endif
  107502. /*
  107503. ** If the numeric type of argument pVal is "integer", then return it
  107504. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  107505. ** the second parameter, iDefault.
  107506. */
  107507. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  107508. if( pVal ){
  107509. int eType = sqlite3_value_numeric_type(pVal);
  107510. if( eType==SQLITE_INTEGER ){
  107511. return sqlite3_value_int64(pVal);
  107512. }
  107513. }
  107514. return iDefault;
  107515. }
  107516. /*
  107517. ** This is the xFilter interface for the virtual table. See
  107518. ** the virtual table xFilter method documentation for additional
  107519. ** information.
  107520. **
  107521. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  107522. ** the %_content table.
  107523. **
  107524. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  107525. ** in the %_content table.
  107526. **
  107527. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  107528. ** column on the left-hand side of the MATCH operator is column
  107529. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  107530. ** side of the MATCH operator.
  107531. */
  107532. static int fts3FilterMethod(
  107533. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  107534. int idxNum, /* Strategy index */
  107535. const char *idxStr, /* Unused */
  107536. int nVal, /* Number of elements in apVal */
  107537. sqlite3_value **apVal /* Arguments for the indexing scheme */
  107538. ){
  107539. int rc;
  107540. char *zSql; /* SQL statement used to access %_content */
  107541. int eSearch;
  107542. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  107543. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  107544. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  107545. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  107546. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  107547. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  107548. int iIdx;
  107549. UNUSED_PARAMETER(idxStr);
  107550. UNUSED_PARAMETER(nVal);
  107551. eSearch = (idxNum & 0x0000FFFF);
  107552. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  107553. assert( p->pSegments==0 );
  107554. /* Collect arguments into local variables */
  107555. iIdx = 0;
  107556. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  107557. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  107558. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  107559. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  107560. assert( iIdx==nVal );
  107561. /* In case the cursor has been used before, clear it now. */
  107562. sqlite3_finalize(pCsr->pStmt);
  107563. sqlite3_free(pCsr->aDoclist);
  107564. sqlite3Fts3ExprFree(pCsr->pExpr);
  107565. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  107566. /* Set the lower and upper bounds on docids to return */
  107567. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  107568. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  107569. if( idxStr ){
  107570. pCsr->bDesc = (idxStr[0]=='D');
  107571. }else{
  107572. pCsr->bDesc = p->bDescIdx;
  107573. }
  107574. pCsr->eSearch = (i16)eSearch;
  107575. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  107576. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  107577. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  107578. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  107579. return SQLITE_NOMEM;
  107580. }
  107581. pCsr->iLangid = 0;
  107582. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  107583. assert( p->base.zErrMsg==0 );
  107584. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  107585. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  107586. &p->base.zErrMsg
  107587. );
  107588. if( rc!=SQLITE_OK ){
  107589. return rc;
  107590. }
  107591. rc = fts3EvalStart(pCsr);
  107592. sqlite3Fts3SegmentsClose(p);
  107593. if( rc!=SQLITE_OK ) return rc;
  107594. pCsr->pNextId = pCsr->aDoclist;
  107595. pCsr->iPrevId = 0;
  107596. }
  107597. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  107598. ** statement loops through all rows of the %_content table. For a
  107599. ** full-text query or docid lookup, the statement retrieves a single
  107600. ** row by docid.
  107601. */
  107602. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  107603. zSql = sqlite3_mprintf(
  107604. "SELECT %s ORDER BY rowid %s",
  107605. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  107606. );
  107607. if( zSql ){
  107608. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  107609. sqlite3_free(zSql);
  107610. }else{
  107611. rc = SQLITE_NOMEM;
  107612. }
  107613. }else if( eSearch==FTS3_DOCID_SEARCH ){
  107614. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  107615. if( rc==SQLITE_OK ){
  107616. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  107617. }
  107618. }
  107619. if( rc!=SQLITE_OK ) return rc;
  107620. return fts3NextMethod(pCursor);
  107621. }
  107622. /*
  107623. ** This is the xEof method of the virtual table. SQLite calls this
  107624. ** routine to find out if it has reached the end of a result set.
  107625. */
  107626. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  107627. return ((Fts3Cursor *)pCursor)->isEof;
  107628. }
  107629. /*
  107630. ** This is the xRowid method. The SQLite core calls this routine to
  107631. ** retrieve the rowid for the current row of the result set. fts3
  107632. ** exposes %_content.docid as the rowid for the virtual table. The
  107633. ** rowid should be written to *pRowid.
  107634. */
  107635. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  107636. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  107637. *pRowid = pCsr->iPrevId;
  107638. return SQLITE_OK;
  107639. }
  107640. /*
  107641. ** This is the xColumn method, called by SQLite to request a value from
  107642. ** the row that the supplied cursor currently points to.
  107643. **
  107644. ** If:
  107645. **
  107646. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  107647. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  107648. ** (iCol == p->nColumn+1) -> Docid column
  107649. ** (iCol == p->nColumn+2) -> Langid column
  107650. */
  107651. static int fts3ColumnMethod(
  107652. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  107653. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  107654. int iCol /* Index of column to read value from */
  107655. ){
  107656. int rc = SQLITE_OK; /* Return Code */
  107657. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  107658. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  107659. /* The column value supplied by SQLite must be in range. */
  107660. assert( iCol>=0 && iCol<=p->nColumn+2 );
  107661. if( iCol==p->nColumn+1 ){
  107662. /* This call is a request for the "docid" column. Since "docid" is an
  107663. ** alias for "rowid", use the xRowid() method to obtain the value.
  107664. */
  107665. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  107666. }else if( iCol==p->nColumn ){
  107667. /* The extra column whose name is the same as the table.
  107668. ** Return a blob which is a pointer to the cursor. */
  107669. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  107670. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  107671. sqlite3_result_int64(pCtx, pCsr->iLangid);
  107672. }else{
  107673. /* The requested column is either a user column (one that contains
  107674. ** indexed data), or the language-id column. */
  107675. rc = fts3CursorSeek(0, pCsr);
  107676. if( rc==SQLITE_OK ){
  107677. if( iCol==p->nColumn+2 ){
  107678. int iLangid = 0;
  107679. if( p->zLanguageid ){
  107680. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  107681. }
  107682. sqlite3_result_int(pCtx, iLangid);
  107683. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  107684. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  107685. }
  107686. }
  107687. }
  107688. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  107689. return rc;
  107690. }
  107691. /*
  107692. ** This function is the implementation of the xUpdate callback used by
  107693. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  107694. ** inserted, updated or deleted.
  107695. */
  107696. static int fts3UpdateMethod(
  107697. sqlite3_vtab *pVtab, /* Virtual table handle */
  107698. int nArg, /* Size of argument array */
  107699. sqlite3_value **apVal, /* Array of arguments */
  107700. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  107701. ){
  107702. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  107703. }
  107704. /*
  107705. ** Implementation of xSync() method. Flush the contents of the pending-terms
  107706. ** hash-table to the database.
  107707. */
  107708. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  107709. /* Following an incremental-merge operation, assuming that the input
  107710. ** segments are not completely consumed (the usual case), they are updated
  107711. ** in place to remove the entries that have already been merged. This
  107712. ** involves updating the leaf block that contains the smallest unmerged
  107713. ** entry and each block (if any) between the leaf and the root node. So
  107714. ** if the height of the input segment b-trees is N, and input segments
  107715. ** are merged eight at a time, updating the input segments at the end
  107716. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  107717. ** small - often between 0 and 2. So the overhead of the incremental
  107718. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  107719. ** dwarfing the actual productive work accomplished, the incremental merge
  107720. ** is only attempted if it will write at least 64 leaf blocks. Hence
  107721. ** nMinMerge.
  107722. **
  107723. ** Of course, updating the input segments also involves deleting a bunch
  107724. ** of blocks from the segments table. But this is not considered overhead
  107725. ** as it would also be required by a crisis-merge that used the same input
  107726. ** segments.
  107727. */
  107728. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  107729. Fts3Table *p = (Fts3Table*)pVtab;
  107730. int rc = sqlite3Fts3PendingTermsFlush(p);
  107731. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  107732. int mxLevel = 0; /* Maximum relative level value in db */
  107733. int A; /* Incr-merge parameter A */
  107734. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  107735. assert( rc==SQLITE_OK || mxLevel==0 );
  107736. A = p->nLeafAdd * mxLevel;
  107737. A += (A/2);
  107738. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  107739. }
  107740. sqlite3Fts3SegmentsClose(p);
  107741. return rc;
  107742. }
  107743. /*
  107744. ** Implementation of xBegin() method. This is a no-op.
  107745. */
  107746. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  107747. Fts3Table *p = (Fts3Table*)pVtab;
  107748. UNUSED_PARAMETER(pVtab);
  107749. assert( p->pSegments==0 );
  107750. assert( p->nPendingData==0 );
  107751. assert( p->inTransaction!=1 );
  107752. TESTONLY( p->inTransaction = 1 );
  107753. TESTONLY( p->mxSavepoint = -1; );
  107754. p->nLeafAdd = 0;
  107755. return SQLITE_OK;
  107756. }
  107757. /*
  107758. ** Implementation of xCommit() method. This is a no-op. The contents of
  107759. ** the pending-terms hash-table have already been flushed into the database
  107760. ** by fts3SyncMethod().
  107761. */
  107762. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  107763. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  107764. UNUSED_PARAMETER(pVtab);
  107765. assert( p->nPendingData==0 );
  107766. assert( p->inTransaction!=0 );
  107767. assert( p->pSegments==0 );
  107768. TESTONLY( p->inTransaction = 0 );
  107769. TESTONLY( p->mxSavepoint = -1; );
  107770. return SQLITE_OK;
  107771. }
  107772. /*
  107773. ** Implementation of xRollback(). Discard the contents of the pending-terms
  107774. ** hash-table. Any changes made to the database are reverted by SQLite.
  107775. */
  107776. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  107777. Fts3Table *p = (Fts3Table*)pVtab;
  107778. sqlite3Fts3PendingTermsClear(p);
  107779. assert( p->inTransaction!=0 );
  107780. TESTONLY( p->inTransaction = 0 );
  107781. TESTONLY( p->mxSavepoint = -1; );
  107782. return SQLITE_OK;
  107783. }
  107784. /*
  107785. ** When called, *ppPoslist must point to the byte immediately following the
  107786. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  107787. ** moves *ppPoslist so that it instead points to the first byte of the
  107788. ** same position list.
  107789. */
  107790. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  107791. char *p = &(*ppPoslist)[-2];
  107792. char c = 0;
  107793. while( p>pStart && (c=*p--)==0 );
  107794. while( p>pStart && (*p & 0x80) | c ){
  107795. c = *p--;
  107796. }
  107797. if( p>pStart ){ p = &p[2]; }
  107798. while( *p++&0x80 );
  107799. *ppPoslist = p;
  107800. }
  107801. /*
  107802. ** Helper function used by the implementation of the overloaded snippet(),
  107803. ** offsets() and optimize() SQL functions.
  107804. **
  107805. ** If the value passed as the third argument is a blob of size
  107806. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  107807. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  107808. ** message is written to context pContext and SQLITE_ERROR returned. The
  107809. ** string passed via zFunc is used as part of the error message.
  107810. */
  107811. static int fts3FunctionArg(
  107812. sqlite3_context *pContext, /* SQL function call context */
  107813. const char *zFunc, /* Function name */
  107814. sqlite3_value *pVal, /* argv[0] passed to function */
  107815. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  107816. ){
  107817. Fts3Cursor *pRet;
  107818. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  107819. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  107820. ){
  107821. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  107822. sqlite3_result_error(pContext, zErr, -1);
  107823. sqlite3_free(zErr);
  107824. return SQLITE_ERROR;
  107825. }
  107826. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  107827. *ppCsr = pRet;
  107828. return SQLITE_OK;
  107829. }
  107830. /*
  107831. ** Implementation of the snippet() function for FTS3
  107832. */
  107833. static void fts3SnippetFunc(
  107834. sqlite3_context *pContext, /* SQLite function call context */
  107835. int nVal, /* Size of apVal[] array */
  107836. sqlite3_value **apVal /* Array of arguments */
  107837. ){
  107838. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107839. const char *zStart = "<b>";
  107840. const char *zEnd = "</b>";
  107841. const char *zEllipsis = "<b>...</b>";
  107842. int iCol = -1;
  107843. int nToken = 15; /* Default number of tokens in snippet */
  107844. /* There must be at least one argument passed to this function (otherwise
  107845. ** the non-overloaded version would have been called instead of this one).
  107846. */
  107847. assert( nVal>=1 );
  107848. if( nVal>6 ){
  107849. sqlite3_result_error(pContext,
  107850. "wrong number of arguments to function snippet()", -1);
  107851. return;
  107852. }
  107853. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  107854. switch( nVal ){
  107855. case 6: nToken = sqlite3_value_int(apVal[5]);
  107856. case 5: iCol = sqlite3_value_int(apVal[4]);
  107857. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  107858. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  107859. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  107860. }
  107861. if( !zEllipsis || !zEnd || !zStart ){
  107862. sqlite3_result_error_nomem(pContext);
  107863. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  107864. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  107865. }
  107866. }
  107867. /*
  107868. ** Implementation of the offsets() function for FTS3
  107869. */
  107870. static void fts3OffsetsFunc(
  107871. sqlite3_context *pContext, /* SQLite function call context */
  107872. int nVal, /* Size of argument array */
  107873. sqlite3_value **apVal /* Array of arguments */
  107874. ){
  107875. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107876. UNUSED_PARAMETER(nVal);
  107877. assert( nVal==1 );
  107878. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  107879. assert( pCsr );
  107880. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  107881. sqlite3Fts3Offsets(pContext, pCsr);
  107882. }
  107883. }
  107884. /*
  107885. ** Implementation of the special optimize() function for FTS3. This
  107886. ** function merges all segments in the database to a single segment.
  107887. ** Example usage is:
  107888. **
  107889. ** SELECT optimize(t) FROM t LIMIT 1;
  107890. **
  107891. ** where 't' is the name of an FTS3 table.
  107892. */
  107893. static void fts3OptimizeFunc(
  107894. sqlite3_context *pContext, /* SQLite function call context */
  107895. int nVal, /* Size of argument array */
  107896. sqlite3_value **apVal /* Array of arguments */
  107897. ){
  107898. int rc; /* Return code */
  107899. Fts3Table *p; /* Virtual table handle */
  107900. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  107901. UNUSED_PARAMETER(nVal);
  107902. assert( nVal==1 );
  107903. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  107904. p = (Fts3Table *)pCursor->base.pVtab;
  107905. assert( p );
  107906. rc = sqlite3Fts3Optimize(p);
  107907. switch( rc ){
  107908. case SQLITE_OK:
  107909. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  107910. break;
  107911. case SQLITE_DONE:
  107912. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  107913. break;
  107914. default:
  107915. sqlite3_result_error_code(pContext, rc);
  107916. break;
  107917. }
  107918. }
  107919. /*
  107920. ** Implementation of the matchinfo() function for FTS3
  107921. */
  107922. static void fts3MatchinfoFunc(
  107923. sqlite3_context *pContext, /* SQLite function call context */
  107924. int nVal, /* Size of argument array */
  107925. sqlite3_value **apVal /* Array of arguments */
  107926. ){
  107927. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107928. assert( nVal==1 || nVal==2 );
  107929. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  107930. const char *zArg = 0;
  107931. if( nVal>1 ){
  107932. zArg = (const char *)sqlite3_value_text(apVal[1]);
  107933. }
  107934. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  107935. }
  107936. }
  107937. /*
  107938. ** This routine implements the xFindFunction method for the FTS3
  107939. ** virtual table.
  107940. */
  107941. static int fts3FindFunctionMethod(
  107942. sqlite3_vtab *pVtab, /* Virtual table handle */
  107943. int nArg, /* Number of SQL function arguments */
  107944. const char *zName, /* Name of SQL function */
  107945. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  107946. void **ppArg /* Unused */
  107947. ){
  107948. struct Overloaded {
  107949. const char *zName;
  107950. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  107951. } aOverload[] = {
  107952. { "snippet", fts3SnippetFunc },
  107953. { "offsets", fts3OffsetsFunc },
  107954. { "optimize", fts3OptimizeFunc },
  107955. { "matchinfo", fts3MatchinfoFunc },
  107956. };
  107957. int i; /* Iterator variable */
  107958. UNUSED_PARAMETER(pVtab);
  107959. UNUSED_PARAMETER(nArg);
  107960. UNUSED_PARAMETER(ppArg);
  107961. for(i=0; i<SizeofArray(aOverload); i++){
  107962. if( strcmp(zName, aOverload[i].zName)==0 ){
  107963. *pxFunc = aOverload[i].xFunc;
  107964. return 1;
  107965. }
  107966. }
  107967. /* No function of the specified name was found. Return 0. */
  107968. return 0;
  107969. }
  107970. /*
  107971. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  107972. */
  107973. static int fts3RenameMethod(
  107974. sqlite3_vtab *pVtab, /* Virtual table handle */
  107975. const char *zName /* New name of table */
  107976. ){
  107977. Fts3Table *p = (Fts3Table *)pVtab;
  107978. sqlite3 *db = p->db; /* Database connection */
  107979. int rc; /* Return Code */
  107980. /* As it happens, the pending terms table is always empty here. This is
  107981. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  107982. ** always opens a savepoint transaction. And the xSavepoint() method
  107983. ** flushes the pending terms table. But leave the (no-op) call to
  107984. ** PendingTermsFlush() in in case that changes.
  107985. */
  107986. assert( p->nPendingData==0 );
  107987. rc = sqlite3Fts3PendingTermsFlush(p);
  107988. if( p->zContentTbl==0 ){
  107989. fts3DbExec(&rc, db,
  107990. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  107991. p->zDb, p->zName, zName
  107992. );
  107993. }
  107994. if( p->bHasDocsize ){
  107995. fts3DbExec(&rc, db,
  107996. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  107997. p->zDb, p->zName, zName
  107998. );
  107999. }
  108000. if( p->bHasStat ){
  108001. fts3DbExec(&rc, db,
  108002. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  108003. p->zDb, p->zName, zName
  108004. );
  108005. }
  108006. fts3DbExec(&rc, db,
  108007. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  108008. p->zDb, p->zName, zName
  108009. );
  108010. fts3DbExec(&rc, db,
  108011. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  108012. p->zDb, p->zName, zName
  108013. );
  108014. return rc;
  108015. }
  108016. /*
  108017. ** The xSavepoint() method.
  108018. **
  108019. ** Flush the contents of the pending-terms table to disk.
  108020. */
  108021. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108022. int rc = SQLITE_OK;
  108023. UNUSED_PARAMETER(iSavepoint);
  108024. assert( ((Fts3Table *)pVtab)->inTransaction );
  108025. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  108026. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  108027. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  108028. rc = fts3SyncMethod(pVtab);
  108029. }
  108030. return rc;
  108031. }
  108032. /*
  108033. ** The xRelease() method.
  108034. **
  108035. ** This is a no-op.
  108036. */
  108037. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108038. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  108039. UNUSED_PARAMETER(iSavepoint);
  108040. UNUSED_PARAMETER(pVtab);
  108041. assert( p->inTransaction );
  108042. assert( p->mxSavepoint >= iSavepoint );
  108043. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  108044. return SQLITE_OK;
  108045. }
  108046. /*
  108047. ** The xRollbackTo() method.
  108048. **
  108049. ** Discard the contents of the pending terms table.
  108050. */
  108051. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108052. Fts3Table *p = (Fts3Table*)pVtab;
  108053. UNUSED_PARAMETER(iSavepoint);
  108054. assert( p->inTransaction );
  108055. assert( p->mxSavepoint >= iSavepoint );
  108056. TESTONLY( p->mxSavepoint = iSavepoint );
  108057. sqlite3Fts3PendingTermsClear(p);
  108058. return SQLITE_OK;
  108059. }
  108060. static const sqlite3_module fts3Module = {
  108061. /* iVersion */ 2,
  108062. /* xCreate */ fts3CreateMethod,
  108063. /* xConnect */ fts3ConnectMethod,
  108064. /* xBestIndex */ fts3BestIndexMethod,
  108065. /* xDisconnect */ fts3DisconnectMethod,
  108066. /* xDestroy */ fts3DestroyMethod,
  108067. /* xOpen */ fts3OpenMethod,
  108068. /* xClose */ fts3CloseMethod,
  108069. /* xFilter */ fts3FilterMethod,
  108070. /* xNext */ fts3NextMethod,
  108071. /* xEof */ fts3EofMethod,
  108072. /* xColumn */ fts3ColumnMethod,
  108073. /* xRowid */ fts3RowidMethod,
  108074. /* xUpdate */ fts3UpdateMethod,
  108075. /* xBegin */ fts3BeginMethod,
  108076. /* xSync */ fts3SyncMethod,
  108077. /* xCommit */ fts3CommitMethod,
  108078. /* xRollback */ fts3RollbackMethod,
  108079. /* xFindFunction */ fts3FindFunctionMethod,
  108080. /* xRename */ fts3RenameMethod,
  108081. /* xSavepoint */ fts3SavepointMethod,
  108082. /* xRelease */ fts3ReleaseMethod,
  108083. /* xRollbackTo */ fts3RollbackToMethod,
  108084. };
  108085. /*
  108086. ** This function is registered as the module destructor (called when an
  108087. ** FTS3 enabled database connection is closed). It frees the memory
  108088. ** allocated for the tokenizer hash table.
  108089. */
  108090. static void hashDestroy(void *p){
  108091. Fts3Hash *pHash = (Fts3Hash *)p;
  108092. sqlite3Fts3HashClear(pHash);
  108093. sqlite3_free(pHash);
  108094. }
  108095. /*
  108096. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  108097. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  108098. ** respectively. The following three forward declarations are for functions
  108099. ** declared in these files used to retrieve the respective implementations.
  108100. **
  108101. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  108102. ** to by the argument to point to the "simple" tokenizer implementation.
  108103. ** And so on.
  108104. */
  108105. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108106. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108107. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108108. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  108109. #endif
  108110. #ifdef SQLITE_ENABLE_ICU
  108111. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108112. #endif
  108113. /*
  108114. ** Initialize the fts3 extension. If this extension is built as part
  108115. ** of the sqlite library, then this function is called directly by
  108116. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  108117. ** function is called by the sqlite3_extension_init() entry point.
  108118. */
  108119. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  108120. int rc = SQLITE_OK;
  108121. Fts3Hash *pHash = 0;
  108122. const sqlite3_tokenizer_module *pSimple = 0;
  108123. const sqlite3_tokenizer_module *pPorter = 0;
  108124. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108125. const sqlite3_tokenizer_module *pUnicode = 0;
  108126. #endif
  108127. #ifdef SQLITE_ENABLE_ICU
  108128. const sqlite3_tokenizer_module *pIcu = 0;
  108129. sqlite3Fts3IcuTokenizerModule(&pIcu);
  108130. #endif
  108131. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108132. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  108133. #endif
  108134. #ifdef SQLITE_TEST
  108135. rc = sqlite3Fts3InitTerm(db);
  108136. if( rc!=SQLITE_OK ) return rc;
  108137. #endif
  108138. rc = sqlite3Fts3InitAux(db);
  108139. if( rc!=SQLITE_OK ) return rc;
  108140. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  108141. sqlite3Fts3PorterTokenizerModule(&pPorter);
  108142. /* Allocate and initialize the hash-table used to store tokenizers. */
  108143. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  108144. if( !pHash ){
  108145. rc = SQLITE_NOMEM;
  108146. }else{
  108147. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  108148. }
  108149. /* Load the built-in tokenizers into the hash table */
  108150. if( rc==SQLITE_OK ){
  108151. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  108152. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  108153. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108154. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  108155. #endif
  108156. #ifdef SQLITE_ENABLE_ICU
  108157. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  108158. #endif
  108159. ){
  108160. rc = SQLITE_NOMEM;
  108161. }
  108162. }
  108163. #ifdef SQLITE_TEST
  108164. if( rc==SQLITE_OK ){
  108165. rc = sqlite3Fts3ExprInitTestInterface(db);
  108166. }
  108167. #endif
  108168. /* Create the virtual table wrapper around the hash-table and overload
  108169. ** the two scalar functions. If this is successful, register the
  108170. ** module with sqlite.
  108171. */
  108172. if( SQLITE_OK==rc
  108173. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  108174. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  108175. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  108176. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  108177. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  108178. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  108179. ){
  108180. rc = sqlite3_create_module_v2(
  108181. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  108182. );
  108183. if( rc==SQLITE_OK ){
  108184. rc = sqlite3_create_module_v2(
  108185. db, "fts4", &fts3Module, (void *)pHash, 0
  108186. );
  108187. }
  108188. if( rc==SQLITE_OK ){
  108189. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  108190. }
  108191. return rc;
  108192. }
  108193. /* An error has occurred. Delete the hash table and return the error code. */
  108194. assert( rc!=SQLITE_OK );
  108195. if( pHash ){
  108196. sqlite3Fts3HashClear(pHash);
  108197. sqlite3_free(pHash);
  108198. }
  108199. return rc;
  108200. }
  108201. /*
  108202. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  108203. ** by pExpr.
  108204. **
  108205. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  108206. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  108207. ** Fts3SegReader objects internally to provide an interface to seek or scan
  108208. ** within the union of all segments of a b-tree. Hence the name.
  108209. **
  108210. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  108211. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  108212. ** there exists prefix b-tree of the right length) then it may be traversed
  108213. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  108214. ** doclist and then traversed.
  108215. */
  108216. static void fts3EvalAllocateReaders(
  108217. Fts3Cursor *pCsr, /* FTS cursor handle */
  108218. Fts3Expr *pExpr, /* Allocate readers for this expression */
  108219. int *pnToken, /* OUT: Total number of tokens in phrase. */
  108220. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  108221. int *pRc /* IN/OUT: Error code */
  108222. ){
  108223. if( pExpr && SQLITE_OK==*pRc ){
  108224. if( pExpr->eType==FTSQUERY_PHRASE ){
  108225. int i;
  108226. int nToken = pExpr->pPhrase->nToken;
  108227. *pnToken += nToken;
  108228. for(i=0; i<nToken; i++){
  108229. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  108230. int rc = fts3TermSegReaderCursor(pCsr,
  108231. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  108232. );
  108233. if( rc!=SQLITE_OK ){
  108234. *pRc = rc;
  108235. return;
  108236. }
  108237. }
  108238. assert( pExpr->pPhrase->iDoclistToken==0 );
  108239. pExpr->pPhrase->iDoclistToken = -1;
  108240. }else{
  108241. *pnOr += (pExpr->eType==FTSQUERY_OR);
  108242. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  108243. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  108244. }
  108245. }
  108246. }
  108247. /*
  108248. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  108249. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  108250. **
  108251. ** This function assumes that pList points to a buffer allocated using
  108252. ** sqlite3_malloc(). This function takes responsibility for eventually
  108253. ** freeing the buffer.
  108254. */
  108255. static void fts3EvalPhraseMergeToken(
  108256. Fts3Table *pTab, /* FTS Table pointer */
  108257. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  108258. int iToken, /* Token pList/nList corresponds to */
  108259. char *pList, /* Pointer to doclist */
  108260. int nList /* Number of bytes in pList */
  108261. ){
  108262. assert( iToken!=p->iDoclistToken );
  108263. if( pList==0 ){
  108264. sqlite3_free(p->doclist.aAll);
  108265. p->doclist.aAll = 0;
  108266. p->doclist.nAll = 0;
  108267. }
  108268. else if( p->iDoclistToken<0 ){
  108269. p->doclist.aAll = pList;
  108270. p->doclist.nAll = nList;
  108271. }
  108272. else if( p->doclist.aAll==0 ){
  108273. sqlite3_free(pList);
  108274. }
  108275. else {
  108276. char *pLeft;
  108277. char *pRight;
  108278. int nLeft;
  108279. int nRight;
  108280. int nDiff;
  108281. if( p->iDoclistToken<iToken ){
  108282. pLeft = p->doclist.aAll;
  108283. nLeft = p->doclist.nAll;
  108284. pRight = pList;
  108285. nRight = nList;
  108286. nDiff = iToken - p->iDoclistToken;
  108287. }else{
  108288. pRight = p->doclist.aAll;
  108289. nRight = p->doclist.nAll;
  108290. pLeft = pList;
  108291. nLeft = nList;
  108292. nDiff = p->iDoclistToken - iToken;
  108293. }
  108294. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  108295. sqlite3_free(pLeft);
  108296. p->doclist.aAll = pRight;
  108297. p->doclist.nAll = nRight;
  108298. }
  108299. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  108300. }
  108301. /*
  108302. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  108303. ** does not take deferred tokens into account.
  108304. **
  108305. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108306. */
  108307. static int fts3EvalPhraseLoad(
  108308. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108309. Fts3Phrase *p /* Phrase object */
  108310. ){
  108311. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108312. int iToken;
  108313. int rc = SQLITE_OK;
  108314. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  108315. Fts3PhraseToken *pToken = &p->aToken[iToken];
  108316. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  108317. if( pToken->pSegcsr ){
  108318. int nThis = 0;
  108319. char *pThis = 0;
  108320. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  108321. if( rc==SQLITE_OK ){
  108322. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  108323. }
  108324. }
  108325. assert( pToken->pSegcsr==0 );
  108326. }
  108327. return rc;
  108328. }
  108329. /*
  108330. ** This function is called on each phrase after the position lists for
  108331. ** any deferred tokens have been loaded into memory. It updates the phrases
  108332. ** current position list to include only those positions that are really
  108333. ** instances of the phrase (after considering deferred tokens). If this
  108334. ** means that the phrase does not appear in the current row, doclist.pList
  108335. ** and doclist.nList are both zeroed.
  108336. **
  108337. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108338. */
  108339. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  108340. int iToken; /* Used to iterate through phrase tokens */
  108341. char *aPoslist = 0; /* Position list for deferred tokens */
  108342. int nPoslist = 0; /* Number of bytes in aPoslist */
  108343. int iPrev = -1; /* Token number of previous deferred token */
  108344. assert( pPhrase->doclist.bFreeList==0 );
  108345. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  108346. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  108347. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  108348. if( pDeferred ){
  108349. char *pList;
  108350. int nList;
  108351. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  108352. if( rc!=SQLITE_OK ) return rc;
  108353. if( pList==0 ){
  108354. sqlite3_free(aPoslist);
  108355. pPhrase->doclist.pList = 0;
  108356. pPhrase->doclist.nList = 0;
  108357. return SQLITE_OK;
  108358. }else if( aPoslist==0 ){
  108359. aPoslist = pList;
  108360. nPoslist = nList;
  108361. }else{
  108362. char *aOut = pList;
  108363. char *p1 = aPoslist;
  108364. char *p2 = aOut;
  108365. assert( iPrev>=0 );
  108366. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  108367. sqlite3_free(aPoslist);
  108368. aPoslist = pList;
  108369. nPoslist = (int)(aOut - aPoslist);
  108370. if( nPoslist==0 ){
  108371. sqlite3_free(aPoslist);
  108372. pPhrase->doclist.pList = 0;
  108373. pPhrase->doclist.nList = 0;
  108374. return SQLITE_OK;
  108375. }
  108376. }
  108377. iPrev = iToken;
  108378. }
  108379. }
  108380. if( iPrev>=0 ){
  108381. int nMaxUndeferred = pPhrase->iDoclistToken;
  108382. if( nMaxUndeferred<0 ){
  108383. pPhrase->doclist.pList = aPoslist;
  108384. pPhrase->doclist.nList = nPoslist;
  108385. pPhrase->doclist.iDocid = pCsr->iPrevId;
  108386. pPhrase->doclist.bFreeList = 1;
  108387. }else{
  108388. int nDistance;
  108389. char *p1;
  108390. char *p2;
  108391. char *aOut;
  108392. if( nMaxUndeferred>iPrev ){
  108393. p1 = aPoslist;
  108394. p2 = pPhrase->doclist.pList;
  108395. nDistance = nMaxUndeferred - iPrev;
  108396. }else{
  108397. p1 = pPhrase->doclist.pList;
  108398. p2 = aPoslist;
  108399. nDistance = iPrev - nMaxUndeferred;
  108400. }
  108401. aOut = (char *)sqlite3_malloc(nPoslist+8);
  108402. if( !aOut ){
  108403. sqlite3_free(aPoslist);
  108404. return SQLITE_NOMEM;
  108405. }
  108406. pPhrase->doclist.pList = aOut;
  108407. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  108408. pPhrase->doclist.bFreeList = 1;
  108409. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  108410. }else{
  108411. sqlite3_free(aOut);
  108412. pPhrase->doclist.pList = 0;
  108413. pPhrase->doclist.nList = 0;
  108414. }
  108415. sqlite3_free(aPoslist);
  108416. }
  108417. }
  108418. return SQLITE_OK;
  108419. }
  108420. /*
  108421. ** Maximum number of tokens a phrase may have to be considered for the
  108422. ** incremental doclists strategy.
  108423. */
  108424. #define MAX_INCR_PHRASE_TOKENS 4
  108425. /*
  108426. ** This function is called for each Fts3Phrase in a full-text query
  108427. ** expression to initialize the mechanism for returning rows. Once this
  108428. ** function has been called successfully on an Fts3Phrase, it may be
  108429. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  108430. **
  108431. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  108432. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  108433. ** memory within this call.
  108434. **
  108435. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108436. */
  108437. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  108438. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108439. int rc = SQLITE_OK; /* Error code */
  108440. int i;
  108441. /* Determine if doclists may be loaded from disk incrementally. This is
  108442. ** possible if the bOptOk argument is true, the FTS doclists will be
  108443. ** scanned in forward order, and the phrase consists of
  108444. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  108445. ** tokens or prefix tokens that cannot use a prefix-index. */
  108446. int bHaveIncr = 0;
  108447. int bIncrOk = (bOptOk
  108448. && pCsr->bDesc==pTab->bDescIdx
  108449. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  108450. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  108451. #ifdef SQLITE_TEST
  108452. && pTab->bNoIncrDoclist==0
  108453. #endif
  108454. );
  108455. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  108456. Fts3PhraseToken *pToken = &p->aToken[i];
  108457. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  108458. bIncrOk = 0;
  108459. }
  108460. if( pToken->pSegcsr ) bHaveIncr = 1;
  108461. }
  108462. if( bIncrOk && bHaveIncr ){
  108463. /* Use the incremental approach. */
  108464. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  108465. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  108466. Fts3PhraseToken *pToken = &p->aToken[i];
  108467. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  108468. if( pSegcsr ){
  108469. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  108470. }
  108471. }
  108472. p->bIncr = 1;
  108473. }else{
  108474. /* Load the full doclist for the phrase into memory. */
  108475. rc = fts3EvalPhraseLoad(pCsr, p);
  108476. p->bIncr = 0;
  108477. }
  108478. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  108479. return rc;
  108480. }
  108481. /*
  108482. ** This function is used to iterate backwards (from the end to start)
  108483. ** through doclists. It is used by this module to iterate through phrase
  108484. ** doclists in reverse and by the fts3_write.c module to iterate through
  108485. ** pending-terms lists when writing to databases with "order=desc".
  108486. **
  108487. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  108488. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  108489. ** function iterates from the end of the doclist to the beginning.
  108490. */
  108491. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  108492. int bDescIdx, /* True if the doclist is desc */
  108493. char *aDoclist, /* Pointer to entire doclist */
  108494. int nDoclist, /* Length of aDoclist in bytes */
  108495. char **ppIter, /* IN/OUT: Iterator pointer */
  108496. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  108497. int *pnList, /* OUT: List length pointer */
  108498. u8 *pbEof /* OUT: End-of-file flag */
  108499. ){
  108500. char *p = *ppIter;
  108501. assert( nDoclist>0 );
  108502. assert( *pbEof==0 );
  108503. assert( p || *piDocid==0 );
  108504. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  108505. if( p==0 ){
  108506. sqlite3_int64 iDocid = 0;
  108507. char *pNext = 0;
  108508. char *pDocid = aDoclist;
  108509. char *pEnd = &aDoclist[nDoclist];
  108510. int iMul = 1;
  108511. while( pDocid<pEnd ){
  108512. sqlite3_int64 iDelta;
  108513. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  108514. iDocid += (iMul * iDelta);
  108515. pNext = pDocid;
  108516. fts3PoslistCopy(0, &pDocid);
  108517. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  108518. iMul = (bDescIdx ? -1 : 1);
  108519. }
  108520. *pnList = (int)(pEnd - pNext);
  108521. *ppIter = pNext;
  108522. *piDocid = iDocid;
  108523. }else{
  108524. int iMul = (bDescIdx ? -1 : 1);
  108525. sqlite3_int64 iDelta;
  108526. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  108527. *piDocid -= (iMul * iDelta);
  108528. if( p==aDoclist ){
  108529. *pbEof = 1;
  108530. }else{
  108531. char *pSave = p;
  108532. fts3ReversePoslist(aDoclist, &p);
  108533. *pnList = (int)(pSave - p);
  108534. }
  108535. *ppIter = p;
  108536. }
  108537. }
  108538. /*
  108539. ** Iterate forwards through a doclist.
  108540. */
  108541. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  108542. int bDescIdx, /* True if the doclist is desc */
  108543. char *aDoclist, /* Pointer to entire doclist */
  108544. int nDoclist, /* Length of aDoclist in bytes */
  108545. char **ppIter, /* IN/OUT: Iterator pointer */
  108546. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  108547. u8 *pbEof /* OUT: End-of-file flag */
  108548. ){
  108549. char *p = *ppIter;
  108550. assert( nDoclist>0 );
  108551. assert( *pbEof==0 );
  108552. assert( p || *piDocid==0 );
  108553. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  108554. if( p==0 ){
  108555. p = aDoclist;
  108556. p += sqlite3Fts3GetVarint(p, piDocid);
  108557. }else{
  108558. fts3PoslistCopy(0, &p);
  108559. if( p>=&aDoclist[nDoclist] ){
  108560. *pbEof = 1;
  108561. }else{
  108562. sqlite3_int64 iVar;
  108563. p += sqlite3Fts3GetVarint(p, &iVar);
  108564. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  108565. }
  108566. }
  108567. *ppIter = p;
  108568. }
  108569. /*
  108570. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  108571. ** to true if EOF is reached.
  108572. */
  108573. static void fts3EvalDlPhraseNext(
  108574. Fts3Table *pTab,
  108575. Fts3Doclist *pDL,
  108576. u8 *pbEof
  108577. ){
  108578. char *pIter; /* Used to iterate through aAll */
  108579. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  108580. if( pDL->pNextDocid ){
  108581. pIter = pDL->pNextDocid;
  108582. }else{
  108583. pIter = pDL->aAll;
  108584. }
  108585. if( pIter>=pEnd ){
  108586. /* We have already reached the end of this doclist. EOF. */
  108587. *pbEof = 1;
  108588. }else{
  108589. sqlite3_int64 iDelta;
  108590. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  108591. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  108592. pDL->iDocid += iDelta;
  108593. }else{
  108594. pDL->iDocid -= iDelta;
  108595. }
  108596. pDL->pList = pIter;
  108597. fts3PoslistCopy(0, &pIter);
  108598. pDL->nList = (int)(pIter - pDL->pList);
  108599. /* pIter now points just past the 0x00 that terminates the position-
  108600. ** list for document pDL->iDocid. However, if this position-list was
  108601. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  108602. ** point to the start of the next docid value. The following line deals
  108603. ** with this case by advancing pIter past the zero-padding added by
  108604. ** fts3EvalNearTrim(). */
  108605. while( pIter<pEnd && *pIter==0 ) pIter++;
  108606. pDL->pNextDocid = pIter;
  108607. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  108608. *pbEof = 0;
  108609. }
  108610. }
  108611. /*
  108612. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  108613. */
  108614. typedef struct TokenDoclist TokenDoclist;
  108615. struct TokenDoclist {
  108616. int bIgnore;
  108617. sqlite3_int64 iDocid;
  108618. char *pList;
  108619. int nList;
  108620. };
  108621. /*
  108622. ** Token pToken is an incrementally loaded token that is part of a
  108623. ** multi-token phrase. Advance it to the next matching document in the
  108624. ** database and populate output variable *p with the details of the new
  108625. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  108626. **
  108627. ** If an error occurs, return an SQLite error code. Otherwise, return
  108628. ** SQLITE_OK.
  108629. */
  108630. static int incrPhraseTokenNext(
  108631. Fts3Table *pTab, /* Virtual table handle */
  108632. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  108633. int iToken, /* Specific token to advance */
  108634. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  108635. u8 *pbEof /* OUT: True if iterator is at EOF */
  108636. ){
  108637. int rc = SQLITE_OK;
  108638. if( pPhrase->iDoclistToken==iToken ){
  108639. assert( p->bIgnore==0 );
  108640. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  108641. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  108642. p->pList = pPhrase->doclist.pList;
  108643. p->nList = pPhrase->doclist.nList;
  108644. p->iDocid = pPhrase->doclist.iDocid;
  108645. }else{
  108646. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  108647. assert( pToken->pDeferred==0 );
  108648. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  108649. if( pToken->pSegcsr ){
  108650. assert( p->bIgnore==0 );
  108651. rc = sqlite3Fts3MsrIncrNext(
  108652. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  108653. );
  108654. if( p->pList==0 ) *pbEof = 1;
  108655. }else{
  108656. p->bIgnore = 1;
  108657. }
  108658. }
  108659. return rc;
  108660. }
  108661. /*
  108662. ** The phrase iterator passed as the second argument:
  108663. **
  108664. ** * features at least one token that uses an incremental doclist, and
  108665. **
  108666. ** * does not contain any deferred tokens.
  108667. **
  108668. ** Advance it to the next matching documnent in the database and populate
  108669. ** the Fts3Doclist.pList and nList fields.
  108670. **
  108671. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  108672. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  108673. ** successfully advanced, *pbEof is set to 0.
  108674. **
  108675. ** If an error occurs, return an SQLite error code. Otherwise, return
  108676. ** SQLITE_OK.
  108677. */
  108678. static int fts3EvalIncrPhraseNext(
  108679. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108680. Fts3Phrase *p, /* Phrase object to advance to next docid */
  108681. u8 *pbEof /* OUT: Set to 1 if EOF */
  108682. ){
  108683. int rc = SQLITE_OK;
  108684. Fts3Doclist *pDL = &p->doclist;
  108685. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108686. u8 bEof = 0;
  108687. /* This is only called if it is guaranteed that the phrase has at least
  108688. ** one incremental token. In which case the bIncr flag is set. */
  108689. assert( p->bIncr==1 );
  108690. if( p->nToken==1 && p->bIncr ){
  108691. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  108692. &pDL->iDocid, &pDL->pList, &pDL->nList
  108693. );
  108694. if( pDL->pList==0 ) bEof = 1;
  108695. }else{
  108696. int bDescDoclist = pCsr->bDesc;
  108697. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  108698. memset(a, 0, sizeof(a));
  108699. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  108700. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  108701. while( bEof==0 ){
  108702. int bMaxSet = 0;
  108703. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  108704. int i; /* Used to iterate through tokens */
  108705. /* Advance the iterator for each token in the phrase once. */
  108706. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  108707. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  108708. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  108709. iMax = a[i].iDocid;
  108710. bMaxSet = 1;
  108711. }
  108712. }
  108713. assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
  108714. assert( rc!=SQLITE_OK || bMaxSet );
  108715. /* Keep advancing iterators until they all point to the same document */
  108716. for(i=0; i<p->nToken; i++){
  108717. while( rc==SQLITE_OK && bEof==0
  108718. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  108719. ){
  108720. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  108721. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  108722. iMax = a[i].iDocid;
  108723. i = 0;
  108724. }
  108725. }
  108726. }
  108727. /* Check if the current entries really are a phrase match */
  108728. if( bEof==0 ){
  108729. int nList = 0;
  108730. int nByte = a[p->nToken-1].nList;
  108731. char *aDoclist = sqlite3_malloc(nByte+1);
  108732. if( !aDoclist ) return SQLITE_NOMEM;
  108733. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  108734. for(i=0; i<(p->nToken-1); i++){
  108735. if( a[i].bIgnore==0 ){
  108736. char *pL = a[i].pList;
  108737. char *pR = aDoclist;
  108738. char *pOut = aDoclist;
  108739. int nDist = p->nToken-1-i;
  108740. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  108741. if( res==0 ) break;
  108742. nList = (int)(pOut - aDoclist);
  108743. }
  108744. }
  108745. if( i==(p->nToken-1) ){
  108746. pDL->iDocid = iMax;
  108747. pDL->pList = aDoclist;
  108748. pDL->nList = nList;
  108749. pDL->bFreeList = 1;
  108750. break;
  108751. }
  108752. sqlite3_free(aDoclist);
  108753. }
  108754. }
  108755. }
  108756. *pbEof = bEof;
  108757. return rc;
  108758. }
  108759. /*
  108760. ** Attempt to move the phrase iterator to point to the next matching docid.
  108761. ** If an error occurs, return an SQLite error code. Otherwise, return
  108762. ** SQLITE_OK.
  108763. **
  108764. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  108765. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  108766. ** successfully advanced, *pbEof is set to 0.
  108767. */
  108768. static int fts3EvalPhraseNext(
  108769. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108770. Fts3Phrase *p, /* Phrase object to advance to next docid */
  108771. u8 *pbEof /* OUT: Set to 1 if EOF */
  108772. ){
  108773. int rc = SQLITE_OK;
  108774. Fts3Doclist *pDL = &p->doclist;
  108775. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108776. if( p->bIncr ){
  108777. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  108778. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  108779. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  108780. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  108781. );
  108782. pDL->pList = pDL->pNextDocid;
  108783. }else{
  108784. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  108785. }
  108786. return rc;
  108787. }
  108788. /*
  108789. **
  108790. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  108791. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  108792. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  108793. ** expressions for which all descendent tokens are deferred.
  108794. **
  108795. ** If parameter bOptOk is zero, then it is guaranteed that the
  108796. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  108797. ** each phrase in the expression (subject to deferred token processing).
  108798. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  108799. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  108800. **
  108801. ** If an error occurs within this function, *pRc is set to an SQLite error
  108802. ** code before returning.
  108803. */
  108804. static void fts3EvalStartReaders(
  108805. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108806. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  108807. int *pRc /* IN/OUT: Error code */
  108808. ){
  108809. if( pExpr && SQLITE_OK==*pRc ){
  108810. if( pExpr->eType==FTSQUERY_PHRASE ){
  108811. int i;
  108812. int nToken = pExpr->pPhrase->nToken;
  108813. for(i=0; i<nToken; i++){
  108814. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  108815. }
  108816. pExpr->bDeferred = (i==nToken);
  108817. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  108818. }else{
  108819. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  108820. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  108821. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  108822. }
  108823. }
  108824. }
  108825. /*
  108826. ** An array of the following structures is assembled as part of the process
  108827. ** of selecting tokens to defer before the query starts executing (as part
  108828. ** of the xFilter() method). There is one element in the array for each
  108829. ** token in the FTS expression.
  108830. **
  108831. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  108832. ** to phrases that are connected only by AND and NEAR operators (not OR or
  108833. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  108834. ** separately. The root of a tokens AND/NEAR cluster is stored in
  108835. ** Fts3TokenAndCost.pRoot.
  108836. */
  108837. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  108838. struct Fts3TokenAndCost {
  108839. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  108840. int iToken; /* Position of token in phrase */
  108841. Fts3PhraseToken *pToken; /* The token itself */
  108842. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  108843. int nOvfl; /* Number of overflow pages to load doclist */
  108844. int iCol; /* The column the token must match */
  108845. };
  108846. /*
  108847. ** This function is used to populate an allocated Fts3TokenAndCost array.
  108848. **
  108849. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  108850. ** Otherwise, if an error occurs during execution, *pRc is set to an
  108851. ** SQLite error code.
  108852. */
  108853. static void fts3EvalTokenCosts(
  108854. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108855. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  108856. Fts3Expr *pExpr, /* Expression to consider */
  108857. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  108858. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  108859. int *pRc /* IN/OUT: Error code */
  108860. ){
  108861. if( *pRc==SQLITE_OK ){
  108862. if( pExpr->eType==FTSQUERY_PHRASE ){
  108863. Fts3Phrase *pPhrase = pExpr->pPhrase;
  108864. int i;
  108865. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  108866. Fts3TokenAndCost *pTC = (*ppTC)++;
  108867. pTC->pPhrase = pPhrase;
  108868. pTC->iToken = i;
  108869. pTC->pRoot = pRoot;
  108870. pTC->pToken = &pPhrase->aToken[i];
  108871. pTC->iCol = pPhrase->iColumn;
  108872. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  108873. }
  108874. }else if( pExpr->eType!=FTSQUERY_NOT ){
  108875. assert( pExpr->eType==FTSQUERY_OR
  108876. || pExpr->eType==FTSQUERY_AND
  108877. || pExpr->eType==FTSQUERY_NEAR
  108878. );
  108879. assert( pExpr->pLeft && pExpr->pRight );
  108880. if( pExpr->eType==FTSQUERY_OR ){
  108881. pRoot = pExpr->pLeft;
  108882. **ppOr = pRoot;
  108883. (*ppOr)++;
  108884. }
  108885. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  108886. if( pExpr->eType==FTSQUERY_OR ){
  108887. pRoot = pExpr->pRight;
  108888. **ppOr = pRoot;
  108889. (*ppOr)++;
  108890. }
  108891. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  108892. }
  108893. }
  108894. }
  108895. /*
  108896. ** Determine the average document (row) size in pages. If successful,
  108897. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  108898. ** an SQLite error code.
  108899. **
  108900. ** The average document size in pages is calculated by first calculating
  108901. ** determining the average size in bytes, B. If B is less than the amount
  108902. ** of data that will fit on a single leaf page of an intkey table in
  108903. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  108904. ** the number of overflow pages consumed by a record B bytes in size.
  108905. */
  108906. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  108907. if( pCsr->nRowAvg==0 ){
  108908. /* The average document size, which is required to calculate the cost
  108909. ** of each doclist, has not yet been determined. Read the required
  108910. ** data from the %_stat table to calculate it.
  108911. **
  108912. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  108913. ** varints, where nCol is the number of columns in the FTS3 table.
  108914. ** The first varint is the number of documents currently stored in
  108915. ** the table. The following nCol varints contain the total amount of
  108916. ** data stored in all rows of each column of the table, from left
  108917. ** to right.
  108918. */
  108919. int rc;
  108920. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  108921. sqlite3_stmt *pStmt;
  108922. sqlite3_int64 nDoc = 0;
  108923. sqlite3_int64 nByte = 0;
  108924. const char *pEnd;
  108925. const char *a;
  108926. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  108927. if( rc!=SQLITE_OK ) return rc;
  108928. a = sqlite3_column_blob(pStmt, 0);
  108929. assert( a );
  108930. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  108931. a += sqlite3Fts3GetVarint(a, &nDoc);
  108932. while( a<pEnd ){
  108933. a += sqlite3Fts3GetVarint(a, &nByte);
  108934. }
  108935. if( nDoc==0 || nByte==0 ){
  108936. sqlite3_reset(pStmt);
  108937. return FTS_CORRUPT_VTAB;
  108938. }
  108939. pCsr->nDoc = nDoc;
  108940. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  108941. assert( pCsr->nRowAvg>0 );
  108942. rc = sqlite3_reset(pStmt);
  108943. if( rc!=SQLITE_OK ) return rc;
  108944. }
  108945. *pnPage = pCsr->nRowAvg;
  108946. return SQLITE_OK;
  108947. }
  108948. /*
  108949. ** This function is called to select the tokens (if any) that will be
  108950. ** deferred. The array aTC[] has already been populated when this is
  108951. ** called.
  108952. **
  108953. ** This function is called once for each AND/NEAR cluster in the
  108954. ** expression. Each invocation determines which tokens to defer within
  108955. ** the cluster with root node pRoot. See comments above the definition
  108956. ** of struct Fts3TokenAndCost for more details.
  108957. **
  108958. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  108959. ** called on each token to defer. Otherwise, an SQLite error code is
  108960. ** returned.
  108961. */
  108962. static int fts3EvalSelectDeferred(
  108963. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108964. Fts3Expr *pRoot, /* Consider tokens with this root node */
  108965. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  108966. int nTC /* Number of entries in aTC[] */
  108967. ){
  108968. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108969. int nDocSize = 0; /* Number of pages per doc loaded */
  108970. int rc = SQLITE_OK; /* Return code */
  108971. int ii; /* Iterator variable for various purposes */
  108972. int nOvfl = 0; /* Total overflow pages used by doclists */
  108973. int nToken = 0; /* Total number of tokens in cluster */
  108974. int nMinEst = 0; /* The minimum count for any phrase so far. */
  108975. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  108976. /* Tokens are never deferred for FTS tables created using the content=xxx
  108977. ** option. The reason being that it is not guaranteed that the content
  108978. ** table actually contains the same data as the index. To prevent this from
  108979. ** causing any problems, the deferred token optimization is completely
  108980. ** disabled for content=xxx tables. */
  108981. if( pTab->zContentTbl ){
  108982. return SQLITE_OK;
  108983. }
  108984. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  108985. ** associated with the tokens spill onto overflow pages, or if there is
  108986. ** only 1 token, exit early. No tokens to defer in this case. */
  108987. for(ii=0; ii<nTC; ii++){
  108988. if( aTC[ii].pRoot==pRoot ){
  108989. nOvfl += aTC[ii].nOvfl;
  108990. nToken++;
  108991. }
  108992. }
  108993. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  108994. /* Obtain the average docsize (in pages). */
  108995. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  108996. assert( rc!=SQLITE_OK || nDocSize>0 );
  108997. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  108998. ** of the number of overflow pages that will be loaded by the pager layer
  108999. ** to retrieve the entire doclist for the token from the full-text index.
  109000. ** Load the doclists for tokens that are either:
  109001. **
  109002. ** a. The cheapest token in the entire query (i.e. the one visited by the
  109003. ** first iteration of this loop), or
  109004. **
  109005. ** b. Part of a multi-token phrase.
  109006. **
  109007. ** After each token doclist is loaded, merge it with the others from the
  109008. ** same phrase and count the number of documents that the merged doclist
  109009. ** contains. Set variable "nMinEst" to the smallest number of documents in
  109010. ** any phrase doclist for which 1 or more token doclists have been loaded.
  109011. ** Let nOther be the number of other phrases for which it is certain that
  109012. ** one or more tokens will not be deferred.
  109013. **
  109014. ** Then, for each token, defer it if loading the doclist would result in
  109015. ** loading N or more overflow pages into memory, where N is computed as:
  109016. **
  109017. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  109018. */
  109019. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  109020. int iTC; /* Used to iterate through aTC[] array. */
  109021. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  109022. /* Set pTC to point to the cheapest remaining token. */
  109023. for(iTC=0; iTC<nTC; iTC++){
  109024. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  109025. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  109026. ){
  109027. pTC = &aTC[iTC];
  109028. }
  109029. }
  109030. assert( pTC );
  109031. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  109032. /* The number of overflow pages to load for this (and therefore all
  109033. ** subsequent) tokens is greater than the estimated number of pages
  109034. ** that will be loaded if all subsequent tokens are deferred.
  109035. */
  109036. Fts3PhraseToken *pToken = pTC->pToken;
  109037. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  109038. fts3SegReaderCursorFree(pToken->pSegcsr);
  109039. pToken->pSegcsr = 0;
  109040. }else{
  109041. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  109042. ** for-loop. Except, limit the value to 2^24 to prevent it from
  109043. ** overflowing the 32-bit integer it is stored in. */
  109044. if( ii<12 ) nLoad4 = nLoad4*4;
  109045. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  109046. /* Either this is the cheapest token in the entire query, or it is
  109047. ** part of a multi-token phrase. Either way, the entire doclist will
  109048. ** (eventually) be loaded into memory. It may as well be now. */
  109049. Fts3PhraseToken *pToken = pTC->pToken;
  109050. int nList = 0;
  109051. char *pList = 0;
  109052. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  109053. assert( rc==SQLITE_OK || pList==0 );
  109054. if( rc==SQLITE_OK ){
  109055. int nCount;
  109056. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  109057. nCount = fts3DoclistCountDocids(
  109058. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  109059. );
  109060. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  109061. }
  109062. }
  109063. }
  109064. pTC->pToken = 0;
  109065. }
  109066. return rc;
  109067. }
  109068. /*
  109069. ** This function is called from within the xFilter method. It initializes
  109070. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  109071. ** the results of a query, the caller does:
  109072. **
  109073. ** fts3EvalStart(pCsr);
  109074. ** while( 1 ){
  109075. ** fts3EvalNext(pCsr);
  109076. ** if( pCsr->bEof ) break;
  109077. ** ... return row pCsr->iPrevId to the caller ...
  109078. ** }
  109079. */
  109080. static int fts3EvalStart(Fts3Cursor *pCsr){
  109081. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109082. int rc = SQLITE_OK;
  109083. int nToken = 0;
  109084. int nOr = 0;
  109085. /* Allocate a MultiSegReader for each token in the expression. */
  109086. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  109087. /* Determine which, if any, tokens in the expression should be deferred. */
  109088. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  109089. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  109090. Fts3TokenAndCost *aTC;
  109091. Fts3Expr **apOr;
  109092. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  109093. sizeof(Fts3TokenAndCost) * nToken
  109094. + sizeof(Fts3Expr *) * nOr * 2
  109095. );
  109096. apOr = (Fts3Expr **)&aTC[nToken];
  109097. if( !aTC ){
  109098. rc = SQLITE_NOMEM;
  109099. }else{
  109100. int ii;
  109101. Fts3TokenAndCost *pTC = aTC;
  109102. Fts3Expr **ppOr = apOr;
  109103. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  109104. nToken = (int)(pTC-aTC);
  109105. nOr = (int)(ppOr-apOr);
  109106. if( rc==SQLITE_OK ){
  109107. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  109108. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  109109. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  109110. }
  109111. }
  109112. sqlite3_free(aTC);
  109113. }
  109114. }
  109115. #endif
  109116. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  109117. return rc;
  109118. }
  109119. /*
  109120. ** Invalidate the current position list for phrase pPhrase.
  109121. */
  109122. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  109123. if( pPhrase->doclist.bFreeList ){
  109124. sqlite3_free(pPhrase->doclist.pList);
  109125. }
  109126. pPhrase->doclist.pList = 0;
  109127. pPhrase->doclist.nList = 0;
  109128. pPhrase->doclist.bFreeList = 0;
  109129. }
  109130. /*
  109131. ** This function is called to edit the position list associated with
  109132. ** the phrase object passed as the fifth argument according to a NEAR
  109133. ** condition. For example:
  109134. **
  109135. ** abc NEAR/5 "def ghi"
  109136. **
  109137. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  109138. ** the example above). When this function is called, *paPoslist points to
  109139. ** the position list, and *pnToken is the number of phrase tokens in, the
  109140. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  109141. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  109142. ** the position list associated with phrase "abc".
  109143. **
  109144. ** All positions in the pPhrase position list that are not sufficiently
  109145. ** close to a position in the *paPoslist position list are removed. If this
  109146. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  109147. **
  109148. ** Before returning, *paPoslist is set to point to the position lsit
  109149. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  109150. ** pPhrase.
  109151. */
  109152. static int fts3EvalNearTrim(
  109153. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  109154. char *aTmp, /* Temporary space to use */
  109155. char **paPoslist, /* IN/OUT: Position list */
  109156. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  109157. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  109158. ){
  109159. int nParam1 = nNear + pPhrase->nToken;
  109160. int nParam2 = nNear + *pnToken;
  109161. int nNew;
  109162. char *p2;
  109163. char *pOut;
  109164. int res;
  109165. assert( pPhrase->doclist.pList );
  109166. p2 = pOut = pPhrase->doclist.pList;
  109167. res = fts3PoslistNearMerge(
  109168. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  109169. );
  109170. if( res ){
  109171. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  109172. assert( pPhrase->doclist.pList[nNew]=='\0' );
  109173. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  109174. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  109175. pPhrase->doclist.nList = nNew;
  109176. *paPoslist = pPhrase->doclist.pList;
  109177. *pnToken = pPhrase->nToken;
  109178. }
  109179. return res;
  109180. }
  109181. /*
  109182. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  109183. ** Otherwise, it advances the expression passed as the second argument to
  109184. ** point to the next matching row in the database. Expressions iterate through
  109185. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  109186. ** or descending if it is non-zero.
  109187. **
  109188. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  109189. ** successful, the following variables in pExpr are set:
  109190. **
  109191. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  109192. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  109193. **
  109194. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  109195. ** at EOF, then the following variables are populated with the position list
  109196. ** for the phrase for the visited row:
  109197. **
  109198. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  109199. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  109200. **
  109201. ** It says above that this function advances the expression to the next
  109202. ** matching row. This is usually true, but there are the following exceptions:
  109203. **
  109204. ** 1. Deferred tokens are not taken into account. If a phrase consists
  109205. ** entirely of deferred tokens, it is assumed to match every row in
  109206. ** the db. In this case the position-list is not populated at all.
  109207. **
  109208. ** Or, if a phrase contains one or more deferred tokens and one or
  109209. ** more non-deferred tokens, then the expression is advanced to the
  109210. ** next possible match, considering only non-deferred tokens. In other
  109211. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  109212. ** is advanced to the next row that contains an instance of "A * C",
  109213. ** where "*" may match any single token. The position list in this case
  109214. ** is populated as for "A * C" before returning.
  109215. **
  109216. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  109217. ** advanced to point to the next row that matches "x AND y".
  109218. **
  109219. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  109220. ** really a match, taking into account deferred tokens and NEAR operators.
  109221. */
  109222. static void fts3EvalNextRow(
  109223. Fts3Cursor *pCsr, /* FTS Cursor handle */
  109224. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  109225. int *pRc /* IN/OUT: Error code */
  109226. ){
  109227. if( *pRc==SQLITE_OK ){
  109228. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  109229. assert( pExpr->bEof==0 );
  109230. pExpr->bStart = 1;
  109231. switch( pExpr->eType ){
  109232. case FTSQUERY_NEAR:
  109233. case FTSQUERY_AND: {
  109234. Fts3Expr *pLeft = pExpr->pLeft;
  109235. Fts3Expr *pRight = pExpr->pRight;
  109236. assert( !pLeft->bDeferred || !pRight->bDeferred );
  109237. if( pLeft->bDeferred ){
  109238. /* LHS is entirely deferred. So we assume it matches every row.
  109239. ** Advance the RHS iterator to find the next row visited. */
  109240. fts3EvalNextRow(pCsr, pRight, pRc);
  109241. pExpr->iDocid = pRight->iDocid;
  109242. pExpr->bEof = pRight->bEof;
  109243. }else if( pRight->bDeferred ){
  109244. /* RHS is entirely deferred. So we assume it matches every row.
  109245. ** Advance the LHS iterator to find the next row visited. */
  109246. fts3EvalNextRow(pCsr, pLeft, pRc);
  109247. pExpr->iDocid = pLeft->iDocid;
  109248. pExpr->bEof = pLeft->bEof;
  109249. }else{
  109250. /* Neither the RHS or LHS are deferred. */
  109251. fts3EvalNextRow(pCsr, pLeft, pRc);
  109252. fts3EvalNextRow(pCsr, pRight, pRc);
  109253. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  109254. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109255. if( iDiff==0 ) break;
  109256. if( iDiff<0 ){
  109257. fts3EvalNextRow(pCsr, pLeft, pRc);
  109258. }else{
  109259. fts3EvalNextRow(pCsr, pRight, pRc);
  109260. }
  109261. }
  109262. pExpr->iDocid = pLeft->iDocid;
  109263. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  109264. }
  109265. break;
  109266. }
  109267. case FTSQUERY_OR: {
  109268. Fts3Expr *pLeft = pExpr->pLeft;
  109269. Fts3Expr *pRight = pExpr->pRight;
  109270. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109271. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  109272. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  109273. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  109274. fts3EvalNextRow(pCsr, pLeft, pRc);
  109275. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  109276. fts3EvalNextRow(pCsr, pRight, pRc);
  109277. }else{
  109278. fts3EvalNextRow(pCsr, pLeft, pRc);
  109279. fts3EvalNextRow(pCsr, pRight, pRc);
  109280. }
  109281. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  109282. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109283. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  109284. pExpr->iDocid = pLeft->iDocid;
  109285. }else{
  109286. pExpr->iDocid = pRight->iDocid;
  109287. }
  109288. break;
  109289. }
  109290. case FTSQUERY_NOT: {
  109291. Fts3Expr *pLeft = pExpr->pLeft;
  109292. Fts3Expr *pRight = pExpr->pRight;
  109293. if( pRight->bStart==0 ){
  109294. fts3EvalNextRow(pCsr, pRight, pRc);
  109295. assert( *pRc!=SQLITE_OK || pRight->bStart );
  109296. }
  109297. fts3EvalNextRow(pCsr, pLeft, pRc);
  109298. if( pLeft->bEof==0 ){
  109299. while( !*pRc
  109300. && !pRight->bEof
  109301. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  109302. ){
  109303. fts3EvalNextRow(pCsr, pRight, pRc);
  109304. }
  109305. }
  109306. pExpr->iDocid = pLeft->iDocid;
  109307. pExpr->bEof = pLeft->bEof;
  109308. break;
  109309. }
  109310. default: {
  109311. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109312. fts3EvalInvalidatePoslist(pPhrase);
  109313. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  109314. pExpr->iDocid = pPhrase->doclist.iDocid;
  109315. break;
  109316. }
  109317. }
  109318. }
  109319. }
  109320. /*
  109321. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  109322. ** cluster, then this function returns 1 immediately.
  109323. **
  109324. ** Otherwise, it checks if the current row really does match the NEAR
  109325. ** expression, using the data currently stored in the position lists
  109326. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  109327. **
  109328. ** If the current row is a match, the position list associated with each
  109329. ** phrase in the NEAR expression is edited in place to contain only those
  109330. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  109331. ** constraints. In this case it returns 1. If the NEAR expression does not
  109332. ** match the current row, 0 is returned. The position lists may or may not
  109333. ** be edited if 0 is returned.
  109334. */
  109335. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  109336. int res = 1;
  109337. /* The following block runs if pExpr is the root of a NEAR query.
  109338. ** For example, the query:
  109339. **
  109340. ** "w" NEAR "x" NEAR "y" NEAR "z"
  109341. **
  109342. ** which is represented in tree form as:
  109343. **
  109344. ** |
  109345. ** +--NEAR--+ <-- root of NEAR query
  109346. ** | |
  109347. ** +--NEAR--+ "z"
  109348. ** | |
  109349. ** +--NEAR--+ "y"
  109350. ** | |
  109351. ** "w" "x"
  109352. **
  109353. ** The right-hand child of a NEAR node is always a phrase. The
  109354. ** left-hand child may be either a phrase or a NEAR node. There are
  109355. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  109356. */
  109357. if( *pRc==SQLITE_OK
  109358. && pExpr->eType==FTSQUERY_NEAR
  109359. && pExpr->bEof==0
  109360. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  109361. ){
  109362. Fts3Expr *p;
  109363. int nTmp = 0; /* Bytes of temp space */
  109364. char *aTmp; /* Temp space for PoslistNearMerge() */
  109365. /* Allocate temporary working space. */
  109366. for(p=pExpr; p->pLeft; p=p->pLeft){
  109367. nTmp += p->pRight->pPhrase->doclist.nList;
  109368. }
  109369. nTmp += p->pPhrase->doclist.nList;
  109370. if( nTmp==0 ){
  109371. res = 0;
  109372. }else{
  109373. aTmp = sqlite3_malloc(nTmp*2);
  109374. if( !aTmp ){
  109375. *pRc = SQLITE_NOMEM;
  109376. res = 0;
  109377. }else{
  109378. char *aPoslist = p->pPhrase->doclist.pList;
  109379. int nToken = p->pPhrase->nToken;
  109380. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  109381. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  109382. int nNear = p->nNear;
  109383. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  109384. }
  109385. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  109386. nToken = pExpr->pRight->pPhrase->nToken;
  109387. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  109388. int nNear;
  109389. Fts3Phrase *pPhrase;
  109390. assert( p->pParent && p->pParent->pLeft==p );
  109391. nNear = p->pParent->nNear;
  109392. pPhrase = (
  109393. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  109394. );
  109395. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  109396. }
  109397. }
  109398. sqlite3_free(aTmp);
  109399. }
  109400. }
  109401. return res;
  109402. }
  109403. /*
  109404. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  109405. ** Assuming no error occurs or has occurred, It returns non-zero if the
  109406. ** expression passed as the second argument matches the row that pCsr
  109407. ** currently points to, or zero if it does not.
  109408. **
  109409. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  109410. ** If an error occurs during execution of this function, *pRc is set to
  109411. ** the appropriate SQLite error code. In this case the returned value is
  109412. ** undefined.
  109413. */
  109414. static int fts3EvalTestExpr(
  109415. Fts3Cursor *pCsr, /* FTS cursor handle */
  109416. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  109417. int *pRc /* IN/OUT: Error code */
  109418. ){
  109419. int bHit = 1; /* Return value */
  109420. if( *pRc==SQLITE_OK ){
  109421. switch( pExpr->eType ){
  109422. case FTSQUERY_NEAR:
  109423. case FTSQUERY_AND:
  109424. bHit = (
  109425. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  109426. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  109427. && fts3EvalNearTest(pExpr, pRc)
  109428. );
  109429. /* If the NEAR expression does not match any rows, zero the doclist for
  109430. ** all phrases involved in the NEAR. This is because the snippet(),
  109431. ** offsets() and matchinfo() functions are not supposed to recognize
  109432. ** any instances of phrases that are part of unmatched NEAR queries.
  109433. ** For example if this expression:
  109434. **
  109435. ** ... MATCH 'a OR (b NEAR c)'
  109436. **
  109437. ** is matched against a row containing:
  109438. **
  109439. ** 'a b d e'
  109440. **
  109441. ** then any snippet() should ony highlight the "a" term, not the "b"
  109442. ** (as "b" is part of a non-matching NEAR clause).
  109443. */
  109444. if( bHit==0
  109445. && pExpr->eType==FTSQUERY_NEAR
  109446. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  109447. ){
  109448. Fts3Expr *p;
  109449. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  109450. if( p->pRight->iDocid==pCsr->iPrevId ){
  109451. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  109452. }
  109453. }
  109454. if( p->iDocid==pCsr->iPrevId ){
  109455. fts3EvalInvalidatePoslist(p->pPhrase);
  109456. }
  109457. }
  109458. break;
  109459. case FTSQUERY_OR: {
  109460. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  109461. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  109462. bHit = bHit1 || bHit2;
  109463. break;
  109464. }
  109465. case FTSQUERY_NOT:
  109466. bHit = (
  109467. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  109468. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  109469. );
  109470. break;
  109471. default: {
  109472. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  109473. if( pCsr->pDeferred
  109474. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  109475. ){
  109476. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109477. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  109478. if( pExpr->bDeferred ){
  109479. fts3EvalInvalidatePoslist(pPhrase);
  109480. }
  109481. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  109482. bHit = (pPhrase->doclist.pList!=0);
  109483. pExpr->iDocid = pCsr->iPrevId;
  109484. }else
  109485. #endif
  109486. {
  109487. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  109488. }
  109489. break;
  109490. }
  109491. }
  109492. }
  109493. return bHit;
  109494. }
  109495. /*
  109496. ** This function is called as the second part of each xNext operation when
  109497. ** iterating through the results of a full-text query. At this point the
  109498. ** cursor points to a row that matches the query expression, with the
  109499. ** following caveats:
  109500. **
  109501. ** * Up until this point, "NEAR" operators in the expression have been
  109502. ** treated as "AND".
  109503. **
  109504. ** * Deferred tokens have not yet been considered.
  109505. **
  109506. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  109507. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  109508. ** operators and deferred tokens the current row is still a match for the
  109509. ** expression. It returns 1 if both of the following are true:
  109510. **
  109511. ** 1. *pRc is SQLITE_OK when this function returns, and
  109512. **
  109513. ** 2. After scanning the current FTS table row for the deferred tokens,
  109514. ** it is determined that the row does *not* match the query.
  109515. **
  109516. ** Or, if no error occurs and it seems the current row does match the FTS
  109517. ** query, return 0.
  109518. */
  109519. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  109520. int rc = *pRc;
  109521. int bMiss = 0;
  109522. if( rc==SQLITE_OK ){
  109523. /* If there are one or more deferred tokens, load the current row into
  109524. ** memory and scan it to determine the position list for each deferred
  109525. ** token. Then, see if this row is really a match, considering deferred
  109526. ** tokens and NEAR operators (neither of which were taken into account
  109527. ** earlier, by fts3EvalNextRow()).
  109528. */
  109529. if( pCsr->pDeferred ){
  109530. rc = fts3CursorSeek(0, pCsr);
  109531. if( rc==SQLITE_OK ){
  109532. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  109533. }
  109534. }
  109535. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  109536. /* Free the position-lists accumulated for each deferred token above. */
  109537. sqlite3Fts3FreeDeferredDoclists(pCsr);
  109538. *pRc = rc;
  109539. }
  109540. return (rc==SQLITE_OK && bMiss);
  109541. }
  109542. /*
  109543. ** Advance to the next document that matches the FTS expression in
  109544. ** Fts3Cursor.pExpr.
  109545. */
  109546. static int fts3EvalNext(Fts3Cursor *pCsr){
  109547. int rc = SQLITE_OK; /* Return Code */
  109548. Fts3Expr *pExpr = pCsr->pExpr;
  109549. assert( pCsr->isEof==0 );
  109550. if( pExpr==0 ){
  109551. pCsr->isEof = 1;
  109552. }else{
  109553. do {
  109554. if( pCsr->isRequireSeek==0 ){
  109555. sqlite3_reset(pCsr->pStmt);
  109556. }
  109557. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  109558. fts3EvalNextRow(pCsr, pExpr, &rc);
  109559. pCsr->isEof = pExpr->bEof;
  109560. pCsr->isRequireSeek = 1;
  109561. pCsr->isMatchinfoNeeded = 1;
  109562. pCsr->iPrevId = pExpr->iDocid;
  109563. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  109564. }
  109565. /* Check if the cursor is past the end of the docid range specified
  109566. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  109567. if( rc==SQLITE_OK && (
  109568. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  109569. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  109570. )){
  109571. pCsr->isEof = 1;
  109572. }
  109573. return rc;
  109574. }
  109575. /*
  109576. ** Restart interation for expression pExpr so that the next call to
  109577. ** fts3EvalNext() visits the first row. Do not allow incremental
  109578. ** loading or merging of phrase doclists for this iteration.
  109579. **
  109580. ** If *pRc is other than SQLITE_OK when this function is called, it is
  109581. ** a no-op. If an error occurs within this function, *pRc is set to an
  109582. ** SQLite error code before returning.
  109583. */
  109584. static void fts3EvalRestart(
  109585. Fts3Cursor *pCsr,
  109586. Fts3Expr *pExpr,
  109587. int *pRc
  109588. ){
  109589. if( pExpr && *pRc==SQLITE_OK ){
  109590. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109591. if( pPhrase ){
  109592. fts3EvalInvalidatePoslist(pPhrase);
  109593. if( pPhrase->bIncr ){
  109594. int i;
  109595. for(i=0; i<pPhrase->nToken; i++){
  109596. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  109597. assert( pToken->pDeferred==0 );
  109598. if( pToken->pSegcsr ){
  109599. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  109600. }
  109601. }
  109602. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  109603. }
  109604. pPhrase->doclist.pNextDocid = 0;
  109605. pPhrase->doclist.iDocid = 0;
  109606. }
  109607. pExpr->iDocid = 0;
  109608. pExpr->bEof = 0;
  109609. pExpr->bStart = 0;
  109610. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  109611. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  109612. }
  109613. }
  109614. /*
  109615. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  109616. ** expression rooted at pExpr, the cursor iterates through all rows matched
  109617. ** by pExpr, calling this function for each row. This function increments
  109618. ** the values in Fts3Expr.aMI[] according to the position-list currently
  109619. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  109620. ** expression nodes.
  109621. */
  109622. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  109623. if( pExpr ){
  109624. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109625. if( pPhrase && pPhrase->doclist.pList ){
  109626. int iCol = 0;
  109627. char *p = pPhrase->doclist.pList;
  109628. assert( *p );
  109629. while( 1 ){
  109630. u8 c = 0;
  109631. int iCnt = 0;
  109632. while( 0xFE & (*p | c) ){
  109633. if( (c&0x80)==0 ) iCnt++;
  109634. c = *p++ & 0x80;
  109635. }
  109636. /* aMI[iCol*3 + 1] = Number of occurrences
  109637. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  109638. */
  109639. pExpr->aMI[iCol*3 + 1] += iCnt;
  109640. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  109641. if( *p==0x00 ) break;
  109642. p++;
  109643. p += sqlite3Fts3GetVarint32(p, &iCol);
  109644. }
  109645. }
  109646. fts3EvalUpdateCounts(pExpr->pLeft);
  109647. fts3EvalUpdateCounts(pExpr->pRight);
  109648. }
  109649. }
  109650. /*
  109651. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  109652. **
  109653. ** If it is not already allocated and populated, this function allocates and
  109654. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  109655. ** of a NEAR expression, then it also allocates and populates the same array
  109656. ** for all other phrases that are part of the NEAR expression.
  109657. **
  109658. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  109659. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  109660. */
  109661. static int fts3EvalGatherStats(
  109662. Fts3Cursor *pCsr, /* Cursor object */
  109663. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  109664. ){
  109665. int rc = SQLITE_OK; /* Return code */
  109666. assert( pExpr->eType==FTSQUERY_PHRASE );
  109667. if( pExpr->aMI==0 ){
  109668. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109669. Fts3Expr *pRoot; /* Root of NEAR expression */
  109670. Fts3Expr *p; /* Iterator used for several purposes */
  109671. sqlite3_int64 iPrevId = pCsr->iPrevId;
  109672. sqlite3_int64 iDocid;
  109673. u8 bEof;
  109674. /* Find the root of the NEAR expression */
  109675. pRoot = pExpr;
  109676. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  109677. pRoot = pRoot->pParent;
  109678. }
  109679. iDocid = pRoot->iDocid;
  109680. bEof = pRoot->bEof;
  109681. assert( pRoot->bStart );
  109682. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  109683. for(p=pRoot; p; p=p->pLeft){
  109684. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  109685. assert( pE->aMI==0 );
  109686. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  109687. if( !pE->aMI ) return SQLITE_NOMEM;
  109688. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  109689. }
  109690. fts3EvalRestart(pCsr, pRoot, &rc);
  109691. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  109692. do {
  109693. /* Ensure the %_content statement is reset. */
  109694. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  109695. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  109696. /* Advance to the next document */
  109697. fts3EvalNextRow(pCsr, pRoot, &rc);
  109698. pCsr->isEof = pRoot->bEof;
  109699. pCsr->isRequireSeek = 1;
  109700. pCsr->isMatchinfoNeeded = 1;
  109701. pCsr->iPrevId = pRoot->iDocid;
  109702. }while( pCsr->isEof==0
  109703. && pRoot->eType==FTSQUERY_NEAR
  109704. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  109705. );
  109706. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  109707. fts3EvalUpdateCounts(pRoot);
  109708. }
  109709. }
  109710. pCsr->isEof = 0;
  109711. pCsr->iPrevId = iPrevId;
  109712. if( bEof ){
  109713. pRoot->bEof = bEof;
  109714. }else{
  109715. /* Caution: pRoot may iterate through docids in ascending or descending
  109716. ** order. For this reason, even though it seems more defensive, the
  109717. ** do loop can not be written:
  109718. **
  109719. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  109720. */
  109721. fts3EvalRestart(pCsr, pRoot, &rc);
  109722. do {
  109723. fts3EvalNextRow(pCsr, pRoot, &rc);
  109724. assert( pRoot->bEof==0 );
  109725. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  109726. fts3EvalTestDeferredAndNear(pCsr, &rc);
  109727. }
  109728. }
  109729. return rc;
  109730. }
  109731. /*
  109732. ** This function is used by the matchinfo() module to query a phrase
  109733. ** expression node for the following information:
  109734. **
  109735. ** 1. The total number of occurrences of the phrase in each column of
  109736. ** the FTS table (considering all rows), and
  109737. **
  109738. ** 2. For each column, the number of rows in the table for which the
  109739. ** column contains at least one instance of the phrase.
  109740. **
  109741. ** If no error occurs, SQLITE_OK is returned and the values for each column
  109742. ** written into the array aiOut as follows:
  109743. **
  109744. ** aiOut[iCol*3 + 1] = Number of occurrences
  109745. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  109746. **
  109747. ** Caveats:
  109748. **
  109749. ** * If a phrase consists entirely of deferred tokens, then all output
  109750. ** values are set to the number of documents in the table. In other
  109751. ** words we assume that very common tokens occur exactly once in each
  109752. ** column of each row of the table.
  109753. **
  109754. ** * If a phrase contains some deferred tokens (and some non-deferred
  109755. ** tokens), count the potential occurrence identified by considering
  109756. ** the non-deferred tokens instead of actual phrase occurrences.
  109757. **
  109758. ** * If the phrase is part of a NEAR expression, then only phrase instances
  109759. ** that meet the NEAR constraint are included in the counts.
  109760. */
  109761. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  109762. Fts3Cursor *pCsr, /* FTS cursor handle */
  109763. Fts3Expr *pExpr, /* Phrase expression */
  109764. u32 *aiOut /* Array to write results into (see above) */
  109765. ){
  109766. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109767. int rc = SQLITE_OK;
  109768. int iCol;
  109769. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  109770. assert( pCsr->nDoc>0 );
  109771. for(iCol=0; iCol<pTab->nColumn; iCol++){
  109772. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  109773. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  109774. }
  109775. }else{
  109776. rc = fts3EvalGatherStats(pCsr, pExpr);
  109777. if( rc==SQLITE_OK ){
  109778. assert( pExpr->aMI );
  109779. for(iCol=0; iCol<pTab->nColumn; iCol++){
  109780. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  109781. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  109782. }
  109783. }
  109784. }
  109785. return rc;
  109786. }
  109787. /*
  109788. ** The expression pExpr passed as the second argument to this function
  109789. ** must be of type FTSQUERY_PHRASE.
  109790. **
  109791. ** The returned value is either NULL or a pointer to a buffer containing
  109792. ** a position-list indicating the occurrences of the phrase in column iCol
  109793. ** of the current row.
  109794. **
  109795. ** More specifically, the returned buffer contains 1 varint for each
  109796. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  109797. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  109798. ** if the requested column contains "a b X c d X X" and the position-list
  109799. ** for 'X' is requested, the buffer returned may contain:
  109800. **
  109801. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  109802. **
  109803. ** This function works regardless of whether or not the phrase is deferred,
  109804. ** incremental, or neither.
  109805. */
  109806. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  109807. Fts3Cursor *pCsr, /* FTS3 cursor object */
  109808. Fts3Expr *pExpr, /* Phrase to return doclist for */
  109809. int iCol, /* Column to return position list for */
  109810. char **ppOut /* OUT: Pointer to position list */
  109811. ){
  109812. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109813. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109814. char *pIter;
  109815. int iThis;
  109816. sqlite3_int64 iDocid;
  109817. /* If this phrase is applies specifically to some column other than
  109818. ** column iCol, return a NULL pointer. */
  109819. *ppOut = 0;
  109820. assert( iCol>=0 && iCol<pTab->nColumn );
  109821. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  109822. return SQLITE_OK;
  109823. }
  109824. iDocid = pExpr->iDocid;
  109825. pIter = pPhrase->doclist.pList;
  109826. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  109827. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  109828. int iMul; /* +1 if csr dir matches index dir, else -1 */
  109829. int bOr = 0;
  109830. u8 bEof = 0;
  109831. u8 bTreeEof = 0;
  109832. Fts3Expr *p; /* Used to iterate from pExpr to root */
  109833. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  109834. /* Check if this phrase descends from an OR expression node. If not,
  109835. ** return NULL. Otherwise, the entry that corresponds to docid
  109836. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  109837. ** tree that the node is part of has been marked as EOF, but the node
  109838. ** itself is not EOF, then it may point to an earlier entry. */
  109839. pNear = pExpr;
  109840. for(p=pExpr->pParent; p; p=p->pParent){
  109841. if( p->eType==FTSQUERY_OR ) bOr = 1;
  109842. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  109843. if( p->bEof ) bTreeEof = 1;
  109844. }
  109845. if( bOr==0 ) return SQLITE_OK;
  109846. /* This is the descendent of an OR node. In this case we cannot use
  109847. ** an incremental phrase. Load the entire doclist for the phrase
  109848. ** into memory in this case. */
  109849. if( pPhrase->bIncr ){
  109850. int rc = SQLITE_OK;
  109851. int bEofSave = pExpr->bEof;
  109852. fts3EvalRestart(pCsr, pExpr, &rc);
  109853. while( rc==SQLITE_OK && !pExpr->bEof ){
  109854. fts3EvalNextRow(pCsr, pExpr, &rc);
  109855. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  109856. }
  109857. pIter = pPhrase->doclist.pList;
  109858. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  109859. if( rc!=SQLITE_OK ) return rc;
  109860. }
  109861. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  109862. while( bTreeEof==1
  109863. && pNear->bEof==0
  109864. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  109865. ){
  109866. int rc = SQLITE_OK;
  109867. fts3EvalNextRow(pCsr, pExpr, &rc);
  109868. if( rc!=SQLITE_OK ) return rc;
  109869. iDocid = pExpr->iDocid;
  109870. pIter = pPhrase->doclist.pList;
  109871. }
  109872. bEof = (pPhrase->doclist.nAll==0);
  109873. assert( bDescDoclist==0 || bDescDoclist==1 );
  109874. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  109875. if( bEof==0 ){
  109876. if( pCsr->bDesc==bDescDoclist ){
  109877. int dummy;
  109878. if( pNear->bEof ){
  109879. /* This expression is already at EOF. So position it to point to the
  109880. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  109881. ** iDocid is already set for this entry, so all that is required is
  109882. ** to set pIter to point to the first byte of the last position-list
  109883. ** in the doclist.
  109884. **
  109885. ** It would also be correct to set pIter and iDocid to zero. In
  109886. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  109887. ** would also move the iterator to point to the last entry in the
  109888. ** doclist. However, this is expensive, as to do so it has to
  109889. ** iterate through the entire doclist from start to finish (since
  109890. ** it does not know the docid for the last entry). */
  109891. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  109892. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  109893. }
  109894. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  109895. sqlite3Fts3DoclistPrev(
  109896. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  109897. &pIter, &iDocid, &dummy, &bEof
  109898. );
  109899. }
  109900. }else{
  109901. if( pNear->bEof ){
  109902. pIter = 0;
  109903. iDocid = 0;
  109904. }
  109905. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  109906. sqlite3Fts3DoclistNext(
  109907. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  109908. &pIter, &iDocid, &bEof
  109909. );
  109910. }
  109911. }
  109912. }
  109913. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  109914. }
  109915. if( pIter==0 ) return SQLITE_OK;
  109916. if( *pIter==0x01 ){
  109917. pIter++;
  109918. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  109919. }else{
  109920. iThis = 0;
  109921. }
  109922. while( iThis<iCol ){
  109923. fts3ColumnlistCopy(0, &pIter);
  109924. if( *pIter==0x00 ) return 0;
  109925. pIter++;
  109926. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  109927. }
  109928. *ppOut = ((iCol==iThis)?pIter:0);
  109929. return SQLITE_OK;
  109930. }
  109931. /*
  109932. ** Free all components of the Fts3Phrase structure that were allocated by
  109933. ** the eval module. Specifically, this means to free:
  109934. **
  109935. ** * the contents of pPhrase->doclist, and
  109936. ** * any Fts3MultiSegReader objects held by phrase tokens.
  109937. */
  109938. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  109939. if( pPhrase ){
  109940. int i;
  109941. sqlite3_free(pPhrase->doclist.aAll);
  109942. fts3EvalInvalidatePoslist(pPhrase);
  109943. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  109944. for(i=0; i<pPhrase->nToken; i++){
  109945. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  109946. pPhrase->aToken[i].pSegcsr = 0;
  109947. }
  109948. }
  109949. }
  109950. /*
  109951. ** Return SQLITE_CORRUPT_VTAB.
  109952. */
  109953. #ifdef SQLITE_DEBUG
  109954. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  109955. return SQLITE_CORRUPT_VTAB;
  109956. }
  109957. #endif
  109958. #if !SQLITE_CORE
  109959. /*
  109960. ** Initialize API pointer table, if required.
  109961. */
  109962. #ifdef _WIN32
  109963. __declspec(dllexport)
  109964. #endif
  109965. SQLITE_API int sqlite3_fts3_init(
  109966. sqlite3 *db,
  109967. char **pzErrMsg,
  109968. const sqlite3_api_routines *pApi
  109969. ){
  109970. SQLITE_EXTENSION_INIT2(pApi)
  109971. return sqlite3Fts3Init(db);
  109972. }
  109973. #endif
  109974. #endif
  109975. /************** End of fts3.c ************************************************/
  109976. /************** Begin file fts3_aux.c ****************************************/
  109977. /*
  109978. ** 2011 Jan 27
  109979. **
  109980. ** The author disclaims copyright to this source code. In place of
  109981. ** a legal notice, here is a blessing:
  109982. **
  109983. ** May you do good and not evil.
  109984. ** May you find forgiveness for yourself and forgive others.
  109985. ** May you share freely, never taking more than you give.
  109986. **
  109987. ******************************************************************************
  109988. **
  109989. */
  109990. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109991. /* #include <string.h> */
  109992. /* #include <assert.h> */
  109993. typedef struct Fts3auxTable Fts3auxTable;
  109994. typedef struct Fts3auxCursor Fts3auxCursor;
  109995. struct Fts3auxTable {
  109996. sqlite3_vtab base; /* Base class used by SQLite core */
  109997. Fts3Table *pFts3Tab;
  109998. };
  109999. struct Fts3auxCursor {
  110000. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  110001. Fts3MultiSegReader csr; /* Must be right after "base" */
  110002. Fts3SegFilter filter;
  110003. char *zStop;
  110004. int nStop; /* Byte-length of string zStop */
  110005. int iLangid; /* Language id to query */
  110006. int isEof; /* True if cursor is at EOF */
  110007. sqlite3_int64 iRowid; /* Current rowid */
  110008. int iCol; /* Current value of 'col' column */
  110009. int nStat; /* Size of aStat[] array */
  110010. struct Fts3auxColstats {
  110011. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  110012. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  110013. } *aStat;
  110014. };
  110015. /*
  110016. ** Schema of the terms table.
  110017. */
  110018. #define FTS3_AUX_SCHEMA \
  110019. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  110020. /*
  110021. ** This function does all the work for both the xConnect and xCreate methods.
  110022. ** These tables have no persistent representation of their own, so xConnect
  110023. ** and xCreate are identical operations.
  110024. */
  110025. static int fts3auxConnectMethod(
  110026. sqlite3 *db, /* Database connection */
  110027. void *pUnused, /* Unused */
  110028. int argc, /* Number of elements in argv array */
  110029. const char * const *argv, /* xCreate/xConnect argument array */
  110030. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  110031. char **pzErr /* OUT: sqlite3_malloc'd error message */
  110032. ){
  110033. char const *zDb; /* Name of database (e.g. "main") */
  110034. char const *zFts3; /* Name of fts3 table */
  110035. int nDb; /* Result of strlen(zDb) */
  110036. int nFts3; /* Result of strlen(zFts3) */
  110037. int nByte; /* Bytes of space to allocate here */
  110038. int rc; /* value returned by declare_vtab() */
  110039. Fts3auxTable *p; /* Virtual table object to return */
  110040. UNUSED_PARAMETER(pUnused);
  110041. /* The user should invoke this in one of two forms:
  110042. **
  110043. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  110044. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  110045. */
  110046. if( argc!=4 && argc!=5 ) goto bad_args;
  110047. zDb = argv[1];
  110048. nDb = (int)strlen(zDb);
  110049. if( argc==5 ){
  110050. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  110051. zDb = argv[3];
  110052. nDb = (int)strlen(zDb);
  110053. zFts3 = argv[4];
  110054. }else{
  110055. goto bad_args;
  110056. }
  110057. }else{
  110058. zFts3 = argv[3];
  110059. }
  110060. nFts3 = (int)strlen(zFts3);
  110061. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  110062. if( rc!=SQLITE_OK ) return rc;
  110063. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  110064. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  110065. if( !p ) return SQLITE_NOMEM;
  110066. memset(p, 0, nByte);
  110067. p->pFts3Tab = (Fts3Table *)&p[1];
  110068. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  110069. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  110070. p->pFts3Tab->db = db;
  110071. p->pFts3Tab->nIndex = 1;
  110072. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  110073. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  110074. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  110075. *ppVtab = (sqlite3_vtab *)p;
  110076. return SQLITE_OK;
  110077. bad_args:
  110078. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  110079. return SQLITE_ERROR;
  110080. }
  110081. /*
  110082. ** This function does the work for both the xDisconnect and xDestroy methods.
  110083. ** These tables have no persistent representation of their own, so xDisconnect
  110084. ** and xDestroy are identical operations.
  110085. */
  110086. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  110087. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  110088. Fts3Table *pFts3 = p->pFts3Tab;
  110089. int i;
  110090. /* Free any prepared statements held */
  110091. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  110092. sqlite3_finalize(pFts3->aStmt[i]);
  110093. }
  110094. sqlite3_free(pFts3->zSegmentsTbl);
  110095. sqlite3_free(p);
  110096. return SQLITE_OK;
  110097. }
  110098. #define FTS4AUX_EQ_CONSTRAINT 1
  110099. #define FTS4AUX_GE_CONSTRAINT 2
  110100. #define FTS4AUX_LE_CONSTRAINT 4
  110101. /*
  110102. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  110103. */
  110104. static int fts3auxBestIndexMethod(
  110105. sqlite3_vtab *pVTab,
  110106. sqlite3_index_info *pInfo
  110107. ){
  110108. int i;
  110109. int iEq = -1;
  110110. int iGe = -1;
  110111. int iLe = -1;
  110112. int iLangid = -1;
  110113. int iNext = 1; /* Next free argvIndex value */
  110114. UNUSED_PARAMETER(pVTab);
  110115. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  110116. if( pInfo->nOrderBy==1
  110117. && pInfo->aOrderBy[0].iColumn==0
  110118. && pInfo->aOrderBy[0].desc==0
  110119. ){
  110120. pInfo->orderByConsumed = 1;
  110121. }
  110122. /* Search for equality and range constraints on the "term" column.
  110123. ** And equality constraints on the hidden "languageid" column. */
  110124. for(i=0; i<pInfo->nConstraint; i++){
  110125. if( pInfo->aConstraint[i].usable ){
  110126. int op = pInfo->aConstraint[i].op;
  110127. int iCol = pInfo->aConstraint[i].iColumn;
  110128. if( iCol==0 ){
  110129. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  110130. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  110131. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  110132. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  110133. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  110134. }
  110135. if( iCol==4 ){
  110136. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  110137. }
  110138. }
  110139. }
  110140. if( iEq>=0 ){
  110141. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  110142. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  110143. pInfo->estimatedCost = 5;
  110144. }else{
  110145. pInfo->idxNum = 0;
  110146. pInfo->estimatedCost = 20000;
  110147. if( iGe>=0 ){
  110148. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  110149. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  110150. pInfo->estimatedCost /= 2;
  110151. }
  110152. if( iLe>=0 ){
  110153. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  110154. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  110155. pInfo->estimatedCost /= 2;
  110156. }
  110157. }
  110158. if( iLangid>=0 ){
  110159. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  110160. pInfo->estimatedCost--;
  110161. }
  110162. return SQLITE_OK;
  110163. }
  110164. /*
  110165. ** xOpen - Open a cursor.
  110166. */
  110167. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  110168. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  110169. UNUSED_PARAMETER(pVTab);
  110170. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  110171. if( !pCsr ) return SQLITE_NOMEM;
  110172. memset(pCsr, 0, sizeof(Fts3auxCursor));
  110173. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  110174. return SQLITE_OK;
  110175. }
  110176. /*
  110177. ** xClose - Close a cursor.
  110178. */
  110179. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  110180. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110181. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110182. sqlite3Fts3SegmentsClose(pFts3);
  110183. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  110184. sqlite3_free((void *)pCsr->filter.zTerm);
  110185. sqlite3_free(pCsr->zStop);
  110186. sqlite3_free(pCsr->aStat);
  110187. sqlite3_free(pCsr);
  110188. return SQLITE_OK;
  110189. }
  110190. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  110191. if( nSize>pCsr->nStat ){
  110192. struct Fts3auxColstats *aNew;
  110193. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  110194. sizeof(struct Fts3auxColstats) * nSize
  110195. );
  110196. if( aNew==0 ) return SQLITE_NOMEM;
  110197. memset(&aNew[pCsr->nStat], 0,
  110198. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  110199. );
  110200. pCsr->aStat = aNew;
  110201. pCsr->nStat = nSize;
  110202. }
  110203. return SQLITE_OK;
  110204. }
  110205. /*
  110206. ** xNext - Advance the cursor to the next row, if any.
  110207. */
  110208. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  110209. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110210. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110211. int rc;
  110212. /* Increment our pretend rowid value. */
  110213. pCsr->iRowid++;
  110214. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  110215. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  110216. }
  110217. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  110218. if( rc==SQLITE_ROW ){
  110219. int i = 0;
  110220. int nDoclist = pCsr->csr.nDoclist;
  110221. char *aDoclist = pCsr->csr.aDoclist;
  110222. int iCol;
  110223. int eState = 0;
  110224. if( pCsr->zStop ){
  110225. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  110226. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  110227. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  110228. pCsr->isEof = 1;
  110229. return SQLITE_OK;
  110230. }
  110231. }
  110232. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  110233. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  110234. iCol = 0;
  110235. while( i<nDoclist ){
  110236. sqlite3_int64 v = 0;
  110237. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  110238. switch( eState ){
  110239. /* State 0. In this state the integer just read was a docid. */
  110240. case 0:
  110241. pCsr->aStat[0].nDoc++;
  110242. eState = 1;
  110243. iCol = 0;
  110244. break;
  110245. /* State 1. In this state we are expecting either a 1, indicating
  110246. ** that the following integer will be a column number, or the
  110247. ** start of a position list for column 0.
  110248. **
  110249. ** The only difference between state 1 and state 2 is that if the
  110250. ** integer encountered in state 1 is not 0 or 1, then we need to
  110251. ** increment the column 0 "nDoc" count for this term.
  110252. */
  110253. case 1:
  110254. assert( iCol==0 );
  110255. if( v>1 ){
  110256. pCsr->aStat[1].nDoc++;
  110257. }
  110258. eState = 2;
  110259. /* fall through */
  110260. case 2:
  110261. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  110262. eState = 0;
  110263. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  110264. eState = 3;
  110265. }else{ /* 2 or greater. A position. */
  110266. pCsr->aStat[iCol+1].nOcc++;
  110267. pCsr->aStat[0].nOcc++;
  110268. }
  110269. break;
  110270. /* State 3. The integer just read is a column number. */
  110271. default: assert( eState==3 );
  110272. iCol = (int)v;
  110273. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  110274. pCsr->aStat[iCol+1].nDoc++;
  110275. eState = 2;
  110276. break;
  110277. }
  110278. }
  110279. pCsr->iCol = 0;
  110280. rc = SQLITE_OK;
  110281. }else{
  110282. pCsr->isEof = 1;
  110283. }
  110284. return rc;
  110285. }
  110286. /*
  110287. ** xFilter - Initialize a cursor to point at the start of its data.
  110288. */
  110289. static int fts3auxFilterMethod(
  110290. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  110291. int idxNum, /* Strategy index */
  110292. const char *idxStr, /* Unused */
  110293. int nVal, /* Number of elements in apVal */
  110294. sqlite3_value **apVal /* Arguments for the indexing scheme */
  110295. ){
  110296. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110297. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110298. int rc;
  110299. int isScan = 0;
  110300. int iLangVal = 0; /* Language id to query */
  110301. int iEq = -1; /* Index of term=? value in apVal */
  110302. int iGe = -1; /* Index of term>=? value in apVal */
  110303. int iLe = -1; /* Index of term<=? value in apVal */
  110304. int iLangid = -1; /* Index of languageid=? value in apVal */
  110305. int iNext = 0;
  110306. UNUSED_PARAMETER(nVal);
  110307. UNUSED_PARAMETER(idxStr);
  110308. assert( idxStr==0 );
  110309. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  110310. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  110311. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  110312. );
  110313. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  110314. iEq = iNext++;
  110315. }else{
  110316. isScan = 1;
  110317. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  110318. iGe = iNext++;
  110319. }
  110320. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  110321. iLe = iNext++;
  110322. }
  110323. }
  110324. if( iNext<nVal ){
  110325. iLangid = iNext++;
  110326. }
  110327. /* In case this cursor is being reused, close and zero it. */
  110328. testcase(pCsr->filter.zTerm);
  110329. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  110330. sqlite3_free((void *)pCsr->filter.zTerm);
  110331. sqlite3_free(pCsr->aStat);
  110332. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  110333. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  110334. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  110335. if( iEq>=0 || iGe>=0 ){
  110336. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  110337. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  110338. if( zStr ){
  110339. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  110340. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  110341. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  110342. }
  110343. }
  110344. if( iLe>=0 ){
  110345. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  110346. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  110347. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  110348. }
  110349. if( iLangid>=0 ){
  110350. iLangVal = sqlite3_value_int(apVal[iLangid]);
  110351. /* If the user specified a negative value for the languageid, use zero
  110352. ** instead. This works, as the "languageid=?" constraint will also
  110353. ** be tested by the VDBE layer. The test will always be false (since
  110354. ** this module will not return a row with a negative languageid), and
  110355. ** so the overall query will return zero rows. */
  110356. if( iLangVal<0 ) iLangVal = 0;
  110357. }
  110358. pCsr->iLangid = iLangVal;
  110359. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  110360. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  110361. );
  110362. if( rc==SQLITE_OK ){
  110363. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  110364. }
  110365. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  110366. return rc;
  110367. }
  110368. /*
  110369. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  110370. */
  110371. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  110372. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110373. return pCsr->isEof;
  110374. }
  110375. /*
  110376. ** xColumn - Return a column value.
  110377. */
  110378. static int fts3auxColumnMethod(
  110379. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  110380. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  110381. int iCol /* Index of column to read value from */
  110382. ){
  110383. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  110384. assert( p->isEof==0 );
  110385. switch( iCol ){
  110386. case 0: /* term */
  110387. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  110388. break;
  110389. case 1: /* col */
  110390. if( p->iCol ){
  110391. sqlite3_result_int(pCtx, p->iCol-1);
  110392. }else{
  110393. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  110394. }
  110395. break;
  110396. case 2: /* documents */
  110397. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  110398. break;
  110399. case 3: /* occurrences */
  110400. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  110401. break;
  110402. default: /* languageid */
  110403. assert( iCol==4 );
  110404. sqlite3_result_int(pCtx, p->iLangid);
  110405. break;
  110406. }
  110407. return SQLITE_OK;
  110408. }
  110409. /*
  110410. ** xRowid - Return the current rowid for the cursor.
  110411. */
  110412. static int fts3auxRowidMethod(
  110413. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  110414. sqlite_int64 *pRowid /* OUT: Rowid value */
  110415. ){
  110416. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110417. *pRowid = pCsr->iRowid;
  110418. return SQLITE_OK;
  110419. }
  110420. /*
  110421. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  110422. ** if successful or an error code if sqlite3_create_module() fails.
  110423. */
  110424. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  110425. static const sqlite3_module fts3aux_module = {
  110426. 0, /* iVersion */
  110427. fts3auxConnectMethod, /* xCreate */
  110428. fts3auxConnectMethod, /* xConnect */
  110429. fts3auxBestIndexMethod, /* xBestIndex */
  110430. fts3auxDisconnectMethod, /* xDisconnect */
  110431. fts3auxDisconnectMethod, /* xDestroy */
  110432. fts3auxOpenMethod, /* xOpen */
  110433. fts3auxCloseMethod, /* xClose */
  110434. fts3auxFilterMethod, /* xFilter */
  110435. fts3auxNextMethod, /* xNext */
  110436. fts3auxEofMethod, /* xEof */
  110437. fts3auxColumnMethod, /* xColumn */
  110438. fts3auxRowidMethod, /* xRowid */
  110439. 0, /* xUpdate */
  110440. 0, /* xBegin */
  110441. 0, /* xSync */
  110442. 0, /* xCommit */
  110443. 0, /* xRollback */
  110444. 0, /* xFindFunction */
  110445. 0, /* xRename */
  110446. 0, /* xSavepoint */
  110447. 0, /* xRelease */
  110448. 0 /* xRollbackTo */
  110449. };
  110450. int rc; /* Return code */
  110451. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  110452. return rc;
  110453. }
  110454. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  110455. /************** End of fts3_aux.c ********************************************/
  110456. /************** Begin file fts3_expr.c ***************************************/
  110457. /*
  110458. ** 2008 Nov 28
  110459. **
  110460. ** The author disclaims copyright to this source code. In place of
  110461. ** a legal notice, here is a blessing:
  110462. **
  110463. ** May you do good and not evil.
  110464. ** May you find forgiveness for yourself and forgive others.
  110465. ** May you share freely, never taking more than you give.
  110466. **
  110467. ******************************************************************************
  110468. **
  110469. ** This module contains code that implements a parser for fts3 query strings
  110470. ** (the right-hand argument to the MATCH operator). Because the supported
  110471. ** syntax is relatively simple, the whole tokenizer/parser system is
  110472. ** hand-coded.
  110473. */
  110474. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  110475. /*
  110476. ** By default, this module parses the legacy syntax that has been
  110477. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  110478. ** is defined, then it uses the new syntax. The differences between
  110479. ** the new and the old syntaxes are:
  110480. **
  110481. ** a) The new syntax supports parenthesis. The old does not.
  110482. **
  110483. ** b) The new syntax supports the AND and NOT operators. The old does not.
  110484. **
  110485. ** c) The old syntax supports the "-" token qualifier. This is not
  110486. ** supported by the new syntax (it is replaced by the NOT operator).
  110487. **
  110488. ** d) When using the old syntax, the OR operator has a greater precedence
  110489. ** than an implicit AND. When using the new, both implicity and explicit
  110490. ** AND operators have a higher precedence than OR.
  110491. **
  110492. ** If compiled with SQLITE_TEST defined, then this module exports the
  110493. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  110494. ** to zero causes the module to use the old syntax. If it is set to
  110495. ** non-zero the new syntax is activated. This is so both syntaxes can
  110496. ** be tested using a single build of testfixture.
  110497. **
  110498. ** The following describes the syntax supported by the fts3 MATCH
  110499. ** operator in a similar format to that used by the lemon parser
  110500. ** generator. This module does not use actually lemon, it uses a
  110501. ** custom parser.
  110502. **
  110503. ** query ::= andexpr (OR andexpr)*.
  110504. **
  110505. ** andexpr ::= notexpr (AND? notexpr)*.
  110506. **
  110507. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  110508. ** notexpr ::= LP query RP.
  110509. **
  110510. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  110511. **
  110512. ** distance_opt ::= .
  110513. ** distance_opt ::= / INTEGER.
  110514. **
  110515. ** phrase ::= TOKEN.
  110516. ** phrase ::= COLUMN:TOKEN.
  110517. ** phrase ::= "TOKEN TOKEN TOKEN...".
  110518. */
  110519. #ifdef SQLITE_TEST
  110520. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  110521. #else
  110522. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  110523. # define sqlite3_fts3_enable_parentheses 1
  110524. # else
  110525. # define sqlite3_fts3_enable_parentheses 0
  110526. # endif
  110527. #endif
  110528. /*
  110529. ** Default span for NEAR operators.
  110530. */
  110531. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  110532. /* #include <string.h> */
  110533. /* #include <assert.h> */
  110534. /*
  110535. ** isNot:
  110536. ** This variable is used by function getNextNode(). When getNextNode() is
  110537. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  110538. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  110539. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  110540. ** zero.
  110541. */
  110542. typedef struct ParseContext ParseContext;
  110543. struct ParseContext {
  110544. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  110545. int iLangid; /* Language id used with tokenizer */
  110546. const char **azCol; /* Array of column names for fts3 table */
  110547. int bFts4; /* True to allow FTS4-only syntax */
  110548. int nCol; /* Number of entries in azCol[] */
  110549. int iDefaultCol; /* Default column to query */
  110550. int isNot; /* True if getNextNode() sees a unary - */
  110551. sqlite3_context *pCtx; /* Write error message here */
  110552. int nNest; /* Number of nested brackets */
  110553. };
  110554. /*
  110555. ** This function is equivalent to the standard isspace() function.
  110556. **
  110557. ** The standard isspace() can be awkward to use safely, because although it
  110558. ** is defined to accept an argument of type int, its behavior when passed
  110559. ** an integer that falls outside of the range of the unsigned char type
  110560. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  110561. ** is defined to accept an argument of type char, and always returns 0 for
  110562. ** any values that fall outside of the range of the unsigned char type (i.e.
  110563. ** negative values).
  110564. */
  110565. static int fts3isspace(char c){
  110566. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  110567. }
  110568. /*
  110569. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  110570. ** zero the memory before returning a pointer to it. If unsuccessful,
  110571. ** return NULL.
  110572. */
  110573. static void *fts3MallocZero(int nByte){
  110574. void *pRet = sqlite3_malloc(nByte);
  110575. if( pRet ) memset(pRet, 0, nByte);
  110576. return pRet;
  110577. }
  110578. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  110579. sqlite3_tokenizer *pTokenizer,
  110580. int iLangid,
  110581. const char *z,
  110582. int n,
  110583. sqlite3_tokenizer_cursor **ppCsr
  110584. ){
  110585. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110586. sqlite3_tokenizer_cursor *pCsr = 0;
  110587. int rc;
  110588. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  110589. assert( rc==SQLITE_OK || pCsr==0 );
  110590. if( rc==SQLITE_OK ){
  110591. pCsr->pTokenizer = pTokenizer;
  110592. if( pModule->iVersion>=1 ){
  110593. rc = pModule->xLanguageid(pCsr, iLangid);
  110594. if( rc!=SQLITE_OK ){
  110595. pModule->xClose(pCsr);
  110596. pCsr = 0;
  110597. }
  110598. }
  110599. }
  110600. *ppCsr = pCsr;
  110601. return rc;
  110602. }
  110603. /*
  110604. ** Extract the next token from buffer z (length n) using the tokenizer
  110605. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  110606. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  110607. ** single token and set *ppExpr to point to it. If the end of the buffer is
  110608. ** reached before a token is found, set *ppExpr to zero. It is the
  110609. ** responsibility of the caller to eventually deallocate the allocated
  110610. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  110611. **
  110612. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  110613. ** fails.
  110614. */
  110615. static int getNextToken(
  110616. ParseContext *pParse, /* fts3 query parse context */
  110617. int iCol, /* Value for Fts3Phrase.iColumn */
  110618. const char *z, int n, /* Input string */
  110619. Fts3Expr **ppExpr, /* OUT: expression */
  110620. int *pnConsumed /* OUT: Number of bytes consumed */
  110621. ){
  110622. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  110623. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110624. int rc;
  110625. sqlite3_tokenizer_cursor *pCursor;
  110626. Fts3Expr *pRet = 0;
  110627. int nConsumed = 0;
  110628. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  110629. if( rc==SQLITE_OK ){
  110630. const char *zToken;
  110631. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  110632. int nByte; /* total space to allocate */
  110633. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  110634. if( rc==SQLITE_OK ){
  110635. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  110636. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  110637. if( !pRet ){
  110638. rc = SQLITE_NOMEM;
  110639. }else{
  110640. pRet->eType = FTSQUERY_PHRASE;
  110641. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  110642. pRet->pPhrase->nToken = 1;
  110643. pRet->pPhrase->iColumn = iCol;
  110644. pRet->pPhrase->aToken[0].n = nToken;
  110645. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  110646. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  110647. if( iEnd<n && z[iEnd]=='*' ){
  110648. pRet->pPhrase->aToken[0].isPrefix = 1;
  110649. iEnd++;
  110650. }
  110651. while( 1 ){
  110652. if( !sqlite3_fts3_enable_parentheses
  110653. && iStart>0 && z[iStart-1]=='-'
  110654. ){
  110655. pParse->isNot = 1;
  110656. iStart--;
  110657. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  110658. pRet->pPhrase->aToken[0].bFirst = 1;
  110659. iStart--;
  110660. }else{
  110661. break;
  110662. }
  110663. }
  110664. }
  110665. nConsumed = iEnd;
  110666. }
  110667. pModule->xClose(pCursor);
  110668. }
  110669. *pnConsumed = nConsumed;
  110670. *ppExpr = pRet;
  110671. return rc;
  110672. }
  110673. /*
  110674. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  110675. ** then free the old allocation.
  110676. */
  110677. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  110678. void *pRet = sqlite3_realloc(pOrig, nNew);
  110679. if( !pRet ){
  110680. sqlite3_free(pOrig);
  110681. }
  110682. return pRet;
  110683. }
  110684. /*
  110685. ** Buffer zInput, length nInput, contains the contents of a quoted string
  110686. ** that appeared as part of an fts3 query expression. Neither quote character
  110687. ** is included in the buffer. This function attempts to tokenize the entire
  110688. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  110689. ** containing the results.
  110690. **
  110691. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  110692. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  110693. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  110694. ** to 0.
  110695. */
  110696. static int getNextString(
  110697. ParseContext *pParse, /* fts3 query parse context */
  110698. const char *zInput, int nInput, /* Input string */
  110699. Fts3Expr **ppExpr /* OUT: expression */
  110700. ){
  110701. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  110702. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110703. int rc;
  110704. Fts3Expr *p = 0;
  110705. sqlite3_tokenizer_cursor *pCursor = 0;
  110706. char *zTemp = 0;
  110707. int nTemp = 0;
  110708. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  110709. int nToken = 0;
  110710. /* The final Fts3Expr data structure, including the Fts3Phrase,
  110711. ** Fts3PhraseToken structures token buffers are all stored as a single
  110712. ** allocation so that the expression can be freed with a single call to
  110713. ** sqlite3_free(). Setting this up requires a two pass approach.
  110714. **
  110715. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  110716. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  110717. ** to assemble data in two dynamic buffers:
  110718. **
  110719. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  110720. ** structure, followed by the array of Fts3PhraseToken
  110721. ** structures. This pass only populates the Fts3PhraseToken array.
  110722. **
  110723. ** Buffer zTemp: Contains copies of all tokens.
  110724. **
  110725. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  110726. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  110727. ** structures.
  110728. */
  110729. rc = sqlite3Fts3OpenTokenizer(
  110730. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  110731. if( rc==SQLITE_OK ){
  110732. int ii;
  110733. for(ii=0; rc==SQLITE_OK; ii++){
  110734. const char *zByte;
  110735. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  110736. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  110737. if( rc==SQLITE_OK ){
  110738. Fts3PhraseToken *pToken;
  110739. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  110740. if( !p ) goto no_mem;
  110741. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  110742. if( !zTemp ) goto no_mem;
  110743. assert( nToken==ii );
  110744. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  110745. memset(pToken, 0, sizeof(Fts3PhraseToken));
  110746. memcpy(&zTemp[nTemp], zByte, nByte);
  110747. nTemp += nByte;
  110748. pToken->n = nByte;
  110749. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  110750. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  110751. nToken = ii+1;
  110752. }
  110753. }
  110754. pModule->xClose(pCursor);
  110755. pCursor = 0;
  110756. }
  110757. if( rc==SQLITE_DONE ){
  110758. int jj;
  110759. char *zBuf = 0;
  110760. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  110761. if( !p ) goto no_mem;
  110762. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  110763. p->eType = FTSQUERY_PHRASE;
  110764. p->pPhrase = (Fts3Phrase *)&p[1];
  110765. p->pPhrase->iColumn = pParse->iDefaultCol;
  110766. p->pPhrase->nToken = nToken;
  110767. zBuf = (char *)&p->pPhrase->aToken[nToken];
  110768. if( zTemp ){
  110769. memcpy(zBuf, zTemp, nTemp);
  110770. sqlite3_free(zTemp);
  110771. }else{
  110772. assert( nTemp==0 );
  110773. }
  110774. for(jj=0; jj<p->pPhrase->nToken; jj++){
  110775. p->pPhrase->aToken[jj].z = zBuf;
  110776. zBuf += p->pPhrase->aToken[jj].n;
  110777. }
  110778. rc = SQLITE_OK;
  110779. }
  110780. *ppExpr = p;
  110781. return rc;
  110782. no_mem:
  110783. if( pCursor ){
  110784. pModule->xClose(pCursor);
  110785. }
  110786. sqlite3_free(zTemp);
  110787. sqlite3_free(p);
  110788. *ppExpr = 0;
  110789. return SQLITE_NOMEM;
  110790. }
  110791. /*
  110792. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  110793. ** call fts3ExprParse(). So this forward declaration is required.
  110794. */
  110795. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  110796. /*
  110797. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  110798. ** structure, or set to 0 if the end of the input buffer is reached.
  110799. **
  110800. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  110801. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  110802. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  110803. */
  110804. static int getNextNode(
  110805. ParseContext *pParse, /* fts3 query parse context */
  110806. const char *z, int n, /* Input string */
  110807. Fts3Expr **ppExpr, /* OUT: expression */
  110808. int *pnConsumed /* OUT: Number of bytes consumed */
  110809. ){
  110810. static const struct Fts3Keyword {
  110811. char *z; /* Keyword text */
  110812. unsigned char n; /* Length of the keyword */
  110813. unsigned char parenOnly; /* Only valid in paren mode */
  110814. unsigned char eType; /* Keyword code */
  110815. } aKeyword[] = {
  110816. { "OR" , 2, 0, FTSQUERY_OR },
  110817. { "AND", 3, 1, FTSQUERY_AND },
  110818. { "NOT", 3, 1, FTSQUERY_NOT },
  110819. { "NEAR", 4, 0, FTSQUERY_NEAR }
  110820. };
  110821. int ii;
  110822. int iCol;
  110823. int iColLen;
  110824. int rc;
  110825. Fts3Expr *pRet = 0;
  110826. const char *zInput = z;
  110827. int nInput = n;
  110828. pParse->isNot = 0;
  110829. /* Skip over any whitespace before checking for a keyword, an open or
  110830. ** close bracket, or a quoted string.
  110831. */
  110832. while( nInput>0 && fts3isspace(*zInput) ){
  110833. nInput--;
  110834. zInput++;
  110835. }
  110836. if( nInput==0 ){
  110837. return SQLITE_DONE;
  110838. }
  110839. /* See if we are dealing with a keyword. */
  110840. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  110841. const struct Fts3Keyword *pKey = &aKeyword[ii];
  110842. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  110843. continue;
  110844. }
  110845. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  110846. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  110847. int nKey = pKey->n;
  110848. char cNext;
  110849. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  110850. if( pKey->eType==FTSQUERY_NEAR ){
  110851. assert( nKey==4 );
  110852. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  110853. nNear = 0;
  110854. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  110855. nNear = nNear * 10 + (zInput[nKey] - '0');
  110856. }
  110857. }
  110858. }
  110859. /* At this point this is probably a keyword. But for that to be true,
  110860. ** the next byte must contain either whitespace, an open or close
  110861. ** parenthesis, a quote character, or EOF.
  110862. */
  110863. cNext = zInput[nKey];
  110864. if( fts3isspace(cNext)
  110865. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  110866. ){
  110867. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  110868. if( !pRet ){
  110869. return SQLITE_NOMEM;
  110870. }
  110871. pRet->eType = pKey->eType;
  110872. pRet->nNear = nNear;
  110873. *ppExpr = pRet;
  110874. *pnConsumed = (int)((zInput - z) + nKey);
  110875. return SQLITE_OK;
  110876. }
  110877. /* Turns out that wasn't a keyword after all. This happens if the
  110878. ** user has supplied a token such as "ORacle". Continue.
  110879. */
  110880. }
  110881. }
  110882. /* Check for an open bracket. */
  110883. if( sqlite3_fts3_enable_parentheses ){
  110884. if( *zInput=='(' ){
  110885. int nConsumed;
  110886. pParse->nNest++;
  110887. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  110888. if( rc==SQLITE_OK && !*ppExpr ){
  110889. rc = SQLITE_DONE;
  110890. }
  110891. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  110892. return rc;
  110893. }
  110894. /* Check for a close bracket. */
  110895. if( *zInput==')' ){
  110896. pParse->nNest--;
  110897. *pnConsumed = (int)((zInput - z) + 1);
  110898. return SQLITE_DONE;
  110899. }
  110900. }
  110901. /* See if we are dealing with a quoted phrase. If this is the case, then
  110902. ** search for the closing quote and pass the whole string to getNextString()
  110903. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  110904. ** a quote character embedded in a string.
  110905. */
  110906. if( *zInput=='"' ){
  110907. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  110908. *pnConsumed = (int)((zInput - z) + ii + 1);
  110909. if( ii==nInput ){
  110910. return SQLITE_ERROR;
  110911. }
  110912. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  110913. }
  110914. /* If control flows to this point, this must be a regular token, or
  110915. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  110916. ** interface. Before doing so, figure out if there is an explicit
  110917. ** column specifier for the token.
  110918. **
  110919. ** TODO: Strangely, it is not possible to associate a column specifier
  110920. ** with a quoted phrase, only with a single token. Not sure if this was
  110921. ** an implementation artifact or an intentional decision when fts3 was
  110922. ** first implemented. Whichever it was, this module duplicates the
  110923. ** limitation.
  110924. */
  110925. iCol = pParse->iDefaultCol;
  110926. iColLen = 0;
  110927. for(ii=0; ii<pParse->nCol; ii++){
  110928. const char *zStr = pParse->azCol[ii];
  110929. int nStr = (int)strlen(zStr);
  110930. if( nInput>nStr && zInput[nStr]==':'
  110931. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  110932. ){
  110933. iCol = ii;
  110934. iColLen = (int)((zInput - z) + nStr + 1);
  110935. break;
  110936. }
  110937. }
  110938. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  110939. *pnConsumed += iColLen;
  110940. return rc;
  110941. }
  110942. /*
  110943. ** The argument is an Fts3Expr structure for a binary operator (any type
  110944. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  110945. ** precedence of the operator. Lower values have a higher precedence (i.e.
  110946. ** group more tightly). For example, in the C language, the == operator
  110947. ** groups more tightly than ||, and would therefore have a higher precedence.
  110948. **
  110949. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  110950. ** is defined), the order of the operators in precedence from highest to
  110951. ** lowest is:
  110952. **
  110953. ** NEAR
  110954. ** NOT
  110955. ** AND (including implicit ANDs)
  110956. ** OR
  110957. **
  110958. ** Note that when using the old query syntax, the OR operator has a higher
  110959. ** precedence than the AND operator.
  110960. */
  110961. static int opPrecedence(Fts3Expr *p){
  110962. assert( p->eType!=FTSQUERY_PHRASE );
  110963. if( sqlite3_fts3_enable_parentheses ){
  110964. return p->eType;
  110965. }else if( p->eType==FTSQUERY_NEAR ){
  110966. return 1;
  110967. }else if( p->eType==FTSQUERY_OR ){
  110968. return 2;
  110969. }
  110970. assert( p->eType==FTSQUERY_AND );
  110971. return 3;
  110972. }
  110973. /*
  110974. ** Argument ppHead contains a pointer to the current head of a query
  110975. ** expression tree being parsed. pPrev is the expression node most recently
  110976. ** inserted into the tree. This function adds pNew, which is always a binary
  110977. ** operator node, into the expression tree based on the relative precedence
  110978. ** of pNew and the existing nodes of the tree. This may result in the head
  110979. ** of the tree changing, in which case *ppHead is set to the new root node.
  110980. */
  110981. static void insertBinaryOperator(
  110982. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  110983. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  110984. Fts3Expr *pNew /* New binary node to insert into expression tree */
  110985. ){
  110986. Fts3Expr *pSplit = pPrev;
  110987. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  110988. pSplit = pSplit->pParent;
  110989. }
  110990. if( pSplit->pParent ){
  110991. assert( pSplit->pParent->pRight==pSplit );
  110992. pSplit->pParent->pRight = pNew;
  110993. pNew->pParent = pSplit->pParent;
  110994. }else{
  110995. *ppHead = pNew;
  110996. }
  110997. pNew->pLeft = pSplit;
  110998. pSplit->pParent = pNew;
  110999. }
  111000. /*
  111001. ** Parse the fts3 query expression found in buffer z, length n. This function
  111002. ** returns either when the end of the buffer is reached or an unmatched
  111003. ** closing bracket - ')' - is encountered.
  111004. **
  111005. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  111006. ** parsed form of the expression and *pnConsumed is set to the number of
  111007. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  111008. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  111009. */
  111010. static int fts3ExprParse(
  111011. ParseContext *pParse, /* fts3 query parse context */
  111012. const char *z, int n, /* Text of MATCH query */
  111013. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  111014. int *pnConsumed /* OUT: Number of bytes consumed */
  111015. ){
  111016. Fts3Expr *pRet = 0;
  111017. Fts3Expr *pPrev = 0;
  111018. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  111019. int nIn = n;
  111020. const char *zIn = z;
  111021. int rc = SQLITE_OK;
  111022. int isRequirePhrase = 1;
  111023. while( rc==SQLITE_OK ){
  111024. Fts3Expr *p = 0;
  111025. int nByte = 0;
  111026. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  111027. if( rc==SQLITE_OK ){
  111028. int isPhrase;
  111029. if( !sqlite3_fts3_enable_parentheses
  111030. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  111031. ){
  111032. /* Create an implicit NOT operator. */
  111033. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  111034. if( !pNot ){
  111035. sqlite3Fts3ExprFree(p);
  111036. rc = SQLITE_NOMEM;
  111037. goto exprparse_out;
  111038. }
  111039. pNot->eType = FTSQUERY_NOT;
  111040. pNot->pRight = p;
  111041. p->pParent = pNot;
  111042. if( pNotBranch ){
  111043. pNot->pLeft = pNotBranch;
  111044. pNotBranch->pParent = pNot;
  111045. }
  111046. pNotBranch = pNot;
  111047. p = pPrev;
  111048. }else{
  111049. int eType = p->eType;
  111050. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  111051. /* The isRequirePhrase variable is set to true if a phrase or
  111052. ** an expression contained in parenthesis is required. If a
  111053. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  111054. ** isRequirePhrase is set, this is a syntax error.
  111055. */
  111056. if( !isPhrase && isRequirePhrase ){
  111057. sqlite3Fts3ExprFree(p);
  111058. rc = SQLITE_ERROR;
  111059. goto exprparse_out;
  111060. }
  111061. if( isPhrase && !isRequirePhrase ){
  111062. /* Insert an implicit AND operator. */
  111063. Fts3Expr *pAnd;
  111064. assert( pRet && pPrev );
  111065. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  111066. if( !pAnd ){
  111067. sqlite3Fts3ExprFree(p);
  111068. rc = SQLITE_NOMEM;
  111069. goto exprparse_out;
  111070. }
  111071. pAnd->eType = FTSQUERY_AND;
  111072. insertBinaryOperator(&pRet, pPrev, pAnd);
  111073. pPrev = pAnd;
  111074. }
  111075. /* This test catches attempts to make either operand of a NEAR
  111076. ** operator something other than a phrase. For example, either of
  111077. ** the following:
  111078. **
  111079. ** (bracketed expression) NEAR phrase
  111080. ** phrase NEAR (bracketed expression)
  111081. **
  111082. ** Return an error in either case.
  111083. */
  111084. if( pPrev && (
  111085. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  111086. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  111087. )){
  111088. sqlite3Fts3ExprFree(p);
  111089. rc = SQLITE_ERROR;
  111090. goto exprparse_out;
  111091. }
  111092. if( isPhrase ){
  111093. if( pRet ){
  111094. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  111095. pPrev->pRight = p;
  111096. p->pParent = pPrev;
  111097. }else{
  111098. pRet = p;
  111099. }
  111100. }else{
  111101. insertBinaryOperator(&pRet, pPrev, p);
  111102. }
  111103. isRequirePhrase = !isPhrase;
  111104. }
  111105. assert( nByte>0 );
  111106. }
  111107. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  111108. nIn -= nByte;
  111109. zIn += nByte;
  111110. pPrev = p;
  111111. }
  111112. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  111113. rc = SQLITE_ERROR;
  111114. }
  111115. if( rc==SQLITE_DONE ){
  111116. rc = SQLITE_OK;
  111117. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  111118. if( !pRet ){
  111119. rc = SQLITE_ERROR;
  111120. }else{
  111121. Fts3Expr *pIter = pNotBranch;
  111122. while( pIter->pLeft ){
  111123. pIter = pIter->pLeft;
  111124. }
  111125. pIter->pLeft = pRet;
  111126. pRet->pParent = pIter;
  111127. pRet = pNotBranch;
  111128. }
  111129. }
  111130. }
  111131. *pnConsumed = n - nIn;
  111132. exprparse_out:
  111133. if( rc!=SQLITE_OK ){
  111134. sqlite3Fts3ExprFree(pRet);
  111135. sqlite3Fts3ExprFree(pNotBranch);
  111136. pRet = 0;
  111137. }
  111138. *ppExpr = pRet;
  111139. return rc;
  111140. }
  111141. /*
  111142. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  111143. ** as the only argument is more than nMaxDepth.
  111144. */
  111145. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  111146. int rc = SQLITE_OK;
  111147. if( p ){
  111148. if( nMaxDepth<0 ){
  111149. rc = SQLITE_TOOBIG;
  111150. }else{
  111151. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  111152. if( rc==SQLITE_OK ){
  111153. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  111154. }
  111155. }
  111156. }
  111157. return rc;
  111158. }
  111159. /*
  111160. ** This function attempts to transform the expression tree at (*pp) to
  111161. ** an equivalent but more balanced form. The tree is modified in place.
  111162. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  111163. ** new root expression node.
  111164. **
  111165. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  111166. **
  111167. ** Otherwise, if an error occurs, an SQLite error code is returned and
  111168. ** expression (*pp) freed.
  111169. */
  111170. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  111171. int rc = SQLITE_OK; /* Return code */
  111172. Fts3Expr *pRoot = *pp; /* Initial root node */
  111173. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  111174. int eType = pRoot->eType; /* Type of node in this tree */
  111175. if( nMaxDepth==0 ){
  111176. rc = SQLITE_ERROR;
  111177. }
  111178. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  111179. Fts3Expr **apLeaf;
  111180. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  111181. if( 0==apLeaf ){
  111182. rc = SQLITE_NOMEM;
  111183. }else{
  111184. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  111185. }
  111186. if( rc==SQLITE_OK ){
  111187. int i;
  111188. Fts3Expr *p;
  111189. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  111190. for(p=pRoot; p->eType==eType; p=p->pLeft){
  111191. assert( p->pParent==0 || p->pParent->pLeft==p );
  111192. assert( p->pLeft && p->pRight );
  111193. }
  111194. /* This loop runs once for each leaf in the tree of eType nodes. */
  111195. while( 1 ){
  111196. int iLvl;
  111197. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  111198. assert( pParent==0 || pParent->pLeft==p );
  111199. p->pParent = 0;
  111200. if( pParent ){
  111201. pParent->pLeft = 0;
  111202. }else{
  111203. pRoot = 0;
  111204. }
  111205. rc = fts3ExprBalance(&p, nMaxDepth-1);
  111206. if( rc!=SQLITE_OK ) break;
  111207. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  111208. if( apLeaf[iLvl]==0 ){
  111209. apLeaf[iLvl] = p;
  111210. p = 0;
  111211. }else{
  111212. assert( pFree );
  111213. pFree->pLeft = apLeaf[iLvl];
  111214. pFree->pRight = p;
  111215. pFree->pLeft->pParent = pFree;
  111216. pFree->pRight->pParent = pFree;
  111217. p = pFree;
  111218. pFree = pFree->pParent;
  111219. p->pParent = 0;
  111220. apLeaf[iLvl] = 0;
  111221. }
  111222. }
  111223. if( p ){
  111224. sqlite3Fts3ExprFree(p);
  111225. rc = SQLITE_TOOBIG;
  111226. break;
  111227. }
  111228. /* If that was the last leaf node, break out of the loop */
  111229. if( pParent==0 ) break;
  111230. /* Set $p to point to the next leaf in the tree of eType nodes */
  111231. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  111232. /* Remove pParent from the original tree. */
  111233. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  111234. pParent->pRight->pParent = pParent->pParent;
  111235. if( pParent->pParent ){
  111236. pParent->pParent->pLeft = pParent->pRight;
  111237. }else{
  111238. assert( pParent==pRoot );
  111239. pRoot = pParent->pRight;
  111240. }
  111241. /* Link pParent into the free node list. It will be used as an
  111242. ** internal node of the new tree. */
  111243. pParent->pParent = pFree;
  111244. pFree = pParent;
  111245. }
  111246. if( rc==SQLITE_OK ){
  111247. p = 0;
  111248. for(i=0; i<nMaxDepth; i++){
  111249. if( apLeaf[i] ){
  111250. if( p==0 ){
  111251. p = apLeaf[i];
  111252. p->pParent = 0;
  111253. }else{
  111254. assert( pFree!=0 );
  111255. pFree->pRight = p;
  111256. pFree->pLeft = apLeaf[i];
  111257. pFree->pLeft->pParent = pFree;
  111258. pFree->pRight->pParent = pFree;
  111259. p = pFree;
  111260. pFree = pFree->pParent;
  111261. p->pParent = 0;
  111262. }
  111263. }
  111264. }
  111265. pRoot = p;
  111266. }else{
  111267. /* An error occurred. Delete the contents of the apLeaf[] array
  111268. ** and pFree list. Everything else is cleaned up by the call to
  111269. ** sqlite3Fts3ExprFree(pRoot) below. */
  111270. Fts3Expr *pDel;
  111271. for(i=0; i<nMaxDepth; i++){
  111272. sqlite3Fts3ExprFree(apLeaf[i]);
  111273. }
  111274. while( (pDel=pFree)!=0 ){
  111275. pFree = pDel->pParent;
  111276. sqlite3_free(pDel);
  111277. }
  111278. }
  111279. assert( pFree==0 );
  111280. sqlite3_free( apLeaf );
  111281. }
  111282. }
  111283. if( rc!=SQLITE_OK ){
  111284. sqlite3Fts3ExprFree(pRoot);
  111285. pRoot = 0;
  111286. }
  111287. *pp = pRoot;
  111288. return rc;
  111289. }
  111290. /*
  111291. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  111292. ** differences:
  111293. **
  111294. ** 1. It does not do expression rebalancing.
  111295. ** 2. It does not check that the expression does not exceed the
  111296. ** maximum allowable depth.
  111297. ** 3. Even if it fails, *ppExpr may still be set to point to an
  111298. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  111299. ** in this case.
  111300. */
  111301. static int fts3ExprParseUnbalanced(
  111302. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  111303. int iLangid, /* Language id for tokenizer */
  111304. char **azCol, /* Array of column names for fts3 table */
  111305. int bFts4, /* True to allow FTS4-only syntax */
  111306. int nCol, /* Number of entries in azCol[] */
  111307. int iDefaultCol, /* Default column to query */
  111308. const char *z, int n, /* Text of MATCH query */
  111309. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  111310. ){
  111311. int nParsed;
  111312. int rc;
  111313. ParseContext sParse;
  111314. memset(&sParse, 0, sizeof(ParseContext));
  111315. sParse.pTokenizer = pTokenizer;
  111316. sParse.iLangid = iLangid;
  111317. sParse.azCol = (const char **)azCol;
  111318. sParse.nCol = nCol;
  111319. sParse.iDefaultCol = iDefaultCol;
  111320. sParse.bFts4 = bFts4;
  111321. if( z==0 ){
  111322. *ppExpr = 0;
  111323. return SQLITE_OK;
  111324. }
  111325. if( n<0 ){
  111326. n = (int)strlen(z);
  111327. }
  111328. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  111329. assert( rc==SQLITE_OK || *ppExpr==0 );
  111330. /* Check for mismatched parenthesis */
  111331. if( rc==SQLITE_OK && sParse.nNest ){
  111332. rc = SQLITE_ERROR;
  111333. }
  111334. return rc;
  111335. }
  111336. /*
  111337. ** Parameters z and n contain a pointer to and length of a buffer containing
  111338. ** an fts3 query expression, respectively. This function attempts to parse the
  111339. ** query expression and create a tree of Fts3Expr structures representing the
  111340. ** parsed expression. If successful, *ppExpr is set to point to the head
  111341. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  111342. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  111343. ** error) is returned and *ppExpr is set to 0.
  111344. **
  111345. ** If parameter n is a negative number, then z is assumed to point to a
  111346. ** nul-terminated string and the length is determined using strlen().
  111347. **
  111348. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  111349. ** use to normalize query tokens while parsing the expression. The azCol[]
  111350. ** array, which is assumed to contain nCol entries, should contain the names
  111351. ** of each column in the target fts3 table, in order from left to right.
  111352. ** Column names must be nul-terminated strings.
  111353. **
  111354. ** The iDefaultCol parameter should be passed the index of the table column
  111355. ** that appears on the left-hand-side of the MATCH operator (the default
  111356. ** column to match against for tokens for which a column name is not explicitly
  111357. ** specified as part of the query string), or -1 if tokens may by default
  111358. ** match any table column.
  111359. */
  111360. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  111361. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  111362. int iLangid, /* Language id for tokenizer */
  111363. char **azCol, /* Array of column names for fts3 table */
  111364. int bFts4, /* True to allow FTS4-only syntax */
  111365. int nCol, /* Number of entries in azCol[] */
  111366. int iDefaultCol, /* Default column to query */
  111367. const char *z, int n, /* Text of MATCH query */
  111368. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  111369. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  111370. ){
  111371. int rc = fts3ExprParseUnbalanced(
  111372. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  111373. );
  111374. /* Rebalance the expression. And check that its depth does not exceed
  111375. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  111376. if( rc==SQLITE_OK && *ppExpr ){
  111377. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  111378. if( rc==SQLITE_OK ){
  111379. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  111380. }
  111381. }
  111382. if( rc!=SQLITE_OK ){
  111383. sqlite3Fts3ExprFree(*ppExpr);
  111384. *ppExpr = 0;
  111385. if( rc==SQLITE_TOOBIG ){
  111386. *pzErr = sqlite3_mprintf(
  111387. "FTS expression tree is too large (maximum depth %d)",
  111388. SQLITE_FTS3_MAX_EXPR_DEPTH
  111389. );
  111390. rc = SQLITE_ERROR;
  111391. }else if( rc==SQLITE_ERROR ){
  111392. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  111393. }
  111394. }
  111395. return rc;
  111396. }
  111397. /*
  111398. ** Free a single node of an expression tree.
  111399. */
  111400. static void fts3FreeExprNode(Fts3Expr *p){
  111401. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  111402. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  111403. sqlite3_free(p->aMI);
  111404. sqlite3_free(p);
  111405. }
  111406. /*
  111407. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  111408. **
  111409. ** This function would be simpler if it recursively called itself. But
  111410. ** that would mean passing a sufficiently large expression to ExprParse()
  111411. ** could cause a stack overflow.
  111412. */
  111413. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  111414. Fts3Expr *p;
  111415. assert( pDel==0 || pDel->pParent==0 );
  111416. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  111417. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  111418. }
  111419. while( p ){
  111420. Fts3Expr *pParent = p->pParent;
  111421. fts3FreeExprNode(p);
  111422. if( pParent && p==pParent->pLeft && pParent->pRight ){
  111423. p = pParent->pRight;
  111424. while( p && (p->pLeft || p->pRight) ){
  111425. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  111426. p = (p->pLeft ? p->pLeft : p->pRight);
  111427. }
  111428. }else{
  111429. p = pParent;
  111430. }
  111431. }
  111432. }
  111433. /****************************************************************************
  111434. *****************************************************************************
  111435. ** Everything after this point is just test code.
  111436. */
  111437. #ifdef SQLITE_TEST
  111438. /* #include <stdio.h> */
  111439. /*
  111440. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  111441. */
  111442. static int queryTestTokenizer(
  111443. sqlite3 *db,
  111444. const char *zName,
  111445. const sqlite3_tokenizer_module **pp
  111446. ){
  111447. int rc;
  111448. sqlite3_stmt *pStmt;
  111449. const char zSql[] = "SELECT fts3_tokenizer(?)";
  111450. *pp = 0;
  111451. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  111452. if( rc!=SQLITE_OK ){
  111453. return rc;
  111454. }
  111455. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  111456. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  111457. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  111458. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  111459. }
  111460. }
  111461. return sqlite3_finalize(pStmt);
  111462. }
  111463. /*
  111464. ** Return a pointer to a buffer containing a text representation of the
  111465. ** expression passed as the first argument. The buffer is obtained from
  111466. ** sqlite3_malloc(). It is the responsibility of the caller to use
  111467. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  111468. ** NULL is returned.
  111469. **
  111470. ** If the second argument is not NULL, then its contents are prepended to
  111471. ** the returned expression text and then freed using sqlite3_free().
  111472. */
  111473. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  111474. if( pExpr==0 ){
  111475. return sqlite3_mprintf("");
  111476. }
  111477. switch( pExpr->eType ){
  111478. case FTSQUERY_PHRASE: {
  111479. Fts3Phrase *pPhrase = pExpr->pPhrase;
  111480. int i;
  111481. zBuf = sqlite3_mprintf(
  111482. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  111483. for(i=0; zBuf && i<pPhrase->nToken; i++){
  111484. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  111485. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  111486. (pPhrase->aToken[i].isPrefix?"+":"")
  111487. );
  111488. }
  111489. return zBuf;
  111490. }
  111491. case FTSQUERY_NEAR:
  111492. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  111493. break;
  111494. case FTSQUERY_NOT:
  111495. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  111496. break;
  111497. case FTSQUERY_AND:
  111498. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  111499. break;
  111500. case FTSQUERY_OR:
  111501. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  111502. break;
  111503. }
  111504. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  111505. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  111506. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  111507. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  111508. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  111509. return zBuf;
  111510. }
  111511. /*
  111512. ** This is the implementation of a scalar SQL function used to test the
  111513. ** expression parser. It should be called as follows:
  111514. **
  111515. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  111516. **
  111517. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  111518. ** to parse the query expression (see README.tokenizers). The second argument
  111519. ** is the query expression to parse. Each subsequent argument is the name
  111520. ** of a column of the fts3 table that the query expression may refer to.
  111521. ** For example:
  111522. **
  111523. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  111524. */
  111525. static void fts3ExprTest(
  111526. sqlite3_context *context,
  111527. int argc,
  111528. sqlite3_value **argv
  111529. ){
  111530. sqlite3_tokenizer_module const *pModule = 0;
  111531. sqlite3_tokenizer *pTokenizer = 0;
  111532. int rc;
  111533. char **azCol = 0;
  111534. const char *zExpr;
  111535. int nExpr;
  111536. int nCol;
  111537. int ii;
  111538. Fts3Expr *pExpr;
  111539. char *zBuf = 0;
  111540. sqlite3 *db = sqlite3_context_db_handle(context);
  111541. if( argc<3 ){
  111542. sqlite3_result_error(context,
  111543. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  111544. );
  111545. return;
  111546. }
  111547. rc = queryTestTokenizer(db,
  111548. (const char *)sqlite3_value_text(argv[0]), &pModule);
  111549. if( rc==SQLITE_NOMEM ){
  111550. sqlite3_result_error_nomem(context);
  111551. goto exprtest_out;
  111552. }else if( !pModule ){
  111553. sqlite3_result_error(context, "No such tokenizer module", -1);
  111554. goto exprtest_out;
  111555. }
  111556. rc = pModule->xCreate(0, 0, &pTokenizer);
  111557. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  111558. if( rc==SQLITE_NOMEM ){
  111559. sqlite3_result_error_nomem(context);
  111560. goto exprtest_out;
  111561. }
  111562. pTokenizer->pModule = pModule;
  111563. zExpr = (const char *)sqlite3_value_text(argv[1]);
  111564. nExpr = sqlite3_value_bytes(argv[1]);
  111565. nCol = argc-2;
  111566. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  111567. if( !azCol ){
  111568. sqlite3_result_error_nomem(context);
  111569. goto exprtest_out;
  111570. }
  111571. for(ii=0; ii<nCol; ii++){
  111572. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  111573. }
  111574. if( sqlite3_user_data(context) ){
  111575. char *zDummy = 0;
  111576. rc = sqlite3Fts3ExprParse(
  111577. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  111578. );
  111579. assert( rc==SQLITE_OK || pExpr==0 );
  111580. sqlite3_free(zDummy);
  111581. }else{
  111582. rc = fts3ExprParseUnbalanced(
  111583. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  111584. );
  111585. }
  111586. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  111587. sqlite3Fts3ExprFree(pExpr);
  111588. sqlite3_result_error(context, "Error parsing expression", -1);
  111589. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  111590. sqlite3_result_error_nomem(context);
  111591. }else{
  111592. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  111593. sqlite3_free(zBuf);
  111594. }
  111595. sqlite3Fts3ExprFree(pExpr);
  111596. exprtest_out:
  111597. if( pModule && pTokenizer ){
  111598. rc = pModule->xDestroy(pTokenizer);
  111599. }
  111600. sqlite3_free(azCol);
  111601. }
  111602. /*
  111603. ** Register the query expression parser test function fts3_exprtest()
  111604. ** with database connection db.
  111605. */
  111606. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  111607. int rc = sqlite3_create_function(
  111608. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  111609. );
  111610. if( rc==SQLITE_OK ){
  111611. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  111612. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  111613. );
  111614. }
  111615. return rc;
  111616. }
  111617. #endif
  111618. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  111619. /************** End of fts3_expr.c *******************************************/
  111620. /************** Begin file fts3_hash.c ***************************************/
  111621. /*
  111622. ** 2001 September 22
  111623. **
  111624. ** The author disclaims copyright to this source code. In place of
  111625. ** a legal notice, here is a blessing:
  111626. **
  111627. ** May you do good and not evil.
  111628. ** May you find forgiveness for yourself and forgive others.
  111629. ** May you share freely, never taking more than you give.
  111630. **
  111631. *************************************************************************
  111632. ** This is the implementation of generic hash-tables used in SQLite.
  111633. ** We've modified it slightly to serve as a standalone hash table
  111634. ** implementation for the full-text indexing module.
  111635. */
  111636. /*
  111637. ** The code in this file is only compiled if:
  111638. **
  111639. ** * The FTS3 module is being built as an extension
  111640. ** (in which case SQLITE_CORE is not defined), or
  111641. **
  111642. ** * The FTS3 module is being built into the core of
  111643. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  111644. */
  111645. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  111646. /* #include <assert.h> */
  111647. /* #include <stdlib.h> */
  111648. /* #include <string.h> */
  111649. /*
  111650. ** Malloc and Free functions
  111651. */
  111652. static void *fts3HashMalloc(int n){
  111653. void *p = sqlite3_malloc(n);
  111654. if( p ){
  111655. memset(p, 0, n);
  111656. }
  111657. return p;
  111658. }
  111659. static void fts3HashFree(void *p){
  111660. sqlite3_free(p);
  111661. }
  111662. /* Turn bulk memory into a hash table object by initializing the
  111663. ** fields of the Hash structure.
  111664. **
  111665. ** "pNew" is a pointer to the hash table that is to be initialized.
  111666. ** keyClass is one of the constants
  111667. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  111668. ** determines what kind of key the hash table will use. "copyKey" is
  111669. ** true if the hash table should make its own private copy of keys and
  111670. ** false if it should just use the supplied pointer.
  111671. */
  111672. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  111673. assert( pNew!=0 );
  111674. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  111675. pNew->keyClass = keyClass;
  111676. pNew->copyKey = copyKey;
  111677. pNew->first = 0;
  111678. pNew->count = 0;
  111679. pNew->htsize = 0;
  111680. pNew->ht = 0;
  111681. }
  111682. /* Remove all entries from a hash table. Reclaim all memory.
  111683. ** Call this routine to delete a hash table or to reset a hash table
  111684. ** to the empty state.
  111685. */
  111686. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  111687. Fts3HashElem *elem; /* For looping over all elements of the table */
  111688. assert( pH!=0 );
  111689. elem = pH->first;
  111690. pH->first = 0;
  111691. fts3HashFree(pH->ht);
  111692. pH->ht = 0;
  111693. pH->htsize = 0;
  111694. while( elem ){
  111695. Fts3HashElem *next_elem = elem->next;
  111696. if( pH->copyKey && elem->pKey ){
  111697. fts3HashFree(elem->pKey);
  111698. }
  111699. fts3HashFree(elem);
  111700. elem = next_elem;
  111701. }
  111702. pH->count = 0;
  111703. }
  111704. /*
  111705. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  111706. */
  111707. static int fts3StrHash(const void *pKey, int nKey){
  111708. const char *z = (const char *)pKey;
  111709. int h = 0;
  111710. if( nKey<=0 ) nKey = (int) strlen(z);
  111711. while( nKey > 0 ){
  111712. h = (h<<3) ^ h ^ *z++;
  111713. nKey--;
  111714. }
  111715. return h & 0x7fffffff;
  111716. }
  111717. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  111718. if( n1!=n2 ) return 1;
  111719. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  111720. }
  111721. /*
  111722. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  111723. */
  111724. static int fts3BinHash(const void *pKey, int nKey){
  111725. int h = 0;
  111726. const char *z = (const char *)pKey;
  111727. while( nKey-- > 0 ){
  111728. h = (h<<3) ^ h ^ *(z++);
  111729. }
  111730. return h & 0x7fffffff;
  111731. }
  111732. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  111733. if( n1!=n2 ) return 1;
  111734. return memcmp(pKey1,pKey2,n1);
  111735. }
  111736. /*
  111737. ** Return a pointer to the appropriate hash function given the key class.
  111738. **
  111739. ** The C syntax in this function definition may be unfamilar to some
  111740. ** programmers, so we provide the following additional explanation:
  111741. **
  111742. ** The name of the function is "ftsHashFunction". The function takes a
  111743. ** single parameter "keyClass". The return value of ftsHashFunction()
  111744. ** is a pointer to another function. Specifically, the return value
  111745. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  111746. ** with types "const void*" and "int" and returns an "int".
  111747. */
  111748. static int (*ftsHashFunction(int keyClass))(const void*,int){
  111749. if( keyClass==FTS3_HASH_STRING ){
  111750. return &fts3StrHash;
  111751. }else{
  111752. assert( keyClass==FTS3_HASH_BINARY );
  111753. return &fts3BinHash;
  111754. }
  111755. }
  111756. /*
  111757. ** Return a pointer to the appropriate hash function given the key class.
  111758. **
  111759. ** For help in interpreted the obscure C code in the function definition,
  111760. ** see the header comment on the previous function.
  111761. */
  111762. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  111763. if( keyClass==FTS3_HASH_STRING ){
  111764. return &fts3StrCompare;
  111765. }else{
  111766. assert( keyClass==FTS3_HASH_BINARY );
  111767. return &fts3BinCompare;
  111768. }
  111769. }
  111770. /* Link an element into the hash table
  111771. */
  111772. static void fts3HashInsertElement(
  111773. Fts3Hash *pH, /* The complete hash table */
  111774. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  111775. Fts3HashElem *pNew /* The element to be inserted */
  111776. ){
  111777. Fts3HashElem *pHead; /* First element already in pEntry */
  111778. pHead = pEntry->chain;
  111779. if( pHead ){
  111780. pNew->next = pHead;
  111781. pNew->prev = pHead->prev;
  111782. if( pHead->prev ){ pHead->prev->next = pNew; }
  111783. else { pH->first = pNew; }
  111784. pHead->prev = pNew;
  111785. }else{
  111786. pNew->next = pH->first;
  111787. if( pH->first ){ pH->first->prev = pNew; }
  111788. pNew->prev = 0;
  111789. pH->first = pNew;
  111790. }
  111791. pEntry->count++;
  111792. pEntry->chain = pNew;
  111793. }
  111794. /* Resize the hash table so that it cantains "new_size" buckets.
  111795. ** "new_size" must be a power of 2. The hash table might fail
  111796. ** to resize if sqliteMalloc() fails.
  111797. **
  111798. ** Return non-zero if a memory allocation error occurs.
  111799. */
  111800. static int fts3Rehash(Fts3Hash *pH, int new_size){
  111801. struct _fts3ht *new_ht; /* The new hash table */
  111802. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  111803. int (*xHash)(const void*,int); /* The hash function */
  111804. assert( (new_size & (new_size-1))==0 );
  111805. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  111806. if( new_ht==0 ) return 1;
  111807. fts3HashFree(pH->ht);
  111808. pH->ht = new_ht;
  111809. pH->htsize = new_size;
  111810. xHash = ftsHashFunction(pH->keyClass);
  111811. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  111812. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  111813. next_elem = elem->next;
  111814. fts3HashInsertElement(pH, &new_ht[h], elem);
  111815. }
  111816. return 0;
  111817. }
  111818. /* This function (for internal use only) locates an element in an
  111819. ** hash table that matches the given key. The hash for this key has
  111820. ** already been computed and is passed as the 4th parameter.
  111821. */
  111822. static Fts3HashElem *fts3FindElementByHash(
  111823. const Fts3Hash *pH, /* The pH to be searched */
  111824. const void *pKey, /* The key we are searching for */
  111825. int nKey,
  111826. int h /* The hash for this key. */
  111827. ){
  111828. Fts3HashElem *elem; /* Used to loop thru the element list */
  111829. int count; /* Number of elements left to test */
  111830. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  111831. if( pH->ht ){
  111832. struct _fts3ht *pEntry = &pH->ht[h];
  111833. elem = pEntry->chain;
  111834. count = pEntry->count;
  111835. xCompare = ftsCompareFunction(pH->keyClass);
  111836. while( count-- && elem ){
  111837. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  111838. return elem;
  111839. }
  111840. elem = elem->next;
  111841. }
  111842. }
  111843. return 0;
  111844. }
  111845. /* Remove a single entry from the hash table given a pointer to that
  111846. ** element and a hash on the element's key.
  111847. */
  111848. static void fts3RemoveElementByHash(
  111849. Fts3Hash *pH, /* The pH containing "elem" */
  111850. Fts3HashElem* elem, /* The element to be removed from the pH */
  111851. int h /* Hash value for the element */
  111852. ){
  111853. struct _fts3ht *pEntry;
  111854. if( elem->prev ){
  111855. elem->prev->next = elem->next;
  111856. }else{
  111857. pH->first = elem->next;
  111858. }
  111859. if( elem->next ){
  111860. elem->next->prev = elem->prev;
  111861. }
  111862. pEntry = &pH->ht[h];
  111863. if( pEntry->chain==elem ){
  111864. pEntry->chain = elem->next;
  111865. }
  111866. pEntry->count--;
  111867. if( pEntry->count<=0 ){
  111868. pEntry->chain = 0;
  111869. }
  111870. if( pH->copyKey && elem->pKey ){
  111871. fts3HashFree(elem->pKey);
  111872. }
  111873. fts3HashFree( elem );
  111874. pH->count--;
  111875. if( pH->count<=0 ){
  111876. assert( pH->first==0 );
  111877. assert( pH->count==0 );
  111878. fts3HashClear(pH);
  111879. }
  111880. }
  111881. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  111882. const Fts3Hash *pH,
  111883. const void *pKey,
  111884. int nKey
  111885. ){
  111886. int h; /* A hash on key */
  111887. int (*xHash)(const void*,int); /* The hash function */
  111888. if( pH==0 || pH->ht==0 ) return 0;
  111889. xHash = ftsHashFunction(pH->keyClass);
  111890. assert( xHash!=0 );
  111891. h = (*xHash)(pKey,nKey);
  111892. assert( (pH->htsize & (pH->htsize-1))==0 );
  111893. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  111894. }
  111895. /*
  111896. ** Attempt to locate an element of the hash table pH with a key
  111897. ** that matches pKey,nKey. Return the data for this element if it is
  111898. ** found, or NULL if there is no match.
  111899. */
  111900. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  111901. Fts3HashElem *pElem; /* The element that matches key (if any) */
  111902. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  111903. return pElem ? pElem->data : 0;
  111904. }
  111905. /* Insert an element into the hash table pH. The key is pKey,nKey
  111906. ** and the data is "data".
  111907. **
  111908. ** If no element exists with a matching key, then a new
  111909. ** element is created. A copy of the key is made if the copyKey
  111910. ** flag is set. NULL is returned.
  111911. **
  111912. ** If another element already exists with the same key, then the
  111913. ** new data replaces the old data and the old data is returned.
  111914. ** The key is not copied in this instance. If a malloc fails, then
  111915. ** the new data is returned and the hash table is unchanged.
  111916. **
  111917. ** If the "data" parameter to this function is NULL, then the
  111918. ** element corresponding to "key" is removed from the hash table.
  111919. */
  111920. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  111921. Fts3Hash *pH, /* The hash table to insert into */
  111922. const void *pKey, /* The key */
  111923. int nKey, /* Number of bytes in the key */
  111924. void *data /* The data */
  111925. ){
  111926. int hraw; /* Raw hash value of the key */
  111927. int h; /* the hash of the key modulo hash table size */
  111928. Fts3HashElem *elem; /* Used to loop thru the element list */
  111929. Fts3HashElem *new_elem; /* New element added to the pH */
  111930. int (*xHash)(const void*,int); /* The hash function */
  111931. assert( pH!=0 );
  111932. xHash = ftsHashFunction(pH->keyClass);
  111933. assert( xHash!=0 );
  111934. hraw = (*xHash)(pKey, nKey);
  111935. assert( (pH->htsize & (pH->htsize-1))==0 );
  111936. h = hraw & (pH->htsize-1);
  111937. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  111938. if( elem ){
  111939. void *old_data = elem->data;
  111940. if( data==0 ){
  111941. fts3RemoveElementByHash(pH,elem,h);
  111942. }else{
  111943. elem->data = data;
  111944. }
  111945. return old_data;
  111946. }
  111947. if( data==0 ) return 0;
  111948. if( (pH->htsize==0 && fts3Rehash(pH,8))
  111949. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  111950. ){
  111951. pH->count = 0;
  111952. return data;
  111953. }
  111954. assert( pH->htsize>0 );
  111955. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  111956. if( new_elem==0 ) return data;
  111957. if( pH->copyKey && pKey!=0 ){
  111958. new_elem->pKey = fts3HashMalloc( nKey );
  111959. if( new_elem->pKey==0 ){
  111960. fts3HashFree(new_elem);
  111961. return data;
  111962. }
  111963. memcpy((void*)new_elem->pKey, pKey, nKey);
  111964. }else{
  111965. new_elem->pKey = (void*)pKey;
  111966. }
  111967. new_elem->nKey = nKey;
  111968. pH->count++;
  111969. assert( pH->htsize>0 );
  111970. assert( (pH->htsize & (pH->htsize-1))==0 );
  111971. h = hraw & (pH->htsize-1);
  111972. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  111973. new_elem->data = data;
  111974. return 0;
  111975. }
  111976. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  111977. /************** End of fts3_hash.c *******************************************/
  111978. /************** Begin file fts3_porter.c *************************************/
  111979. /*
  111980. ** 2006 September 30
  111981. **
  111982. ** The author disclaims copyright to this source code. In place of
  111983. ** a legal notice, here is a blessing:
  111984. **
  111985. ** May you do good and not evil.
  111986. ** May you find forgiveness for yourself and forgive others.
  111987. ** May you share freely, never taking more than you give.
  111988. **
  111989. *************************************************************************
  111990. ** Implementation of the full-text-search tokenizer that implements
  111991. ** a Porter stemmer.
  111992. */
  111993. /*
  111994. ** The code in this file is only compiled if:
  111995. **
  111996. ** * The FTS3 module is being built as an extension
  111997. ** (in which case SQLITE_CORE is not defined), or
  111998. **
  111999. ** * The FTS3 module is being built into the core of
  112000. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  112001. */
  112002. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  112003. /* #include <assert.h> */
  112004. /* #include <stdlib.h> */
  112005. /* #include <stdio.h> */
  112006. /* #include <string.h> */
  112007. /*
  112008. ** Class derived from sqlite3_tokenizer
  112009. */
  112010. typedef struct porter_tokenizer {
  112011. sqlite3_tokenizer base; /* Base class */
  112012. } porter_tokenizer;
  112013. /*
  112014. ** Class derived from sqlite3_tokenizer_cursor
  112015. */
  112016. typedef struct porter_tokenizer_cursor {
  112017. sqlite3_tokenizer_cursor base;
  112018. const char *zInput; /* input we are tokenizing */
  112019. int nInput; /* size of the input */
  112020. int iOffset; /* current position in zInput */
  112021. int iToken; /* index of next token to be returned */
  112022. char *zToken; /* storage for current token */
  112023. int nAllocated; /* space allocated to zToken buffer */
  112024. } porter_tokenizer_cursor;
  112025. /*
  112026. ** Create a new tokenizer instance.
  112027. */
  112028. static int porterCreate(
  112029. int argc, const char * const *argv,
  112030. sqlite3_tokenizer **ppTokenizer
  112031. ){
  112032. porter_tokenizer *t;
  112033. UNUSED_PARAMETER(argc);
  112034. UNUSED_PARAMETER(argv);
  112035. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  112036. if( t==NULL ) return SQLITE_NOMEM;
  112037. memset(t, 0, sizeof(*t));
  112038. *ppTokenizer = &t->base;
  112039. return SQLITE_OK;
  112040. }
  112041. /*
  112042. ** Destroy a tokenizer
  112043. */
  112044. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  112045. sqlite3_free(pTokenizer);
  112046. return SQLITE_OK;
  112047. }
  112048. /*
  112049. ** Prepare to begin tokenizing a particular string. The input
  112050. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  112051. ** used to incrementally tokenize this string is returned in
  112052. ** *ppCursor.
  112053. */
  112054. static int porterOpen(
  112055. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  112056. const char *zInput, int nInput, /* String to be tokenized */
  112057. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  112058. ){
  112059. porter_tokenizer_cursor *c;
  112060. UNUSED_PARAMETER(pTokenizer);
  112061. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  112062. if( c==NULL ) return SQLITE_NOMEM;
  112063. c->zInput = zInput;
  112064. if( zInput==0 ){
  112065. c->nInput = 0;
  112066. }else if( nInput<0 ){
  112067. c->nInput = (int)strlen(zInput);
  112068. }else{
  112069. c->nInput = nInput;
  112070. }
  112071. c->iOffset = 0; /* start tokenizing at the beginning */
  112072. c->iToken = 0;
  112073. c->zToken = NULL; /* no space allocated, yet. */
  112074. c->nAllocated = 0;
  112075. *ppCursor = &c->base;
  112076. return SQLITE_OK;
  112077. }
  112078. /*
  112079. ** Close a tokenization cursor previously opened by a call to
  112080. ** porterOpen() above.
  112081. */
  112082. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  112083. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  112084. sqlite3_free(c->zToken);
  112085. sqlite3_free(c);
  112086. return SQLITE_OK;
  112087. }
  112088. /*
  112089. ** Vowel or consonant
  112090. */
  112091. static const char cType[] = {
  112092. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  112093. 1, 1, 1, 2, 1
  112094. };
  112095. /*
  112096. ** isConsonant() and isVowel() determine if their first character in
  112097. ** the string they point to is a consonant or a vowel, according
  112098. ** to Porter ruls.
  112099. **
  112100. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  112101. ** 'Y' is a consonant unless it follows another consonant,
  112102. ** in which case it is a vowel.
  112103. **
  112104. ** In these routine, the letters are in reverse order. So the 'y' rule
  112105. ** is that 'y' is a consonant unless it is followed by another
  112106. ** consonent.
  112107. */
  112108. static int isVowel(const char*);
  112109. static int isConsonant(const char *z){
  112110. int j;
  112111. char x = *z;
  112112. if( x==0 ) return 0;
  112113. assert( x>='a' && x<='z' );
  112114. j = cType[x-'a'];
  112115. if( j<2 ) return j;
  112116. return z[1]==0 || isVowel(z + 1);
  112117. }
  112118. static int isVowel(const char *z){
  112119. int j;
  112120. char x = *z;
  112121. if( x==0 ) return 0;
  112122. assert( x>='a' && x<='z' );
  112123. j = cType[x-'a'];
  112124. if( j<2 ) return 1-j;
  112125. return isConsonant(z + 1);
  112126. }
  112127. /*
  112128. ** Let any sequence of one or more vowels be represented by V and let
  112129. ** C be sequence of one or more consonants. Then every word can be
  112130. ** represented as:
  112131. **
  112132. ** [C] (VC){m} [V]
  112133. **
  112134. ** In prose: A word is an optional consonant followed by zero or
  112135. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  112136. ** number of vowel consonant pairs. This routine computes the value
  112137. ** of m for the first i bytes of a word.
  112138. **
  112139. ** Return true if the m-value for z is 1 or more. In other words,
  112140. ** return true if z contains at least one vowel that is followed
  112141. ** by a consonant.
  112142. **
  112143. ** In this routine z[] is in reverse order. So we are really looking
  112144. ** for an instance of of a consonant followed by a vowel.
  112145. */
  112146. static int m_gt_0(const char *z){
  112147. while( isVowel(z) ){ z++; }
  112148. if( *z==0 ) return 0;
  112149. while( isConsonant(z) ){ z++; }
  112150. return *z!=0;
  112151. }
  112152. /* Like mgt0 above except we are looking for a value of m which is
  112153. ** exactly 1
  112154. */
  112155. static int m_eq_1(const char *z){
  112156. while( isVowel(z) ){ z++; }
  112157. if( *z==0 ) return 0;
  112158. while( isConsonant(z) ){ z++; }
  112159. if( *z==0 ) return 0;
  112160. while( isVowel(z) ){ z++; }
  112161. if( *z==0 ) return 1;
  112162. while( isConsonant(z) ){ z++; }
  112163. return *z==0;
  112164. }
  112165. /* Like mgt0 above except we are looking for a value of m>1 instead
  112166. ** or m>0
  112167. */
  112168. static int m_gt_1(const char *z){
  112169. while( isVowel(z) ){ z++; }
  112170. if( *z==0 ) return 0;
  112171. while( isConsonant(z) ){ z++; }
  112172. if( *z==0 ) return 0;
  112173. while( isVowel(z) ){ z++; }
  112174. if( *z==0 ) return 0;
  112175. while( isConsonant(z) ){ z++; }
  112176. return *z!=0;
  112177. }
  112178. /*
  112179. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  112180. */
  112181. static int hasVowel(const char *z){
  112182. while( isConsonant(z) ){ z++; }
  112183. return *z!=0;
  112184. }
  112185. /*
  112186. ** Return TRUE if the word ends in a double consonant.
  112187. **
  112188. ** The text is reversed here. So we are really looking at
  112189. ** the first two characters of z[].
  112190. */
  112191. static int doubleConsonant(const char *z){
  112192. return isConsonant(z) && z[0]==z[1];
  112193. }
  112194. /*
  112195. ** Return TRUE if the word ends with three letters which
  112196. ** are consonant-vowel-consonent and where the final consonant
  112197. ** is not 'w', 'x', or 'y'.
  112198. **
  112199. ** The word is reversed here. So we are really checking the
  112200. ** first three letters and the first one cannot be in [wxy].
  112201. */
  112202. static int star_oh(const char *z){
  112203. return
  112204. isConsonant(z) &&
  112205. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  112206. isVowel(z+1) &&
  112207. isConsonant(z+2);
  112208. }
  112209. /*
  112210. ** If the word ends with zFrom and xCond() is true for the stem
  112211. ** of the word that preceeds the zFrom ending, then change the
  112212. ** ending to zTo.
  112213. **
  112214. ** The input word *pz and zFrom are both in reverse order. zTo
  112215. ** is in normal order.
  112216. **
  112217. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  112218. ** match. Not that TRUE is returned even if xCond() fails and
  112219. ** no substitution occurs.
  112220. */
  112221. static int stem(
  112222. char **pz, /* The word being stemmed (Reversed) */
  112223. const char *zFrom, /* If the ending matches this... (Reversed) */
  112224. const char *zTo, /* ... change the ending to this (not reversed) */
  112225. int (*xCond)(const char*) /* Condition that must be true */
  112226. ){
  112227. char *z = *pz;
  112228. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  112229. if( *zFrom!=0 ) return 0;
  112230. if( xCond && !xCond(z) ) return 1;
  112231. while( *zTo ){
  112232. *(--z) = *(zTo++);
  112233. }
  112234. *pz = z;
  112235. return 1;
  112236. }
  112237. /*
  112238. ** This is the fallback stemmer used when the porter stemmer is
  112239. ** inappropriate. The input word is copied into the output with
  112240. ** US-ASCII case folding. If the input word is too long (more
  112241. ** than 20 bytes if it contains no digits or more than 6 bytes if
  112242. ** it contains digits) then word is truncated to 20 or 6 bytes
  112243. ** by taking 10 or 3 bytes from the beginning and end.
  112244. */
  112245. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  112246. int i, mx, j;
  112247. int hasDigit = 0;
  112248. for(i=0; i<nIn; i++){
  112249. char c = zIn[i];
  112250. if( c>='A' && c<='Z' ){
  112251. zOut[i] = c - 'A' + 'a';
  112252. }else{
  112253. if( c>='0' && c<='9' ) hasDigit = 1;
  112254. zOut[i] = c;
  112255. }
  112256. }
  112257. mx = hasDigit ? 3 : 10;
  112258. if( nIn>mx*2 ){
  112259. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  112260. zOut[j] = zOut[i];
  112261. }
  112262. i = j;
  112263. }
  112264. zOut[i] = 0;
  112265. *pnOut = i;
  112266. }
  112267. /*
  112268. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  112269. ** zOut is at least big enough to hold nIn bytes. Write the actual
  112270. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  112271. **
  112272. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  112273. ** are converted to lower case. Upper-case UTF characters are
  112274. ** unchanged.
  112275. **
  112276. ** Words that are longer than about 20 bytes are stemmed by retaining
  112277. ** a few bytes from the beginning and the end of the word. If the
  112278. ** word contains digits, 3 bytes are taken from the beginning and
  112279. ** 3 bytes from the end. For long words without digits, 10 bytes
  112280. ** are taken from each end. US-ASCII case folding still applies.
  112281. **
  112282. ** If the input word contains not digits but does characters not
  112283. ** in [a-zA-Z] then no stemming is attempted and this routine just
  112284. ** copies the input into the input into the output with US-ASCII
  112285. ** case folding.
  112286. **
  112287. ** Stemming never increases the length of the word. So there is
  112288. ** no chance of overflowing the zOut buffer.
  112289. */
  112290. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  112291. int i, j;
  112292. char zReverse[28];
  112293. char *z, *z2;
  112294. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  112295. /* The word is too big or too small for the porter stemmer.
  112296. ** Fallback to the copy stemmer */
  112297. copy_stemmer(zIn, nIn, zOut, pnOut);
  112298. return;
  112299. }
  112300. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  112301. char c = zIn[i];
  112302. if( c>='A' && c<='Z' ){
  112303. zReverse[j] = c + 'a' - 'A';
  112304. }else if( c>='a' && c<='z' ){
  112305. zReverse[j] = c;
  112306. }else{
  112307. /* The use of a character not in [a-zA-Z] means that we fallback
  112308. ** to the copy stemmer */
  112309. copy_stemmer(zIn, nIn, zOut, pnOut);
  112310. return;
  112311. }
  112312. }
  112313. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  112314. z = &zReverse[j+1];
  112315. /* Step 1a */
  112316. if( z[0]=='s' ){
  112317. if(
  112318. !stem(&z, "sess", "ss", 0) &&
  112319. !stem(&z, "sei", "i", 0) &&
  112320. !stem(&z, "ss", "ss", 0)
  112321. ){
  112322. z++;
  112323. }
  112324. }
  112325. /* Step 1b */
  112326. z2 = z;
  112327. if( stem(&z, "dee", "ee", m_gt_0) ){
  112328. /* Do nothing. The work was all in the test */
  112329. }else if(
  112330. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  112331. && z!=z2
  112332. ){
  112333. if( stem(&z, "ta", "ate", 0) ||
  112334. stem(&z, "lb", "ble", 0) ||
  112335. stem(&z, "zi", "ize", 0) ){
  112336. /* Do nothing. The work was all in the test */
  112337. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  112338. z++;
  112339. }else if( m_eq_1(z) && star_oh(z) ){
  112340. *(--z) = 'e';
  112341. }
  112342. }
  112343. /* Step 1c */
  112344. if( z[0]=='y' && hasVowel(z+1) ){
  112345. z[0] = 'i';
  112346. }
  112347. /* Step 2 */
  112348. switch( z[1] ){
  112349. case 'a':
  112350. stem(&z, "lanoita", "ate", m_gt_0) ||
  112351. stem(&z, "lanoit", "tion", m_gt_0);
  112352. break;
  112353. case 'c':
  112354. stem(&z, "icne", "ence", m_gt_0) ||
  112355. stem(&z, "icna", "ance", m_gt_0);
  112356. break;
  112357. case 'e':
  112358. stem(&z, "rezi", "ize", m_gt_0);
  112359. break;
  112360. case 'g':
  112361. stem(&z, "igol", "log", m_gt_0);
  112362. break;
  112363. case 'l':
  112364. stem(&z, "ilb", "ble", m_gt_0) ||
  112365. stem(&z, "illa", "al", m_gt_0) ||
  112366. stem(&z, "iltne", "ent", m_gt_0) ||
  112367. stem(&z, "ile", "e", m_gt_0) ||
  112368. stem(&z, "ilsuo", "ous", m_gt_0);
  112369. break;
  112370. case 'o':
  112371. stem(&z, "noitazi", "ize", m_gt_0) ||
  112372. stem(&z, "noita", "ate", m_gt_0) ||
  112373. stem(&z, "rota", "ate", m_gt_0);
  112374. break;
  112375. case 's':
  112376. stem(&z, "msila", "al", m_gt_0) ||
  112377. stem(&z, "ssenevi", "ive", m_gt_0) ||
  112378. stem(&z, "ssenluf", "ful", m_gt_0) ||
  112379. stem(&z, "ssensuo", "ous", m_gt_0);
  112380. break;
  112381. case 't':
  112382. stem(&z, "itila", "al", m_gt_0) ||
  112383. stem(&z, "itivi", "ive", m_gt_0) ||
  112384. stem(&z, "itilib", "ble", m_gt_0);
  112385. break;
  112386. }
  112387. /* Step 3 */
  112388. switch( z[0] ){
  112389. case 'e':
  112390. stem(&z, "etaci", "ic", m_gt_0) ||
  112391. stem(&z, "evita", "", m_gt_0) ||
  112392. stem(&z, "ezila", "al", m_gt_0);
  112393. break;
  112394. case 'i':
  112395. stem(&z, "itici", "ic", m_gt_0);
  112396. break;
  112397. case 'l':
  112398. stem(&z, "laci", "ic", m_gt_0) ||
  112399. stem(&z, "luf", "", m_gt_0);
  112400. break;
  112401. case 's':
  112402. stem(&z, "ssen", "", m_gt_0);
  112403. break;
  112404. }
  112405. /* Step 4 */
  112406. switch( z[1] ){
  112407. case 'a':
  112408. if( z[0]=='l' && m_gt_1(z+2) ){
  112409. z += 2;
  112410. }
  112411. break;
  112412. case 'c':
  112413. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  112414. z += 4;
  112415. }
  112416. break;
  112417. case 'e':
  112418. if( z[0]=='r' && m_gt_1(z+2) ){
  112419. z += 2;
  112420. }
  112421. break;
  112422. case 'i':
  112423. if( z[0]=='c' && m_gt_1(z+2) ){
  112424. z += 2;
  112425. }
  112426. break;
  112427. case 'l':
  112428. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  112429. z += 4;
  112430. }
  112431. break;
  112432. case 'n':
  112433. if( z[0]=='t' ){
  112434. if( z[2]=='a' ){
  112435. if( m_gt_1(z+3) ){
  112436. z += 3;
  112437. }
  112438. }else if( z[2]=='e' ){
  112439. stem(&z, "tneme", "", m_gt_1) ||
  112440. stem(&z, "tnem", "", m_gt_1) ||
  112441. stem(&z, "tne", "", m_gt_1);
  112442. }
  112443. }
  112444. break;
  112445. case 'o':
  112446. if( z[0]=='u' ){
  112447. if( m_gt_1(z+2) ){
  112448. z += 2;
  112449. }
  112450. }else if( z[3]=='s' || z[3]=='t' ){
  112451. stem(&z, "noi", "", m_gt_1);
  112452. }
  112453. break;
  112454. case 's':
  112455. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  112456. z += 3;
  112457. }
  112458. break;
  112459. case 't':
  112460. stem(&z, "eta", "", m_gt_1) ||
  112461. stem(&z, "iti", "", m_gt_1);
  112462. break;
  112463. case 'u':
  112464. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  112465. z += 3;
  112466. }
  112467. break;
  112468. case 'v':
  112469. case 'z':
  112470. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  112471. z += 3;
  112472. }
  112473. break;
  112474. }
  112475. /* Step 5a */
  112476. if( z[0]=='e' ){
  112477. if( m_gt_1(z+1) ){
  112478. z++;
  112479. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  112480. z++;
  112481. }
  112482. }
  112483. /* Step 5b */
  112484. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  112485. z++;
  112486. }
  112487. /* z[] is now the stemmed word in reverse order. Flip it back
  112488. ** around into forward order and return.
  112489. */
  112490. *pnOut = i = (int)strlen(z);
  112491. zOut[i] = 0;
  112492. while( *z ){
  112493. zOut[--i] = *(z++);
  112494. }
  112495. }
  112496. /*
  112497. ** Characters that can be part of a token. We assume any character
  112498. ** whose value is greater than 0x80 (any UTF character) can be
  112499. ** part of a token. In other words, delimiters all must have
  112500. ** values of 0x7f or lower.
  112501. */
  112502. static const char porterIdChar[] = {
  112503. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  112504. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  112505. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  112506. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  112507. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  112508. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  112509. };
  112510. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  112511. /*
  112512. ** Extract the next token from a tokenization cursor. The cursor must
  112513. ** have been opened by a prior call to porterOpen().
  112514. */
  112515. static int porterNext(
  112516. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  112517. const char **pzToken, /* OUT: *pzToken is the token text */
  112518. int *pnBytes, /* OUT: Number of bytes in token */
  112519. int *piStartOffset, /* OUT: Starting offset of token */
  112520. int *piEndOffset, /* OUT: Ending offset of token */
  112521. int *piPosition /* OUT: Position integer of token */
  112522. ){
  112523. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  112524. const char *z = c->zInput;
  112525. while( c->iOffset<c->nInput ){
  112526. int iStartOffset, ch;
  112527. /* Scan past delimiter characters */
  112528. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  112529. c->iOffset++;
  112530. }
  112531. /* Count non-delimiter characters. */
  112532. iStartOffset = c->iOffset;
  112533. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  112534. c->iOffset++;
  112535. }
  112536. if( c->iOffset>iStartOffset ){
  112537. int n = c->iOffset-iStartOffset;
  112538. if( n>c->nAllocated ){
  112539. char *pNew;
  112540. c->nAllocated = n+20;
  112541. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  112542. if( !pNew ) return SQLITE_NOMEM;
  112543. c->zToken = pNew;
  112544. }
  112545. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  112546. *pzToken = c->zToken;
  112547. *piStartOffset = iStartOffset;
  112548. *piEndOffset = c->iOffset;
  112549. *piPosition = c->iToken++;
  112550. return SQLITE_OK;
  112551. }
  112552. }
  112553. return SQLITE_DONE;
  112554. }
  112555. /*
  112556. ** The set of routines that implement the porter-stemmer tokenizer
  112557. */
  112558. static const sqlite3_tokenizer_module porterTokenizerModule = {
  112559. 0,
  112560. porterCreate,
  112561. porterDestroy,
  112562. porterOpen,
  112563. porterClose,
  112564. porterNext,
  112565. 0
  112566. };
  112567. /*
  112568. ** Allocate a new porter tokenizer. Return a pointer to the new
  112569. ** tokenizer in *ppModule
  112570. */
  112571. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  112572. sqlite3_tokenizer_module const**ppModule
  112573. ){
  112574. *ppModule = &porterTokenizerModule;
  112575. }
  112576. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  112577. /************** End of fts3_porter.c *****************************************/
  112578. /************** Begin file fts3_tokenizer.c **********************************/
  112579. /*
  112580. ** 2007 June 22
  112581. **
  112582. ** The author disclaims copyright to this source code. In place of
  112583. ** a legal notice, here is a blessing:
  112584. **
  112585. ** May you do good and not evil.
  112586. ** May you find forgiveness for yourself and forgive others.
  112587. ** May you share freely, never taking more than you give.
  112588. **
  112589. ******************************************************************************
  112590. **
  112591. ** This is part of an SQLite module implementing full-text search.
  112592. ** This particular file implements the generic tokenizer interface.
  112593. */
  112594. /*
  112595. ** The code in this file is only compiled if:
  112596. **
  112597. ** * The FTS3 module is being built as an extension
  112598. ** (in which case SQLITE_CORE is not defined), or
  112599. **
  112600. ** * The FTS3 module is being built into the core of
  112601. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  112602. */
  112603. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  112604. /* #include <assert.h> */
  112605. /* #include <string.h> */
  112606. /*
  112607. ** Implementation of the SQL scalar function for accessing the underlying
  112608. ** hash table. This function may be called as follows:
  112609. **
  112610. ** SELECT <function-name>(<key-name>);
  112611. ** SELECT <function-name>(<key-name>, <pointer>);
  112612. **
  112613. ** where <function-name> is the name passed as the second argument
  112614. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  112615. **
  112616. ** If the <pointer> argument is specified, it must be a blob value
  112617. ** containing a pointer to be stored as the hash data corresponding
  112618. ** to the string <key-name>. If <pointer> is not specified, then
  112619. ** the string <key-name> must already exist in the has table. Otherwise,
  112620. ** an error is returned.
  112621. **
  112622. ** Whether or not the <pointer> argument is specified, the value returned
  112623. ** is a blob containing the pointer stored as the hash data corresponding
  112624. ** to string <key-name> (after the hash-table is updated, if applicable).
  112625. */
  112626. static void scalarFunc(
  112627. sqlite3_context *context,
  112628. int argc,
  112629. sqlite3_value **argv
  112630. ){
  112631. Fts3Hash *pHash;
  112632. void *pPtr = 0;
  112633. const unsigned char *zName;
  112634. int nName;
  112635. assert( argc==1 || argc==2 );
  112636. pHash = (Fts3Hash *)sqlite3_user_data(context);
  112637. zName = sqlite3_value_text(argv[0]);
  112638. nName = sqlite3_value_bytes(argv[0])+1;
  112639. if( argc==2 ){
  112640. void *pOld;
  112641. int n = sqlite3_value_bytes(argv[1]);
  112642. if( n!=sizeof(pPtr) ){
  112643. sqlite3_result_error(context, "argument type mismatch", -1);
  112644. return;
  112645. }
  112646. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  112647. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  112648. if( pOld==pPtr ){
  112649. sqlite3_result_error(context, "out of memory", -1);
  112650. return;
  112651. }
  112652. }else{
  112653. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  112654. if( !pPtr ){
  112655. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  112656. sqlite3_result_error(context, zErr, -1);
  112657. sqlite3_free(zErr);
  112658. return;
  112659. }
  112660. }
  112661. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  112662. }
  112663. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  112664. static const char isFtsIdChar[] = {
  112665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  112666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  112667. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  112668. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  112669. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  112670. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  112671. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  112672. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  112673. };
  112674. return (c&0x80 || isFtsIdChar[(int)(c)]);
  112675. }
  112676. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  112677. const char *z1;
  112678. const char *z2 = 0;
  112679. /* Find the start of the next token. */
  112680. z1 = zStr;
  112681. while( z2==0 ){
  112682. char c = *z1;
  112683. switch( c ){
  112684. case '\0': return 0; /* No more tokens here */
  112685. case '\'':
  112686. case '"':
  112687. case '`': {
  112688. z2 = z1;
  112689. while( *++z2 && (*z2!=c || *++z2==c) );
  112690. break;
  112691. }
  112692. case '[':
  112693. z2 = &z1[1];
  112694. while( *z2 && z2[0]!=']' ) z2++;
  112695. if( *z2 ) z2++;
  112696. break;
  112697. default:
  112698. if( sqlite3Fts3IsIdChar(*z1) ){
  112699. z2 = &z1[1];
  112700. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  112701. }else{
  112702. z1++;
  112703. }
  112704. }
  112705. }
  112706. *pn = (int)(z2-z1);
  112707. return z1;
  112708. }
  112709. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  112710. Fts3Hash *pHash, /* Tokenizer hash table */
  112711. const char *zArg, /* Tokenizer name */
  112712. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  112713. char **pzErr /* OUT: Set to malloced error message */
  112714. ){
  112715. int rc;
  112716. char *z = (char *)zArg;
  112717. int n = 0;
  112718. char *zCopy;
  112719. char *zEnd; /* Pointer to nul-term of zCopy */
  112720. sqlite3_tokenizer_module *m;
  112721. zCopy = sqlite3_mprintf("%s", zArg);
  112722. if( !zCopy ) return SQLITE_NOMEM;
  112723. zEnd = &zCopy[strlen(zCopy)];
  112724. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  112725. z[n] = '\0';
  112726. sqlite3Fts3Dequote(z);
  112727. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  112728. if( !m ){
  112729. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  112730. rc = SQLITE_ERROR;
  112731. }else{
  112732. char const **aArg = 0;
  112733. int iArg = 0;
  112734. z = &z[n+1];
  112735. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  112736. int nNew = sizeof(char *)*(iArg+1);
  112737. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  112738. if( !aNew ){
  112739. sqlite3_free(zCopy);
  112740. sqlite3_free((void *)aArg);
  112741. return SQLITE_NOMEM;
  112742. }
  112743. aArg = aNew;
  112744. aArg[iArg++] = z;
  112745. z[n] = '\0';
  112746. sqlite3Fts3Dequote(z);
  112747. z = &z[n+1];
  112748. }
  112749. rc = m->xCreate(iArg, aArg, ppTok);
  112750. assert( rc!=SQLITE_OK || *ppTok );
  112751. if( rc!=SQLITE_OK ){
  112752. *pzErr = sqlite3_mprintf("unknown tokenizer");
  112753. }else{
  112754. (*ppTok)->pModule = m;
  112755. }
  112756. sqlite3_free((void *)aArg);
  112757. }
  112758. sqlite3_free(zCopy);
  112759. return rc;
  112760. }
  112761. #ifdef SQLITE_TEST
  112762. #include <tcl.h>
  112763. /* #include <string.h> */
  112764. /*
  112765. ** Implementation of a special SQL scalar function for testing tokenizers
  112766. ** designed to be used in concert with the Tcl testing framework. This
  112767. ** function must be called with two or more arguments:
  112768. **
  112769. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  112770. **
  112771. ** where <function-name> is the name passed as the second argument
  112772. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  112773. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  112774. **
  112775. ** The return value is a string that may be interpreted as a Tcl
  112776. ** list. For each token in the <input-string>, three elements are
  112777. ** added to the returned list. The first is the token position, the
  112778. ** second is the token text (folded, stemmed, etc.) and the third is the
  112779. ** substring of <input-string> associated with the token. For example,
  112780. ** using the built-in "simple" tokenizer:
  112781. **
  112782. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  112783. **
  112784. ** will return the string:
  112785. **
  112786. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  112787. **
  112788. */
  112789. static void testFunc(
  112790. sqlite3_context *context,
  112791. int argc,
  112792. sqlite3_value **argv
  112793. ){
  112794. Fts3Hash *pHash;
  112795. sqlite3_tokenizer_module *p;
  112796. sqlite3_tokenizer *pTokenizer = 0;
  112797. sqlite3_tokenizer_cursor *pCsr = 0;
  112798. const char *zErr = 0;
  112799. const char *zName;
  112800. int nName;
  112801. const char *zInput;
  112802. int nInput;
  112803. const char *azArg[64];
  112804. const char *zToken;
  112805. int nToken = 0;
  112806. int iStart = 0;
  112807. int iEnd = 0;
  112808. int iPos = 0;
  112809. int i;
  112810. Tcl_Obj *pRet;
  112811. if( argc<2 ){
  112812. sqlite3_result_error(context, "insufficient arguments", -1);
  112813. return;
  112814. }
  112815. nName = sqlite3_value_bytes(argv[0]);
  112816. zName = (const char *)sqlite3_value_text(argv[0]);
  112817. nInput = sqlite3_value_bytes(argv[argc-1]);
  112818. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  112819. pHash = (Fts3Hash *)sqlite3_user_data(context);
  112820. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  112821. if( !p ){
  112822. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  112823. sqlite3_result_error(context, zErr, -1);
  112824. sqlite3_free(zErr);
  112825. return;
  112826. }
  112827. pRet = Tcl_NewObj();
  112828. Tcl_IncrRefCount(pRet);
  112829. for(i=1; i<argc-1; i++){
  112830. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  112831. }
  112832. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  112833. zErr = "error in xCreate()";
  112834. goto finish;
  112835. }
  112836. pTokenizer->pModule = p;
  112837. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  112838. zErr = "error in xOpen()";
  112839. goto finish;
  112840. }
  112841. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  112842. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  112843. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  112844. zToken = &zInput[iStart];
  112845. nToken = iEnd-iStart;
  112846. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  112847. }
  112848. if( SQLITE_OK!=p->xClose(pCsr) ){
  112849. zErr = "error in xClose()";
  112850. goto finish;
  112851. }
  112852. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  112853. zErr = "error in xDestroy()";
  112854. goto finish;
  112855. }
  112856. finish:
  112857. if( zErr ){
  112858. sqlite3_result_error(context, zErr, -1);
  112859. }else{
  112860. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  112861. }
  112862. Tcl_DecrRefCount(pRet);
  112863. }
  112864. static
  112865. int registerTokenizer(
  112866. sqlite3 *db,
  112867. char *zName,
  112868. const sqlite3_tokenizer_module *p
  112869. ){
  112870. int rc;
  112871. sqlite3_stmt *pStmt;
  112872. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  112873. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  112874. if( rc!=SQLITE_OK ){
  112875. return rc;
  112876. }
  112877. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  112878. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  112879. sqlite3_step(pStmt);
  112880. return sqlite3_finalize(pStmt);
  112881. }
  112882. static
  112883. int queryTokenizer(
  112884. sqlite3 *db,
  112885. char *zName,
  112886. const sqlite3_tokenizer_module **pp
  112887. ){
  112888. int rc;
  112889. sqlite3_stmt *pStmt;
  112890. const char zSql[] = "SELECT fts3_tokenizer(?)";
  112891. *pp = 0;
  112892. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  112893. if( rc!=SQLITE_OK ){
  112894. return rc;
  112895. }
  112896. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  112897. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  112898. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  112899. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  112900. }
  112901. }
  112902. return sqlite3_finalize(pStmt);
  112903. }
  112904. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  112905. /*
  112906. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  112907. ** This function is used for testing only, it is not included in the
  112908. ** build unless SQLITE_TEST is defined.
  112909. **
  112910. ** The purpose of this is to test that the fts3_tokenizer() function
  112911. ** can be used as designed by the C-code in the queryTokenizer and
  112912. ** registerTokenizer() functions above. These two functions are repeated
  112913. ** in the README.tokenizer file as an example, so it is important to
  112914. ** test them.
  112915. **
  112916. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  112917. ** function with no arguments. An assert() will fail if a problem is
  112918. ** detected. i.e.:
  112919. **
  112920. ** SELECT fts3_tokenizer_internal_test();
  112921. **
  112922. */
  112923. static void intTestFunc(
  112924. sqlite3_context *context,
  112925. int argc,
  112926. sqlite3_value **argv
  112927. ){
  112928. int rc;
  112929. const sqlite3_tokenizer_module *p1;
  112930. const sqlite3_tokenizer_module *p2;
  112931. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  112932. UNUSED_PARAMETER(argc);
  112933. UNUSED_PARAMETER(argv);
  112934. /* Test the query function */
  112935. sqlite3Fts3SimpleTokenizerModule(&p1);
  112936. rc = queryTokenizer(db, "simple", &p2);
  112937. assert( rc==SQLITE_OK );
  112938. assert( p1==p2 );
  112939. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  112940. assert( rc==SQLITE_ERROR );
  112941. assert( p2==0 );
  112942. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  112943. /* Test the storage function */
  112944. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  112945. assert( rc==SQLITE_OK );
  112946. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  112947. assert( rc==SQLITE_OK );
  112948. assert( p2==p1 );
  112949. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  112950. }
  112951. #endif
  112952. /*
  112953. ** Set up SQL objects in database db used to access the contents of
  112954. ** the hash table pointed to by argument pHash. The hash table must
  112955. ** been initialized to use string keys, and to take a private copy
  112956. ** of the key when a value is inserted. i.e. by a call similar to:
  112957. **
  112958. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  112959. **
  112960. ** This function adds a scalar function (see header comment above
  112961. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  112962. ** defined at compilation time, a temporary virtual table (see header
  112963. ** comment above struct HashTableVtab) to the database schema. Both
  112964. ** provide read/write access to the contents of *pHash.
  112965. **
  112966. ** The third argument to this function, zName, is used as the name
  112967. ** of both the scalar and, if created, the virtual table.
  112968. */
  112969. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  112970. sqlite3 *db,
  112971. Fts3Hash *pHash,
  112972. const char *zName
  112973. ){
  112974. int rc = SQLITE_OK;
  112975. void *p = (void *)pHash;
  112976. const int any = SQLITE_ANY;
  112977. #ifdef SQLITE_TEST
  112978. char *zTest = 0;
  112979. char *zTest2 = 0;
  112980. void *pdb = (void *)db;
  112981. zTest = sqlite3_mprintf("%s_test", zName);
  112982. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  112983. if( !zTest || !zTest2 ){
  112984. rc = SQLITE_NOMEM;
  112985. }
  112986. #endif
  112987. if( SQLITE_OK==rc ){
  112988. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  112989. }
  112990. if( SQLITE_OK==rc ){
  112991. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  112992. }
  112993. #ifdef SQLITE_TEST
  112994. if( SQLITE_OK==rc ){
  112995. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  112996. }
  112997. if( SQLITE_OK==rc ){
  112998. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  112999. }
  113000. #endif
  113001. #ifdef SQLITE_TEST
  113002. sqlite3_free(zTest);
  113003. sqlite3_free(zTest2);
  113004. #endif
  113005. return rc;
  113006. }
  113007. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113008. /************** End of fts3_tokenizer.c **************************************/
  113009. /************** Begin file fts3_tokenizer1.c *********************************/
  113010. /*
  113011. ** 2006 Oct 10
  113012. **
  113013. ** The author disclaims copyright to this source code. In place of
  113014. ** a legal notice, here is a blessing:
  113015. **
  113016. ** May you do good and not evil.
  113017. ** May you find forgiveness for yourself and forgive others.
  113018. ** May you share freely, never taking more than you give.
  113019. **
  113020. ******************************************************************************
  113021. **
  113022. ** Implementation of the "simple" full-text-search tokenizer.
  113023. */
  113024. /*
  113025. ** The code in this file is only compiled if:
  113026. **
  113027. ** * The FTS3 module is being built as an extension
  113028. ** (in which case SQLITE_CORE is not defined), or
  113029. **
  113030. ** * The FTS3 module is being built into the core of
  113031. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  113032. */
  113033. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113034. /* #include <assert.h> */
  113035. /* #include <stdlib.h> */
  113036. /* #include <stdio.h> */
  113037. /* #include <string.h> */
  113038. typedef struct simple_tokenizer {
  113039. sqlite3_tokenizer base;
  113040. char delim[128]; /* flag ASCII delimiters */
  113041. } simple_tokenizer;
  113042. typedef struct simple_tokenizer_cursor {
  113043. sqlite3_tokenizer_cursor base;
  113044. const char *pInput; /* input we are tokenizing */
  113045. int nBytes; /* size of the input */
  113046. int iOffset; /* current position in pInput */
  113047. int iToken; /* index of next token to be returned */
  113048. char *pToken; /* storage for current token */
  113049. int nTokenAllocated; /* space allocated to zToken buffer */
  113050. } simple_tokenizer_cursor;
  113051. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  113052. return c<0x80 && t->delim[c];
  113053. }
  113054. static int fts3_isalnum(int x){
  113055. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  113056. }
  113057. /*
  113058. ** Create a new tokenizer instance.
  113059. */
  113060. static int simpleCreate(
  113061. int argc, const char * const *argv,
  113062. sqlite3_tokenizer **ppTokenizer
  113063. ){
  113064. simple_tokenizer *t;
  113065. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  113066. if( t==NULL ) return SQLITE_NOMEM;
  113067. memset(t, 0, sizeof(*t));
  113068. /* TODO(shess) Delimiters need to remain the same from run to run,
  113069. ** else we need to reindex. One solution would be a meta-table to
  113070. ** track such information in the database, then we'd only want this
  113071. ** information on the initial create.
  113072. */
  113073. if( argc>1 ){
  113074. int i, n = (int)strlen(argv[1]);
  113075. for(i=0; i<n; i++){
  113076. unsigned char ch = argv[1][i];
  113077. /* We explicitly don't support UTF-8 delimiters for now. */
  113078. if( ch>=0x80 ){
  113079. sqlite3_free(t);
  113080. return SQLITE_ERROR;
  113081. }
  113082. t->delim[ch] = 1;
  113083. }
  113084. } else {
  113085. /* Mark non-alphanumeric ASCII characters as delimiters */
  113086. int i;
  113087. for(i=1; i<0x80; i++){
  113088. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  113089. }
  113090. }
  113091. *ppTokenizer = &t->base;
  113092. return SQLITE_OK;
  113093. }
  113094. /*
  113095. ** Destroy a tokenizer
  113096. */
  113097. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  113098. sqlite3_free(pTokenizer);
  113099. return SQLITE_OK;
  113100. }
  113101. /*
  113102. ** Prepare to begin tokenizing a particular string. The input
  113103. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  113104. ** used to incrementally tokenize this string is returned in
  113105. ** *ppCursor.
  113106. */
  113107. static int simpleOpen(
  113108. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  113109. const char *pInput, int nBytes, /* String to be tokenized */
  113110. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  113111. ){
  113112. simple_tokenizer_cursor *c;
  113113. UNUSED_PARAMETER(pTokenizer);
  113114. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  113115. if( c==NULL ) return SQLITE_NOMEM;
  113116. c->pInput = pInput;
  113117. if( pInput==0 ){
  113118. c->nBytes = 0;
  113119. }else if( nBytes<0 ){
  113120. c->nBytes = (int)strlen(pInput);
  113121. }else{
  113122. c->nBytes = nBytes;
  113123. }
  113124. c->iOffset = 0; /* start tokenizing at the beginning */
  113125. c->iToken = 0;
  113126. c->pToken = NULL; /* no space allocated, yet. */
  113127. c->nTokenAllocated = 0;
  113128. *ppCursor = &c->base;
  113129. return SQLITE_OK;
  113130. }
  113131. /*
  113132. ** Close a tokenization cursor previously opened by a call to
  113133. ** simpleOpen() above.
  113134. */
  113135. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  113136. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  113137. sqlite3_free(c->pToken);
  113138. sqlite3_free(c);
  113139. return SQLITE_OK;
  113140. }
  113141. /*
  113142. ** Extract the next token from a tokenization cursor. The cursor must
  113143. ** have been opened by a prior call to simpleOpen().
  113144. */
  113145. static int simpleNext(
  113146. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  113147. const char **ppToken, /* OUT: *ppToken is the token text */
  113148. int *pnBytes, /* OUT: Number of bytes in token */
  113149. int *piStartOffset, /* OUT: Starting offset of token */
  113150. int *piEndOffset, /* OUT: Ending offset of token */
  113151. int *piPosition /* OUT: Position integer of token */
  113152. ){
  113153. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  113154. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  113155. unsigned char *p = (unsigned char *)c->pInput;
  113156. while( c->iOffset<c->nBytes ){
  113157. int iStartOffset;
  113158. /* Scan past delimiter characters */
  113159. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  113160. c->iOffset++;
  113161. }
  113162. /* Count non-delimiter characters. */
  113163. iStartOffset = c->iOffset;
  113164. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  113165. c->iOffset++;
  113166. }
  113167. if( c->iOffset>iStartOffset ){
  113168. int i, n = c->iOffset-iStartOffset;
  113169. if( n>c->nTokenAllocated ){
  113170. char *pNew;
  113171. c->nTokenAllocated = n+20;
  113172. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  113173. if( !pNew ) return SQLITE_NOMEM;
  113174. c->pToken = pNew;
  113175. }
  113176. for(i=0; i<n; i++){
  113177. /* TODO(shess) This needs expansion to handle UTF-8
  113178. ** case-insensitivity.
  113179. */
  113180. unsigned char ch = p[iStartOffset+i];
  113181. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  113182. }
  113183. *ppToken = c->pToken;
  113184. *pnBytes = n;
  113185. *piStartOffset = iStartOffset;
  113186. *piEndOffset = c->iOffset;
  113187. *piPosition = c->iToken++;
  113188. return SQLITE_OK;
  113189. }
  113190. }
  113191. return SQLITE_DONE;
  113192. }
  113193. /*
  113194. ** The set of routines that implement the simple tokenizer
  113195. */
  113196. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  113197. 0,
  113198. simpleCreate,
  113199. simpleDestroy,
  113200. simpleOpen,
  113201. simpleClose,
  113202. simpleNext,
  113203. 0,
  113204. };
  113205. /*
  113206. ** Allocate a new simple tokenizer. Return a pointer to the new
  113207. ** tokenizer in *ppModule
  113208. */
  113209. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  113210. sqlite3_tokenizer_module const**ppModule
  113211. ){
  113212. *ppModule = &simpleTokenizerModule;
  113213. }
  113214. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113215. /************** End of fts3_tokenizer1.c *************************************/
  113216. /************** Begin file fts3_tokenize_vtab.c ******************************/
  113217. /*
  113218. ** 2013 Apr 22
  113219. **
  113220. ** The author disclaims copyright to this source code. In place of
  113221. ** a legal notice, here is a blessing:
  113222. **
  113223. ** May you do good and not evil.
  113224. ** May you find forgiveness for yourself and forgive others.
  113225. ** May you share freely, never taking more than you give.
  113226. **
  113227. ******************************************************************************
  113228. **
  113229. ** This file contains code for the "fts3tokenize" virtual table module.
  113230. ** An fts3tokenize virtual table is created as follows:
  113231. **
  113232. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  113233. ** <tokenizer-name>, <arg-1>, ...
  113234. ** );
  113235. **
  113236. ** The table created has the following schema:
  113237. **
  113238. ** CREATE TABLE <tbl>(input, token, start, end, position)
  113239. **
  113240. ** When queried, the query must include a WHERE clause of type:
  113241. **
  113242. ** input = <string>
  113243. **
  113244. ** The virtual table module tokenizes this <string>, using the FTS3
  113245. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  113246. ** statement and returns one row for each token in the result. With
  113247. ** fields set as follows:
  113248. **
  113249. ** input: Always set to a copy of <string>
  113250. ** token: A token from the input.
  113251. ** start: Byte offset of the token within the input <string>.
  113252. ** end: Byte offset of the byte immediately following the end of the
  113253. ** token within the input string.
  113254. ** pos: Token offset of token within input.
  113255. **
  113256. */
  113257. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113258. /* #include <string.h> */
  113259. /* #include <assert.h> */
  113260. typedef struct Fts3tokTable Fts3tokTable;
  113261. typedef struct Fts3tokCursor Fts3tokCursor;
  113262. /*
  113263. ** Virtual table structure.
  113264. */
  113265. struct Fts3tokTable {
  113266. sqlite3_vtab base; /* Base class used by SQLite core */
  113267. const sqlite3_tokenizer_module *pMod;
  113268. sqlite3_tokenizer *pTok;
  113269. };
  113270. /*
  113271. ** Virtual table cursor structure.
  113272. */
  113273. struct Fts3tokCursor {
  113274. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  113275. char *zInput; /* Input string */
  113276. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  113277. int iRowid; /* Current 'rowid' value */
  113278. const char *zToken; /* Current 'token' value */
  113279. int nToken; /* Size of zToken in bytes */
  113280. int iStart; /* Current 'start' value */
  113281. int iEnd; /* Current 'end' value */
  113282. int iPos; /* Current 'pos' value */
  113283. };
  113284. /*
  113285. ** Query FTS for the tokenizer implementation named zName.
  113286. */
  113287. static int fts3tokQueryTokenizer(
  113288. Fts3Hash *pHash,
  113289. const char *zName,
  113290. const sqlite3_tokenizer_module **pp,
  113291. char **pzErr
  113292. ){
  113293. sqlite3_tokenizer_module *p;
  113294. int nName = (int)strlen(zName);
  113295. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  113296. if( !p ){
  113297. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  113298. return SQLITE_ERROR;
  113299. }
  113300. *pp = p;
  113301. return SQLITE_OK;
  113302. }
  113303. /*
  113304. ** The second argument, argv[], is an array of pointers to nul-terminated
  113305. ** strings. This function makes a copy of the array and strings into a
  113306. ** single block of memory. It then dequotes any of the strings that appear
  113307. ** to be quoted.
  113308. **
  113309. ** If successful, output parameter *pazDequote is set to point at the
  113310. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  113311. ** responsible for eventually calling sqlite3_free() to free the array
  113312. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  113313. ** The final value of *pazDequote is undefined in this case.
  113314. */
  113315. static int fts3tokDequoteArray(
  113316. int argc, /* Number of elements in argv[] */
  113317. const char * const *argv, /* Input array */
  113318. char ***pazDequote /* Output array */
  113319. ){
  113320. int rc = SQLITE_OK; /* Return code */
  113321. if( argc==0 ){
  113322. *pazDequote = 0;
  113323. }else{
  113324. int i;
  113325. int nByte = 0;
  113326. char **azDequote;
  113327. for(i=0; i<argc; i++){
  113328. nByte += (int)(strlen(argv[i]) + 1);
  113329. }
  113330. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  113331. if( azDequote==0 ){
  113332. rc = SQLITE_NOMEM;
  113333. }else{
  113334. char *pSpace = (char *)&azDequote[argc];
  113335. for(i=0; i<argc; i++){
  113336. int n = (int)strlen(argv[i]);
  113337. azDequote[i] = pSpace;
  113338. memcpy(pSpace, argv[i], n+1);
  113339. sqlite3Fts3Dequote(pSpace);
  113340. pSpace += (n+1);
  113341. }
  113342. }
  113343. }
  113344. return rc;
  113345. }
  113346. /*
  113347. ** Schema of the tokenizer table.
  113348. */
  113349. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  113350. /*
  113351. ** This function does all the work for both the xConnect and xCreate methods.
  113352. ** These tables have no persistent representation of their own, so xConnect
  113353. ** and xCreate are identical operations.
  113354. **
  113355. ** argv[0]: module name
  113356. ** argv[1]: database name
  113357. ** argv[2]: table name
  113358. ** argv[3]: first argument (tokenizer name)
  113359. */
  113360. static int fts3tokConnectMethod(
  113361. sqlite3 *db, /* Database connection */
  113362. void *pHash, /* Hash table of tokenizers */
  113363. int argc, /* Number of elements in argv array */
  113364. const char * const *argv, /* xCreate/xConnect argument array */
  113365. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  113366. char **pzErr /* OUT: sqlite3_malloc'd error message */
  113367. ){
  113368. Fts3tokTable *pTab;
  113369. const sqlite3_tokenizer_module *pMod = 0;
  113370. sqlite3_tokenizer *pTok = 0;
  113371. int rc;
  113372. char **azDequote = 0;
  113373. int nDequote;
  113374. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  113375. if( rc!=SQLITE_OK ) return rc;
  113376. nDequote = argc-3;
  113377. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  113378. if( rc==SQLITE_OK ){
  113379. const char *zModule;
  113380. if( nDequote<1 ){
  113381. zModule = "simple";
  113382. }else{
  113383. zModule = azDequote[0];
  113384. }
  113385. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  113386. }
  113387. assert( (rc==SQLITE_OK)==(pMod!=0) );
  113388. if( rc==SQLITE_OK ){
  113389. const char * const *azArg = (const char * const *)&azDequote[1];
  113390. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  113391. }
  113392. if( rc==SQLITE_OK ){
  113393. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  113394. if( pTab==0 ){
  113395. rc = SQLITE_NOMEM;
  113396. }
  113397. }
  113398. if( rc==SQLITE_OK ){
  113399. memset(pTab, 0, sizeof(Fts3tokTable));
  113400. pTab->pMod = pMod;
  113401. pTab->pTok = pTok;
  113402. *ppVtab = &pTab->base;
  113403. }else{
  113404. if( pTok ){
  113405. pMod->xDestroy(pTok);
  113406. }
  113407. }
  113408. sqlite3_free(azDequote);
  113409. return rc;
  113410. }
  113411. /*
  113412. ** This function does the work for both the xDisconnect and xDestroy methods.
  113413. ** These tables have no persistent representation of their own, so xDisconnect
  113414. ** and xDestroy are identical operations.
  113415. */
  113416. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  113417. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  113418. pTab->pMod->xDestroy(pTab->pTok);
  113419. sqlite3_free(pTab);
  113420. return SQLITE_OK;
  113421. }
  113422. /*
  113423. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  113424. */
  113425. static int fts3tokBestIndexMethod(
  113426. sqlite3_vtab *pVTab,
  113427. sqlite3_index_info *pInfo
  113428. ){
  113429. int i;
  113430. UNUSED_PARAMETER(pVTab);
  113431. for(i=0; i<pInfo->nConstraint; i++){
  113432. if( pInfo->aConstraint[i].usable
  113433. && pInfo->aConstraint[i].iColumn==0
  113434. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  113435. ){
  113436. pInfo->idxNum = 1;
  113437. pInfo->aConstraintUsage[i].argvIndex = 1;
  113438. pInfo->aConstraintUsage[i].omit = 1;
  113439. pInfo->estimatedCost = 1;
  113440. return SQLITE_OK;
  113441. }
  113442. }
  113443. pInfo->idxNum = 0;
  113444. assert( pInfo->estimatedCost>1000000.0 );
  113445. return SQLITE_OK;
  113446. }
  113447. /*
  113448. ** xOpen - Open a cursor.
  113449. */
  113450. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  113451. Fts3tokCursor *pCsr;
  113452. UNUSED_PARAMETER(pVTab);
  113453. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  113454. if( pCsr==0 ){
  113455. return SQLITE_NOMEM;
  113456. }
  113457. memset(pCsr, 0, sizeof(Fts3tokCursor));
  113458. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  113459. return SQLITE_OK;
  113460. }
  113461. /*
  113462. ** Reset the tokenizer cursor passed as the only argument. As if it had
  113463. ** just been returned by fts3tokOpenMethod().
  113464. */
  113465. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  113466. if( pCsr->pCsr ){
  113467. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  113468. pTab->pMod->xClose(pCsr->pCsr);
  113469. pCsr->pCsr = 0;
  113470. }
  113471. sqlite3_free(pCsr->zInput);
  113472. pCsr->zInput = 0;
  113473. pCsr->zToken = 0;
  113474. pCsr->nToken = 0;
  113475. pCsr->iStart = 0;
  113476. pCsr->iEnd = 0;
  113477. pCsr->iPos = 0;
  113478. pCsr->iRowid = 0;
  113479. }
  113480. /*
  113481. ** xClose - Close a cursor.
  113482. */
  113483. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  113484. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113485. fts3tokResetCursor(pCsr);
  113486. sqlite3_free(pCsr);
  113487. return SQLITE_OK;
  113488. }
  113489. /*
  113490. ** xNext - Advance the cursor to the next row, if any.
  113491. */
  113492. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  113493. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113494. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  113495. int rc; /* Return code */
  113496. pCsr->iRowid++;
  113497. rc = pTab->pMod->xNext(pCsr->pCsr,
  113498. &pCsr->zToken, &pCsr->nToken,
  113499. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  113500. );
  113501. if( rc!=SQLITE_OK ){
  113502. fts3tokResetCursor(pCsr);
  113503. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  113504. }
  113505. return rc;
  113506. }
  113507. /*
  113508. ** xFilter - Initialize a cursor to point at the start of its data.
  113509. */
  113510. static int fts3tokFilterMethod(
  113511. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  113512. int idxNum, /* Strategy index */
  113513. const char *idxStr, /* Unused */
  113514. int nVal, /* Number of elements in apVal */
  113515. sqlite3_value **apVal /* Arguments for the indexing scheme */
  113516. ){
  113517. int rc = SQLITE_ERROR;
  113518. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113519. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  113520. UNUSED_PARAMETER(idxStr);
  113521. UNUSED_PARAMETER(nVal);
  113522. fts3tokResetCursor(pCsr);
  113523. if( idxNum==1 ){
  113524. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  113525. int nByte = sqlite3_value_bytes(apVal[0]);
  113526. pCsr->zInput = sqlite3_malloc(nByte+1);
  113527. if( pCsr->zInput==0 ){
  113528. rc = SQLITE_NOMEM;
  113529. }else{
  113530. memcpy(pCsr->zInput, zByte, nByte);
  113531. pCsr->zInput[nByte] = 0;
  113532. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  113533. if( rc==SQLITE_OK ){
  113534. pCsr->pCsr->pTokenizer = pTab->pTok;
  113535. }
  113536. }
  113537. }
  113538. if( rc!=SQLITE_OK ) return rc;
  113539. return fts3tokNextMethod(pCursor);
  113540. }
  113541. /*
  113542. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  113543. */
  113544. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  113545. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113546. return (pCsr->zToken==0);
  113547. }
  113548. /*
  113549. ** xColumn - Return a column value.
  113550. */
  113551. static int fts3tokColumnMethod(
  113552. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  113553. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  113554. int iCol /* Index of column to read value from */
  113555. ){
  113556. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113557. /* CREATE TABLE x(input, token, start, end, position) */
  113558. switch( iCol ){
  113559. case 0:
  113560. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  113561. break;
  113562. case 1:
  113563. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  113564. break;
  113565. case 2:
  113566. sqlite3_result_int(pCtx, pCsr->iStart);
  113567. break;
  113568. case 3:
  113569. sqlite3_result_int(pCtx, pCsr->iEnd);
  113570. break;
  113571. default:
  113572. assert( iCol==4 );
  113573. sqlite3_result_int(pCtx, pCsr->iPos);
  113574. break;
  113575. }
  113576. return SQLITE_OK;
  113577. }
  113578. /*
  113579. ** xRowid - Return the current rowid for the cursor.
  113580. */
  113581. static int fts3tokRowidMethod(
  113582. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  113583. sqlite_int64 *pRowid /* OUT: Rowid value */
  113584. ){
  113585. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113586. *pRowid = (sqlite3_int64)pCsr->iRowid;
  113587. return SQLITE_OK;
  113588. }
  113589. /*
  113590. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  113591. ** if successful or an error code if sqlite3_create_module() fails.
  113592. */
  113593. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  113594. static const sqlite3_module fts3tok_module = {
  113595. 0, /* iVersion */
  113596. fts3tokConnectMethod, /* xCreate */
  113597. fts3tokConnectMethod, /* xConnect */
  113598. fts3tokBestIndexMethod, /* xBestIndex */
  113599. fts3tokDisconnectMethod, /* xDisconnect */
  113600. fts3tokDisconnectMethod, /* xDestroy */
  113601. fts3tokOpenMethod, /* xOpen */
  113602. fts3tokCloseMethod, /* xClose */
  113603. fts3tokFilterMethod, /* xFilter */
  113604. fts3tokNextMethod, /* xNext */
  113605. fts3tokEofMethod, /* xEof */
  113606. fts3tokColumnMethod, /* xColumn */
  113607. fts3tokRowidMethod, /* xRowid */
  113608. 0, /* xUpdate */
  113609. 0, /* xBegin */
  113610. 0, /* xSync */
  113611. 0, /* xCommit */
  113612. 0, /* xRollback */
  113613. 0, /* xFindFunction */
  113614. 0, /* xRename */
  113615. 0, /* xSavepoint */
  113616. 0, /* xRelease */
  113617. 0 /* xRollbackTo */
  113618. };
  113619. int rc; /* Return code */
  113620. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  113621. return rc;
  113622. }
  113623. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113624. /************** End of fts3_tokenize_vtab.c **********************************/
  113625. /************** Begin file fts3_write.c **************************************/
  113626. /*
  113627. ** 2009 Oct 23
  113628. **
  113629. ** The author disclaims copyright to this source code. In place of
  113630. ** a legal notice, here is a blessing:
  113631. **
  113632. ** May you do good and not evil.
  113633. ** May you find forgiveness for yourself and forgive others.
  113634. ** May you share freely, never taking more than you give.
  113635. **
  113636. ******************************************************************************
  113637. **
  113638. ** This file is part of the SQLite FTS3 extension module. Specifically,
  113639. ** this file contains code to insert, update and delete rows from FTS3
  113640. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  113641. ** of the sub-routines used to merge segments are also used by the query
  113642. ** code in fts3.c.
  113643. */
  113644. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113645. /* #include <string.h> */
  113646. /* #include <assert.h> */
  113647. /* #include <stdlib.h> */
  113648. #define FTS_MAX_APPENDABLE_HEIGHT 16
  113649. /*
  113650. ** When full-text index nodes are loaded from disk, the buffer that they
  113651. ** are loaded into has the following number of bytes of padding at the end
  113652. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  113653. ** of 920 bytes is allocated for it.
  113654. **
  113655. ** This means that if we have a pointer into a buffer containing node data,
  113656. ** it is always safe to read up to two varints from it without risking an
  113657. ** overread, even if the node data is corrupted.
  113658. */
  113659. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  113660. /*
  113661. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  113662. ** memory incrementally instead of all at once. This can be a big performance
  113663. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  113664. ** method before retrieving all query results (as may happen, for example,
  113665. ** if a query has a LIMIT clause).
  113666. **
  113667. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  113668. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  113669. ** The code is written so that the hard lower-limit for each of these values
  113670. ** is 1. Clearly such small values would be inefficient, but can be useful
  113671. ** for testing purposes.
  113672. **
  113673. ** If this module is built with SQLITE_TEST defined, these constants may
  113674. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  113675. ** a Tcl interface to read and write the values.
  113676. */
  113677. #ifdef SQLITE_TEST
  113678. int test_fts3_node_chunksize = (4*1024);
  113679. int test_fts3_node_chunk_threshold = (4*1024)*4;
  113680. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  113681. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  113682. #else
  113683. # define FTS3_NODE_CHUNKSIZE (4*1024)
  113684. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  113685. #endif
  113686. /*
  113687. ** The two values that may be meaningfully bound to the :1 parameter in
  113688. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  113689. */
  113690. #define FTS_STAT_DOCTOTAL 0
  113691. #define FTS_STAT_INCRMERGEHINT 1
  113692. #define FTS_STAT_AUTOINCRMERGE 2
  113693. /*
  113694. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  113695. ** and incremental merge operation that takes place. This is used for
  113696. ** debugging FTS only, it should not usually be turned on in production
  113697. ** systems.
  113698. */
  113699. #ifdef FTS3_LOG_MERGES
  113700. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  113701. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  113702. }
  113703. #else
  113704. #define fts3LogMerge(x, y)
  113705. #endif
  113706. typedef struct PendingList PendingList;
  113707. typedef struct SegmentNode SegmentNode;
  113708. typedef struct SegmentWriter SegmentWriter;
  113709. /*
  113710. ** An instance of the following data structure is used to build doclists
  113711. ** incrementally. See function fts3PendingListAppend() for details.
  113712. */
  113713. struct PendingList {
  113714. int nData;
  113715. char *aData;
  113716. int nSpace;
  113717. sqlite3_int64 iLastDocid;
  113718. sqlite3_int64 iLastCol;
  113719. sqlite3_int64 iLastPos;
  113720. };
  113721. /*
  113722. ** Each cursor has a (possibly empty) linked list of the following objects.
  113723. */
  113724. struct Fts3DeferredToken {
  113725. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  113726. int iCol; /* Column token must occur in */
  113727. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  113728. PendingList *pList; /* Doclist is assembled here */
  113729. };
  113730. /*
  113731. ** An instance of this structure is used to iterate through the terms on
  113732. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  113733. ** this structure are only manipulated by code in this file, opaque handles
  113734. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  113735. ** terms when querying the full-text index. See functions:
  113736. **
  113737. ** sqlite3Fts3SegReaderNew()
  113738. ** sqlite3Fts3SegReaderFree()
  113739. ** sqlite3Fts3SegReaderIterate()
  113740. **
  113741. ** Methods used to manipulate Fts3SegReader structures:
  113742. **
  113743. ** fts3SegReaderNext()
  113744. ** fts3SegReaderFirstDocid()
  113745. ** fts3SegReaderNextDocid()
  113746. */
  113747. struct Fts3SegReader {
  113748. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  113749. u8 bLookup; /* True for a lookup only */
  113750. u8 rootOnly; /* True for a root-only reader */
  113751. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  113752. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  113753. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  113754. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  113755. char *aNode; /* Pointer to node data (or NULL) */
  113756. int nNode; /* Size of buffer at aNode (or 0) */
  113757. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  113758. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  113759. Fts3HashElem **ppNextElem;
  113760. /* Variables set by fts3SegReaderNext(). These may be read directly
  113761. ** by the caller. They are valid from the time SegmentReaderNew() returns
  113762. ** until SegmentReaderNext() returns something other than SQLITE_OK
  113763. ** (i.e. SQLITE_DONE).
  113764. */
  113765. int nTerm; /* Number of bytes in current term */
  113766. char *zTerm; /* Pointer to current term */
  113767. int nTermAlloc; /* Allocated size of zTerm buffer */
  113768. char *aDoclist; /* Pointer to doclist of current entry */
  113769. int nDoclist; /* Size of doclist in current entry */
  113770. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  113771. ** through the current doclist (aDoclist/nDoclist).
  113772. */
  113773. char *pOffsetList;
  113774. int nOffsetList; /* For descending pending seg-readers only */
  113775. sqlite3_int64 iDocid;
  113776. };
  113777. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  113778. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  113779. /*
  113780. ** An instance of this structure is used to create a segment b-tree in the
  113781. ** database. The internal details of this type are only accessed by the
  113782. ** following functions:
  113783. **
  113784. ** fts3SegWriterAdd()
  113785. ** fts3SegWriterFlush()
  113786. ** fts3SegWriterFree()
  113787. */
  113788. struct SegmentWriter {
  113789. SegmentNode *pTree; /* Pointer to interior tree structure */
  113790. sqlite3_int64 iFirst; /* First slot in %_segments written */
  113791. sqlite3_int64 iFree; /* Next free slot in %_segments */
  113792. char *zTerm; /* Pointer to previous term buffer */
  113793. int nTerm; /* Number of bytes in zTerm */
  113794. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  113795. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  113796. int nSize; /* Size of allocation at aData */
  113797. int nData; /* Bytes of data in aData */
  113798. char *aData; /* Pointer to block from malloc() */
  113799. };
  113800. /*
  113801. ** Type SegmentNode is used by the following three functions to create
  113802. ** the interior part of the segment b+-tree structures (everything except
  113803. ** the leaf nodes). These functions and type are only ever used by code
  113804. ** within the fts3SegWriterXXX() family of functions described above.
  113805. **
  113806. ** fts3NodeAddTerm()
  113807. ** fts3NodeWrite()
  113808. ** fts3NodeFree()
  113809. **
  113810. ** When a b+tree is written to the database (either as a result of a merge
  113811. ** or the pending-terms table being flushed), leaves are written into the
  113812. ** database file as soon as they are completely populated. The interior of
  113813. ** the tree is assembled in memory and written out only once all leaves have
  113814. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  113815. ** very large, meaning that the interior of the tree consumes relatively
  113816. ** little memory.
  113817. */
  113818. struct SegmentNode {
  113819. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  113820. SegmentNode *pRight; /* Pointer to right-sibling */
  113821. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  113822. int nEntry; /* Number of terms written to node so far */
  113823. char *zTerm; /* Pointer to previous term buffer */
  113824. int nTerm; /* Number of bytes in zTerm */
  113825. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  113826. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  113827. int nData; /* Bytes of valid data so far */
  113828. char *aData; /* Node data */
  113829. };
  113830. /*
  113831. ** Valid values for the second argument to fts3SqlStmt().
  113832. */
  113833. #define SQL_DELETE_CONTENT 0
  113834. #define SQL_IS_EMPTY 1
  113835. #define SQL_DELETE_ALL_CONTENT 2
  113836. #define SQL_DELETE_ALL_SEGMENTS 3
  113837. #define SQL_DELETE_ALL_SEGDIR 4
  113838. #define SQL_DELETE_ALL_DOCSIZE 5
  113839. #define SQL_DELETE_ALL_STAT 6
  113840. #define SQL_SELECT_CONTENT_BY_ROWID 7
  113841. #define SQL_NEXT_SEGMENT_INDEX 8
  113842. #define SQL_INSERT_SEGMENTS 9
  113843. #define SQL_NEXT_SEGMENTS_ID 10
  113844. #define SQL_INSERT_SEGDIR 11
  113845. #define SQL_SELECT_LEVEL 12
  113846. #define SQL_SELECT_LEVEL_RANGE 13
  113847. #define SQL_SELECT_LEVEL_COUNT 14
  113848. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  113849. #define SQL_DELETE_SEGDIR_LEVEL 16
  113850. #define SQL_DELETE_SEGMENTS_RANGE 17
  113851. #define SQL_CONTENT_INSERT 18
  113852. #define SQL_DELETE_DOCSIZE 19
  113853. #define SQL_REPLACE_DOCSIZE 20
  113854. #define SQL_SELECT_DOCSIZE 21
  113855. #define SQL_SELECT_STAT 22
  113856. #define SQL_REPLACE_STAT 23
  113857. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  113858. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  113859. #define SQL_DELETE_SEGDIR_RANGE 26
  113860. #define SQL_SELECT_ALL_LANGID 27
  113861. #define SQL_FIND_MERGE_LEVEL 28
  113862. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  113863. #define SQL_DELETE_SEGDIR_ENTRY 30
  113864. #define SQL_SHIFT_SEGDIR_ENTRY 31
  113865. #define SQL_SELECT_SEGDIR 32
  113866. #define SQL_CHOMP_SEGDIR 33
  113867. #define SQL_SEGMENT_IS_APPENDABLE 34
  113868. #define SQL_SELECT_INDEXES 35
  113869. #define SQL_SELECT_MXLEVEL 36
  113870. /*
  113871. ** This function is used to obtain an SQLite prepared statement handle
  113872. ** for the statement identified by the second argument. If successful,
  113873. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  113874. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  113875. **
  113876. ** If argument apVal is not NULL, then it must point to an array with
  113877. ** at least as many entries as the requested statement has bound
  113878. ** parameters. The values are bound to the statements parameters before
  113879. ** returning.
  113880. */
  113881. static int fts3SqlStmt(
  113882. Fts3Table *p, /* Virtual table handle */
  113883. int eStmt, /* One of the SQL_XXX constants above */
  113884. sqlite3_stmt **pp, /* OUT: Statement handle */
  113885. sqlite3_value **apVal /* Values to bind to statement */
  113886. ){
  113887. const char *azSql[] = {
  113888. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  113889. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  113890. /* 2 */ "DELETE FROM %Q.'%q_content'",
  113891. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  113892. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  113893. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  113894. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  113895. /* 7 */ "SELECT %s WHERE rowid=?",
  113896. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  113897. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  113898. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  113899. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  113900. /* Return segments in order from oldest to newest.*/
  113901. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113902. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  113903. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113904. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  113905. "ORDER BY level DESC, idx ASC",
  113906. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  113907. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  113908. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  113909. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  113910. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  113911. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  113912. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  113913. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  113914. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  113915. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  113916. /* 24 */ "",
  113917. /* 25 */ "",
  113918. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  113919. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  113920. /* This statement is used to determine which level to read the input from
  113921. ** when performing an incremental merge. It returns the absolute level number
  113922. ** of the oldest level in the db that contains at least ? segments. Or,
  113923. ** if no level in the FTS index contains more than ? segments, the statement
  113924. ** returns zero rows. */
  113925. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  113926. " ORDER BY (level %% 1024) ASC LIMIT 1",
  113927. /* Estimate the upper limit on the number of leaf nodes in a new segment
  113928. ** created by merging the oldest :2 segments from absolute level :1. See
  113929. ** function sqlite3Fts3Incrmerge() for details. */
  113930. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  113931. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  113932. /* SQL_DELETE_SEGDIR_ENTRY
  113933. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  113934. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  113935. /* SQL_SHIFT_SEGDIR_ENTRY
  113936. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  113937. ** to :1. */
  113938. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  113939. /* SQL_SELECT_SEGDIR
  113940. ** Read a single entry from the %_segdir table. The entry from absolute
  113941. ** level :1 with index value :2. */
  113942. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113943. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  113944. /* SQL_CHOMP_SEGDIR
  113945. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  113946. ** entry located on absolute level :3 with index :4. */
  113947. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  113948. "WHERE level = ? AND idx = ?",
  113949. /* SQL_SEGMENT_IS_APPENDABLE
  113950. ** Return a single row if the segment with end_block=? is appendable. Or
  113951. ** no rows otherwise. */
  113952. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  113953. /* SQL_SELECT_INDEXES
  113954. ** Return the list of valid segment indexes for absolute level ? */
  113955. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  113956. /* SQL_SELECT_MXLEVEL
  113957. ** Return the largest relative level in the FTS index or indexes. */
  113958. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  113959. };
  113960. int rc = SQLITE_OK;
  113961. sqlite3_stmt *pStmt;
  113962. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  113963. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  113964. pStmt = p->aStmt[eStmt];
  113965. if( !pStmt ){
  113966. char *zSql;
  113967. if( eStmt==SQL_CONTENT_INSERT ){
  113968. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  113969. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  113970. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  113971. }else{
  113972. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  113973. }
  113974. if( !zSql ){
  113975. rc = SQLITE_NOMEM;
  113976. }else{
  113977. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  113978. sqlite3_free(zSql);
  113979. assert( rc==SQLITE_OK || pStmt==0 );
  113980. p->aStmt[eStmt] = pStmt;
  113981. }
  113982. }
  113983. if( apVal ){
  113984. int i;
  113985. int nParam = sqlite3_bind_parameter_count(pStmt);
  113986. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  113987. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  113988. }
  113989. }
  113990. *pp = pStmt;
  113991. return rc;
  113992. }
  113993. static int fts3SelectDocsize(
  113994. Fts3Table *pTab, /* FTS3 table handle */
  113995. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  113996. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  113997. ){
  113998. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  113999. int rc; /* Return code */
  114000. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  114001. if( rc==SQLITE_OK ){
  114002. sqlite3_bind_int64(pStmt, 1, iDocid);
  114003. rc = sqlite3_step(pStmt);
  114004. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  114005. rc = sqlite3_reset(pStmt);
  114006. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  114007. pStmt = 0;
  114008. }else{
  114009. rc = SQLITE_OK;
  114010. }
  114011. }
  114012. *ppStmt = pStmt;
  114013. return rc;
  114014. }
  114015. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  114016. Fts3Table *pTab, /* Fts3 table handle */
  114017. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  114018. ){
  114019. sqlite3_stmt *pStmt = 0;
  114020. int rc;
  114021. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  114022. if( rc==SQLITE_OK ){
  114023. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  114024. if( sqlite3_step(pStmt)!=SQLITE_ROW
  114025. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  114026. ){
  114027. rc = sqlite3_reset(pStmt);
  114028. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  114029. pStmt = 0;
  114030. }
  114031. }
  114032. *ppStmt = pStmt;
  114033. return rc;
  114034. }
  114035. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  114036. Fts3Table *pTab, /* Fts3 table handle */
  114037. sqlite3_int64 iDocid, /* Docid to read size data for */
  114038. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  114039. ){
  114040. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  114041. }
  114042. /*
  114043. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  114044. ** array apVal[] to the SQL statement identified by eStmt, the statement
  114045. ** is executed.
  114046. **
  114047. ** Returns SQLITE_OK if the statement is successfully executed, or an
  114048. ** SQLite error code otherwise.
  114049. */
  114050. static void fts3SqlExec(
  114051. int *pRC, /* Result code */
  114052. Fts3Table *p, /* The FTS3 table */
  114053. int eStmt, /* Index of statement to evaluate */
  114054. sqlite3_value **apVal /* Parameters to bind */
  114055. ){
  114056. sqlite3_stmt *pStmt;
  114057. int rc;
  114058. if( *pRC ) return;
  114059. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  114060. if( rc==SQLITE_OK ){
  114061. sqlite3_step(pStmt);
  114062. rc = sqlite3_reset(pStmt);
  114063. }
  114064. *pRC = rc;
  114065. }
  114066. /*
  114067. ** This function ensures that the caller has obtained an exclusive
  114068. ** shared-cache table-lock on the %_segdir table. This is required before
  114069. ** writing data to the fts3 table. If this lock is not acquired first, then
  114070. ** the caller may end up attempting to take this lock as part of committing
  114071. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  114072. ** LOCKED_SHAREDCACHEto a COMMIT command.
  114073. **
  114074. ** It is best to avoid this because if FTS3 returns any error when
  114075. ** committing a transaction, the whole transaction will be rolled back.
  114076. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  114077. ** It can still happen if the user locks the underlying tables directly
  114078. ** instead of accessing them via FTS.
  114079. */
  114080. static int fts3Writelock(Fts3Table *p){
  114081. int rc = SQLITE_OK;
  114082. if( p->nPendingData==0 ){
  114083. sqlite3_stmt *pStmt;
  114084. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  114085. if( rc==SQLITE_OK ){
  114086. sqlite3_bind_null(pStmt, 1);
  114087. sqlite3_step(pStmt);
  114088. rc = sqlite3_reset(pStmt);
  114089. }
  114090. }
  114091. return rc;
  114092. }
  114093. /*
  114094. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  114095. ** Within each language id, a separate index is maintained to store the
  114096. ** document terms, and each configured prefix size (configured the FTS
  114097. ** "prefix=" option). And each index consists of multiple levels ("relative
  114098. ** levels").
  114099. **
  114100. ** All three of these values (the language id, the specific index and the
  114101. ** level within the index) are encoded in 64-bit integer values stored
  114102. ** in the %_segdir table on disk. This function is used to convert three
  114103. ** separate component values into the single 64-bit integer value that
  114104. ** can be used to query the %_segdir table.
  114105. **
  114106. ** Specifically, each language-id/index combination is allocated 1024
  114107. ** 64-bit integer level values ("absolute levels"). The main terms index
  114108. ** for language-id 0 is allocate values 0-1023. The first prefix index
  114109. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  114110. ** Language 1 indexes are allocated immediately following language 0.
  114111. **
  114112. ** So, for a system with nPrefix prefix indexes configured, the block of
  114113. ** absolute levels that corresponds to language-id iLangid and index
  114114. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  114115. */
  114116. static sqlite3_int64 getAbsoluteLevel(
  114117. Fts3Table *p, /* FTS3 table handle */
  114118. int iLangid, /* Language id */
  114119. int iIndex, /* Index in p->aIndex[] */
  114120. int iLevel /* Level of segments */
  114121. ){
  114122. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  114123. assert( iLangid>=0 );
  114124. assert( p->nIndex>0 );
  114125. assert( iIndex>=0 && iIndex<p->nIndex );
  114126. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  114127. return iBase + iLevel;
  114128. }
  114129. /*
  114130. ** Set *ppStmt to a statement handle that may be used to iterate through
  114131. ** all rows in the %_segdir table, from oldest to newest. If successful,
  114132. ** return SQLITE_OK. If an error occurs while preparing the statement,
  114133. ** return an SQLite error code.
  114134. **
  114135. ** There is only ever one instance of this SQL statement compiled for
  114136. ** each FTS3 table.
  114137. **
  114138. ** The statement returns the following columns from the %_segdir table:
  114139. **
  114140. ** 0: idx
  114141. ** 1: start_block
  114142. ** 2: leaves_end_block
  114143. ** 3: end_block
  114144. ** 4: root
  114145. */
  114146. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  114147. Fts3Table *p, /* FTS3 table */
  114148. int iLangid, /* Language being queried */
  114149. int iIndex, /* Index for p->aIndex[] */
  114150. int iLevel, /* Level to select (relative level) */
  114151. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  114152. ){
  114153. int rc;
  114154. sqlite3_stmt *pStmt = 0;
  114155. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  114156. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  114157. assert( iIndex>=0 && iIndex<p->nIndex );
  114158. if( iLevel<0 ){
  114159. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  114160. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  114161. if( rc==SQLITE_OK ){
  114162. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  114163. sqlite3_bind_int64(pStmt, 2,
  114164. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  114165. );
  114166. }
  114167. }else{
  114168. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  114169. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  114170. if( rc==SQLITE_OK ){
  114171. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  114172. }
  114173. }
  114174. *ppStmt = pStmt;
  114175. return rc;
  114176. }
  114177. /*
  114178. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  114179. ** if successful, or an SQLite error code otherwise.
  114180. **
  114181. ** This function also serves to allocate the PendingList structure itself.
  114182. ** For example, to create a new PendingList structure containing two
  114183. ** varints:
  114184. **
  114185. ** PendingList *p = 0;
  114186. ** fts3PendingListAppendVarint(&p, 1);
  114187. ** fts3PendingListAppendVarint(&p, 2);
  114188. */
  114189. static int fts3PendingListAppendVarint(
  114190. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  114191. sqlite3_int64 i /* Value to append to data */
  114192. ){
  114193. PendingList *p = *pp;
  114194. /* Allocate or grow the PendingList as required. */
  114195. if( !p ){
  114196. p = sqlite3_malloc(sizeof(*p) + 100);
  114197. if( !p ){
  114198. return SQLITE_NOMEM;
  114199. }
  114200. p->nSpace = 100;
  114201. p->aData = (char *)&p[1];
  114202. p->nData = 0;
  114203. }
  114204. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  114205. int nNew = p->nSpace * 2;
  114206. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  114207. if( !p ){
  114208. sqlite3_free(*pp);
  114209. *pp = 0;
  114210. return SQLITE_NOMEM;
  114211. }
  114212. p->nSpace = nNew;
  114213. p->aData = (char *)&p[1];
  114214. }
  114215. /* Append the new serialized varint to the end of the list. */
  114216. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  114217. p->aData[p->nData] = '\0';
  114218. *pp = p;
  114219. return SQLITE_OK;
  114220. }
  114221. /*
  114222. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  114223. ** is returned if the structure is sqlite3_realloced as part of adding
  114224. ** the entry. Otherwise, zero.
  114225. **
  114226. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  114227. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  114228. ** it is set to SQLITE_OK.
  114229. */
  114230. static int fts3PendingListAppend(
  114231. PendingList **pp, /* IN/OUT: PendingList structure */
  114232. sqlite3_int64 iDocid, /* Docid for entry to add */
  114233. sqlite3_int64 iCol, /* Column for entry to add */
  114234. sqlite3_int64 iPos, /* Position of term for entry to add */
  114235. int *pRc /* OUT: Return code */
  114236. ){
  114237. PendingList *p = *pp;
  114238. int rc = SQLITE_OK;
  114239. assert( !p || p->iLastDocid<=iDocid );
  114240. if( !p || p->iLastDocid!=iDocid ){
  114241. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  114242. if( p ){
  114243. assert( p->nData<p->nSpace );
  114244. assert( p->aData[p->nData]==0 );
  114245. p->nData++;
  114246. }
  114247. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  114248. goto pendinglistappend_out;
  114249. }
  114250. p->iLastCol = -1;
  114251. p->iLastPos = 0;
  114252. p->iLastDocid = iDocid;
  114253. }
  114254. if( iCol>0 && p->iLastCol!=iCol ){
  114255. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  114256. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  114257. ){
  114258. goto pendinglistappend_out;
  114259. }
  114260. p->iLastCol = iCol;
  114261. p->iLastPos = 0;
  114262. }
  114263. if( iCol>=0 ){
  114264. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  114265. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  114266. if( rc==SQLITE_OK ){
  114267. p->iLastPos = iPos;
  114268. }
  114269. }
  114270. pendinglistappend_out:
  114271. *pRc = rc;
  114272. if( p!=*pp ){
  114273. *pp = p;
  114274. return 1;
  114275. }
  114276. return 0;
  114277. }
  114278. /*
  114279. ** Free a PendingList object allocated by fts3PendingListAppend().
  114280. */
  114281. static void fts3PendingListDelete(PendingList *pList){
  114282. sqlite3_free(pList);
  114283. }
  114284. /*
  114285. ** Add an entry to one of the pending-terms hash tables.
  114286. */
  114287. static int fts3PendingTermsAddOne(
  114288. Fts3Table *p,
  114289. int iCol,
  114290. int iPos,
  114291. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  114292. const char *zToken,
  114293. int nToken
  114294. ){
  114295. PendingList *pList;
  114296. int rc = SQLITE_OK;
  114297. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  114298. if( pList ){
  114299. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  114300. }
  114301. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  114302. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  114303. /* Malloc failed while inserting the new entry. This can only
  114304. ** happen if there was no previous entry for this token.
  114305. */
  114306. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  114307. sqlite3_free(pList);
  114308. rc = SQLITE_NOMEM;
  114309. }
  114310. }
  114311. if( rc==SQLITE_OK ){
  114312. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  114313. }
  114314. return rc;
  114315. }
  114316. /*
  114317. ** Tokenize the nul-terminated string zText and add all tokens to the
  114318. ** pending-terms hash-table. The docid used is that currently stored in
  114319. ** p->iPrevDocid, and the column is specified by argument iCol.
  114320. **
  114321. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  114322. */
  114323. static int fts3PendingTermsAdd(
  114324. Fts3Table *p, /* Table into which text will be inserted */
  114325. int iLangid, /* Language id to use */
  114326. const char *zText, /* Text of document to be inserted */
  114327. int iCol, /* Column into which text is being inserted */
  114328. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  114329. ){
  114330. int rc;
  114331. int iStart = 0;
  114332. int iEnd = 0;
  114333. int iPos = 0;
  114334. int nWord = 0;
  114335. char const *zToken;
  114336. int nToken = 0;
  114337. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  114338. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  114339. sqlite3_tokenizer_cursor *pCsr;
  114340. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  114341. const char**,int*,int*,int*,int*);
  114342. assert( pTokenizer && pModule );
  114343. /* If the user has inserted a NULL value, this function may be called with
  114344. ** zText==0. In this case, add zero token entries to the hash table and
  114345. ** return early. */
  114346. if( zText==0 ){
  114347. *pnWord = 0;
  114348. return SQLITE_OK;
  114349. }
  114350. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  114351. if( rc!=SQLITE_OK ){
  114352. return rc;
  114353. }
  114354. xNext = pModule->xNext;
  114355. while( SQLITE_OK==rc
  114356. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  114357. ){
  114358. int i;
  114359. if( iPos>=nWord ) nWord = iPos+1;
  114360. /* Positions cannot be negative; we use -1 as a terminator internally.
  114361. ** Tokens must have a non-zero length.
  114362. */
  114363. if( iPos<0 || !zToken || nToken<=0 ){
  114364. rc = SQLITE_ERROR;
  114365. break;
  114366. }
  114367. /* Add the term to the terms index */
  114368. rc = fts3PendingTermsAddOne(
  114369. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  114370. );
  114371. /* Add the term to each of the prefix indexes that it is not too
  114372. ** short for. */
  114373. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  114374. struct Fts3Index *pIndex = &p->aIndex[i];
  114375. if( nToken<pIndex->nPrefix ) continue;
  114376. rc = fts3PendingTermsAddOne(
  114377. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  114378. );
  114379. }
  114380. }
  114381. pModule->xClose(pCsr);
  114382. *pnWord += nWord;
  114383. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  114384. }
  114385. /*
  114386. ** Calling this function indicates that subsequent calls to
  114387. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  114388. ** contents of the document with docid iDocid.
  114389. */
  114390. static int fts3PendingTermsDocid(
  114391. Fts3Table *p, /* Full-text table handle */
  114392. int iLangid, /* Language id of row being written */
  114393. sqlite_int64 iDocid /* Docid of row being written */
  114394. ){
  114395. assert( iLangid>=0 );
  114396. /* TODO(shess) Explore whether partially flushing the buffer on
  114397. ** forced-flush would provide better performance. I suspect that if
  114398. ** we ordered the doclists by size and flushed the largest until the
  114399. ** buffer was half empty, that would let the less frequent terms
  114400. ** generate longer doclists.
  114401. */
  114402. if( iDocid<=p->iPrevDocid
  114403. || p->iPrevLangid!=iLangid
  114404. || p->nPendingData>p->nMaxPendingData
  114405. ){
  114406. int rc = sqlite3Fts3PendingTermsFlush(p);
  114407. if( rc!=SQLITE_OK ) return rc;
  114408. }
  114409. p->iPrevDocid = iDocid;
  114410. p->iPrevLangid = iLangid;
  114411. return SQLITE_OK;
  114412. }
  114413. /*
  114414. ** Discard the contents of the pending-terms hash tables.
  114415. */
  114416. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  114417. int i;
  114418. for(i=0; i<p->nIndex; i++){
  114419. Fts3HashElem *pElem;
  114420. Fts3Hash *pHash = &p->aIndex[i].hPending;
  114421. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  114422. PendingList *pList = (PendingList *)fts3HashData(pElem);
  114423. fts3PendingListDelete(pList);
  114424. }
  114425. fts3HashClear(pHash);
  114426. }
  114427. p->nPendingData = 0;
  114428. }
  114429. /*
  114430. ** This function is called by the xUpdate() method as part of an INSERT
  114431. ** operation. It adds entries for each term in the new record to the
  114432. ** pendingTerms hash table.
  114433. **
  114434. ** Argument apVal is the same as the similarly named argument passed to
  114435. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  114436. */
  114437. static int fts3InsertTerms(
  114438. Fts3Table *p,
  114439. int iLangid,
  114440. sqlite3_value **apVal,
  114441. u32 *aSz
  114442. ){
  114443. int i; /* Iterator variable */
  114444. for(i=2; i<p->nColumn+2; i++){
  114445. int iCol = i-2;
  114446. if( p->abNotindexed[iCol]==0 ){
  114447. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  114448. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  114449. if( rc!=SQLITE_OK ){
  114450. return rc;
  114451. }
  114452. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  114453. }
  114454. }
  114455. return SQLITE_OK;
  114456. }
  114457. /*
  114458. ** This function is called by the xUpdate() method for an INSERT operation.
  114459. ** The apVal parameter is passed a copy of the apVal argument passed by
  114460. ** SQLite to the xUpdate() method. i.e:
  114461. **
  114462. ** apVal[0] Not used for INSERT.
  114463. ** apVal[1] rowid
  114464. ** apVal[2] Left-most user-defined column
  114465. ** ...
  114466. ** apVal[p->nColumn+1] Right-most user-defined column
  114467. ** apVal[p->nColumn+2] Hidden column with same name as table
  114468. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  114469. ** apVal[p->nColumn+4] Hidden languageid column
  114470. */
  114471. static int fts3InsertData(
  114472. Fts3Table *p, /* Full-text table */
  114473. sqlite3_value **apVal, /* Array of values to insert */
  114474. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  114475. ){
  114476. int rc; /* Return code */
  114477. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  114478. if( p->zContentTbl ){
  114479. sqlite3_value *pRowid = apVal[p->nColumn+3];
  114480. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  114481. pRowid = apVal[1];
  114482. }
  114483. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  114484. return SQLITE_CONSTRAINT;
  114485. }
  114486. *piDocid = sqlite3_value_int64(pRowid);
  114487. return SQLITE_OK;
  114488. }
  114489. /* Locate the statement handle used to insert data into the %_content
  114490. ** table. The SQL for this statement is:
  114491. **
  114492. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  114493. **
  114494. ** The statement features N '?' variables, where N is the number of user
  114495. ** defined columns in the FTS3 table, plus one for the docid field.
  114496. */
  114497. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  114498. if( rc==SQLITE_OK && p->zLanguageid ){
  114499. rc = sqlite3_bind_int(
  114500. pContentInsert, p->nColumn+2,
  114501. sqlite3_value_int(apVal[p->nColumn+4])
  114502. );
  114503. }
  114504. if( rc!=SQLITE_OK ) return rc;
  114505. /* There is a quirk here. The users INSERT statement may have specified
  114506. ** a value for the "rowid" field, for the "docid" field, or for both.
  114507. ** Which is a problem, since "rowid" and "docid" are aliases for the
  114508. ** same value. For example:
  114509. **
  114510. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  114511. **
  114512. ** In FTS3, this is an error. It is an error to specify non-NULL values
  114513. ** for both docid and some other rowid alias.
  114514. */
  114515. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  114516. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  114517. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  114518. ){
  114519. /* A rowid/docid conflict. */
  114520. return SQLITE_ERROR;
  114521. }
  114522. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  114523. if( rc!=SQLITE_OK ) return rc;
  114524. }
  114525. /* Execute the statement to insert the record. Set *piDocid to the
  114526. ** new docid value.
  114527. */
  114528. sqlite3_step(pContentInsert);
  114529. rc = sqlite3_reset(pContentInsert);
  114530. *piDocid = sqlite3_last_insert_rowid(p->db);
  114531. return rc;
  114532. }
  114533. /*
  114534. ** Remove all data from the FTS3 table. Clear the hash table containing
  114535. ** pending terms.
  114536. */
  114537. static int fts3DeleteAll(Fts3Table *p, int bContent){
  114538. int rc = SQLITE_OK; /* Return code */
  114539. /* Discard the contents of the pending-terms hash table. */
  114540. sqlite3Fts3PendingTermsClear(p);
  114541. /* Delete everything from the shadow tables. Except, leave %_content as
  114542. ** is if bContent is false. */
  114543. assert( p->zContentTbl==0 || bContent==0 );
  114544. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  114545. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  114546. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  114547. if( p->bHasDocsize ){
  114548. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  114549. }
  114550. if( p->bHasStat ){
  114551. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  114552. }
  114553. return rc;
  114554. }
  114555. /*
  114556. **
  114557. */
  114558. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  114559. int iLangid = 0;
  114560. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  114561. return iLangid;
  114562. }
  114563. /*
  114564. ** The first element in the apVal[] array is assumed to contain the docid
  114565. ** (an integer) of a row about to be deleted. Remove all terms from the
  114566. ** full-text index.
  114567. */
  114568. static void fts3DeleteTerms(
  114569. int *pRC, /* Result code */
  114570. Fts3Table *p, /* The FTS table to delete from */
  114571. sqlite3_value *pRowid, /* The docid to be deleted */
  114572. u32 *aSz, /* Sizes of deleted document written here */
  114573. int *pbFound /* OUT: Set to true if row really does exist */
  114574. ){
  114575. int rc;
  114576. sqlite3_stmt *pSelect;
  114577. assert( *pbFound==0 );
  114578. if( *pRC ) return;
  114579. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  114580. if( rc==SQLITE_OK ){
  114581. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  114582. int i;
  114583. int iLangid = langidFromSelect(p, pSelect);
  114584. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  114585. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  114586. int iCol = i-1;
  114587. if( p->abNotindexed[iCol]==0 ){
  114588. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  114589. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  114590. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  114591. }
  114592. }
  114593. if( rc!=SQLITE_OK ){
  114594. sqlite3_reset(pSelect);
  114595. *pRC = rc;
  114596. return;
  114597. }
  114598. *pbFound = 1;
  114599. }
  114600. rc = sqlite3_reset(pSelect);
  114601. }else{
  114602. sqlite3_reset(pSelect);
  114603. }
  114604. *pRC = rc;
  114605. }
  114606. /*
  114607. ** Forward declaration to account for the circular dependency between
  114608. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  114609. */
  114610. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  114611. /*
  114612. ** This function allocates a new level iLevel index in the segdir table.
  114613. ** Usually, indexes are allocated within a level sequentially starting
  114614. ** with 0, so the allocated index is one greater than the value returned
  114615. ** by:
  114616. **
  114617. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  114618. **
  114619. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  114620. ** level, they are merged into a single level (iLevel+1) segment and the
  114621. ** allocated index is 0.
  114622. **
  114623. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  114624. ** returned. Otherwise, an SQLite error code is returned.
  114625. */
  114626. static int fts3AllocateSegdirIdx(
  114627. Fts3Table *p,
  114628. int iLangid, /* Language id */
  114629. int iIndex, /* Index for p->aIndex */
  114630. int iLevel,
  114631. int *piIdx
  114632. ){
  114633. int rc; /* Return Code */
  114634. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  114635. int iNext = 0; /* Result of query pNextIdx */
  114636. assert( iLangid>=0 );
  114637. assert( p->nIndex>=1 );
  114638. /* Set variable iNext to the next available segdir index at level iLevel. */
  114639. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  114640. if( rc==SQLITE_OK ){
  114641. sqlite3_bind_int64(
  114642. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  114643. );
  114644. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  114645. iNext = sqlite3_column_int(pNextIdx, 0);
  114646. }
  114647. rc = sqlite3_reset(pNextIdx);
  114648. }
  114649. if( rc==SQLITE_OK ){
  114650. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  114651. ** full, merge all segments in level iLevel into a single iLevel+1
  114652. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  114653. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  114654. */
  114655. if( iNext>=FTS3_MERGE_COUNT ){
  114656. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  114657. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  114658. *piIdx = 0;
  114659. }else{
  114660. *piIdx = iNext;
  114661. }
  114662. }
  114663. return rc;
  114664. }
  114665. /*
  114666. ** The %_segments table is declared as follows:
  114667. **
  114668. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  114669. **
  114670. ** This function reads data from a single row of the %_segments table. The
  114671. ** specific row is identified by the iBlockid parameter. If paBlob is not
  114672. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  114673. ** with the contents of the blob stored in the "block" column of the
  114674. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  114675. ** to the size of the blob in bytes before returning.
  114676. **
  114677. ** If an error occurs, or the table does not contain the specified row,
  114678. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  114679. ** paBlob is non-NULL, then it is the responsibility of the caller to
  114680. ** eventually free the returned buffer.
  114681. **
  114682. ** This function may leave an open sqlite3_blob* handle in the
  114683. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  114684. ** to this function. The handle may be closed by calling the
  114685. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  114686. ** performance improvement, but the blob handle should always be closed
  114687. ** before control is returned to the user (to prevent a lock being held
  114688. ** on the database file for longer than necessary). Thus, any virtual table
  114689. ** method (xFilter etc.) that may directly or indirectly call this function
  114690. ** must call sqlite3Fts3SegmentsClose() before returning.
  114691. */
  114692. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  114693. Fts3Table *p, /* FTS3 table handle */
  114694. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  114695. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  114696. int *pnBlob, /* OUT: Size of blob data */
  114697. int *pnLoad /* OUT: Bytes actually loaded */
  114698. ){
  114699. int rc; /* Return code */
  114700. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  114701. assert( pnBlob );
  114702. if( p->pSegments ){
  114703. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  114704. }else{
  114705. if( 0==p->zSegmentsTbl ){
  114706. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  114707. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  114708. }
  114709. rc = sqlite3_blob_open(
  114710. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  114711. );
  114712. }
  114713. if( rc==SQLITE_OK ){
  114714. int nByte = sqlite3_blob_bytes(p->pSegments);
  114715. *pnBlob = nByte;
  114716. if( paBlob ){
  114717. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  114718. if( !aByte ){
  114719. rc = SQLITE_NOMEM;
  114720. }else{
  114721. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  114722. nByte = FTS3_NODE_CHUNKSIZE;
  114723. *pnLoad = nByte;
  114724. }
  114725. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  114726. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  114727. if( rc!=SQLITE_OK ){
  114728. sqlite3_free(aByte);
  114729. aByte = 0;
  114730. }
  114731. }
  114732. *paBlob = aByte;
  114733. }
  114734. }
  114735. return rc;
  114736. }
  114737. /*
  114738. ** Close the blob handle at p->pSegments, if it is open. See comments above
  114739. ** the sqlite3Fts3ReadBlock() function for details.
  114740. */
  114741. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  114742. sqlite3_blob_close(p->pSegments);
  114743. p->pSegments = 0;
  114744. }
  114745. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  114746. int nRead; /* Number of bytes to read */
  114747. int rc; /* Return code */
  114748. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  114749. rc = sqlite3_blob_read(
  114750. pReader->pBlob,
  114751. &pReader->aNode[pReader->nPopulate],
  114752. nRead,
  114753. pReader->nPopulate
  114754. );
  114755. if( rc==SQLITE_OK ){
  114756. pReader->nPopulate += nRead;
  114757. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  114758. if( pReader->nPopulate==pReader->nNode ){
  114759. sqlite3_blob_close(pReader->pBlob);
  114760. pReader->pBlob = 0;
  114761. pReader->nPopulate = 0;
  114762. }
  114763. }
  114764. return rc;
  114765. }
  114766. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  114767. int rc = SQLITE_OK;
  114768. assert( !pReader->pBlob
  114769. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  114770. );
  114771. while( pReader->pBlob && rc==SQLITE_OK
  114772. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  114773. ){
  114774. rc = fts3SegReaderIncrRead(pReader);
  114775. }
  114776. return rc;
  114777. }
  114778. /*
  114779. ** Set an Fts3SegReader cursor to point at EOF.
  114780. */
  114781. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  114782. if( !fts3SegReaderIsRootOnly(pSeg) ){
  114783. sqlite3_free(pSeg->aNode);
  114784. sqlite3_blob_close(pSeg->pBlob);
  114785. pSeg->pBlob = 0;
  114786. }
  114787. pSeg->aNode = 0;
  114788. }
  114789. /*
  114790. ** Move the iterator passed as the first argument to the next term in the
  114791. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  114792. ** SQLITE_DONE. Otherwise, an SQLite error code.
  114793. */
  114794. static int fts3SegReaderNext(
  114795. Fts3Table *p,
  114796. Fts3SegReader *pReader,
  114797. int bIncr
  114798. ){
  114799. int rc; /* Return code of various sub-routines */
  114800. char *pNext; /* Cursor variable */
  114801. int nPrefix; /* Number of bytes in term prefix */
  114802. int nSuffix; /* Number of bytes in term suffix */
  114803. if( !pReader->aDoclist ){
  114804. pNext = pReader->aNode;
  114805. }else{
  114806. pNext = &pReader->aDoclist[pReader->nDoclist];
  114807. }
  114808. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  114809. if( fts3SegReaderIsPending(pReader) ){
  114810. Fts3HashElem *pElem = *(pReader->ppNextElem);
  114811. if( pElem==0 ){
  114812. pReader->aNode = 0;
  114813. }else{
  114814. PendingList *pList = (PendingList *)fts3HashData(pElem);
  114815. pReader->zTerm = (char *)fts3HashKey(pElem);
  114816. pReader->nTerm = fts3HashKeysize(pElem);
  114817. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  114818. pReader->aNode = pReader->aDoclist = pList->aData;
  114819. pReader->ppNextElem++;
  114820. assert( pReader->aNode );
  114821. }
  114822. return SQLITE_OK;
  114823. }
  114824. fts3SegReaderSetEof(pReader);
  114825. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  114826. ** blocks have already been traversed. */
  114827. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  114828. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  114829. return SQLITE_OK;
  114830. }
  114831. rc = sqlite3Fts3ReadBlock(
  114832. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  114833. (bIncr ? &pReader->nPopulate : 0)
  114834. );
  114835. if( rc!=SQLITE_OK ) return rc;
  114836. assert( pReader->pBlob==0 );
  114837. if( bIncr && pReader->nPopulate<pReader->nNode ){
  114838. pReader->pBlob = p->pSegments;
  114839. p->pSegments = 0;
  114840. }
  114841. pNext = pReader->aNode;
  114842. }
  114843. assert( !fts3SegReaderIsPending(pReader) );
  114844. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  114845. if( rc!=SQLITE_OK ) return rc;
  114846. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  114847. ** safe (no risk of overread) even if the node data is corrupted. */
  114848. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  114849. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  114850. if( nPrefix<0 || nSuffix<=0
  114851. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  114852. ){
  114853. return FTS_CORRUPT_VTAB;
  114854. }
  114855. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  114856. int nNew = (nPrefix+nSuffix)*2;
  114857. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  114858. if( !zNew ){
  114859. return SQLITE_NOMEM;
  114860. }
  114861. pReader->zTerm = zNew;
  114862. pReader->nTermAlloc = nNew;
  114863. }
  114864. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  114865. if( rc!=SQLITE_OK ) return rc;
  114866. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  114867. pReader->nTerm = nPrefix+nSuffix;
  114868. pNext += nSuffix;
  114869. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  114870. pReader->aDoclist = pNext;
  114871. pReader->pOffsetList = 0;
  114872. /* Check that the doclist does not appear to extend past the end of the
  114873. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  114874. ** of these statements is untrue, then the data structure is corrupt.
  114875. */
  114876. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  114877. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  114878. ){
  114879. return FTS_CORRUPT_VTAB;
  114880. }
  114881. return SQLITE_OK;
  114882. }
  114883. /*
  114884. ** Set the SegReader to point to the first docid in the doclist associated
  114885. ** with the current term.
  114886. */
  114887. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  114888. int rc = SQLITE_OK;
  114889. assert( pReader->aDoclist );
  114890. assert( !pReader->pOffsetList );
  114891. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  114892. u8 bEof = 0;
  114893. pReader->iDocid = 0;
  114894. pReader->nOffsetList = 0;
  114895. sqlite3Fts3DoclistPrev(0,
  114896. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  114897. &pReader->iDocid, &pReader->nOffsetList, &bEof
  114898. );
  114899. }else{
  114900. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  114901. if( rc==SQLITE_OK ){
  114902. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  114903. pReader->pOffsetList = &pReader->aDoclist[n];
  114904. }
  114905. }
  114906. return rc;
  114907. }
  114908. /*
  114909. ** Advance the SegReader to point to the next docid in the doclist
  114910. ** associated with the current term.
  114911. **
  114912. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  114913. ** *ppOffsetList is set to point to the first column-offset list
  114914. ** in the doclist entry (i.e. immediately past the docid varint).
  114915. ** *pnOffsetList is set to the length of the set of column-offset
  114916. ** lists, not including the nul-terminator byte. For example:
  114917. */
  114918. static int fts3SegReaderNextDocid(
  114919. Fts3Table *pTab,
  114920. Fts3SegReader *pReader, /* Reader to advance to next docid */
  114921. char **ppOffsetList, /* OUT: Pointer to current position-list */
  114922. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  114923. ){
  114924. int rc = SQLITE_OK;
  114925. char *p = pReader->pOffsetList;
  114926. char c = 0;
  114927. assert( p );
  114928. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  114929. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  114930. ** Pending-terms doclists are always built up in ascending order, so
  114931. ** we have to iterate through them backwards here. */
  114932. u8 bEof = 0;
  114933. if( ppOffsetList ){
  114934. *ppOffsetList = pReader->pOffsetList;
  114935. *pnOffsetList = pReader->nOffsetList - 1;
  114936. }
  114937. sqlite3Fts3DoclistPrev(0,
  114938. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  114939. &pReader->nOffsetList, &bEof
  114940. );
  114941. if( bEof ){
  114942. pReader->pOffsetList = 0;
  114943. }else{
  114944. pReader->pOffsetList = p;
  114945. }
  114946. }else{
  114947. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  114948. /* Pointer p currently points at the first byte of an offset list. The
  114949. ** following block advances it to point one byte past the end of
  114950. ** the same offset list. */
  114951. while( 1 ){
  114952. /* The following line of code (and the "p++" below the while() loop) is
  114953. ** normally all that is required to move pointer p to the desired
  114954. ** position. The exception is if this node is being loaded from disk
  114955. ** incrementally and pointer "p" now points to the first byte past
  114956. ** the populated part of pReader->aNode[].
  114957. */
  114958. while( *p | c ) c = *p++ & 0x80;
  114959. assert( *p==0 );
  114960. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  114961. rc = fts3SegReaderIncrRead(pReader);
  114962. if( rc!=SQLITE_OK ) return rc;
  114963. }
  114964. p++;
  114965. /* If required, populate the output variables with a pointer to and the
  114966. ** size of the previous offset-list.
  114967. */
  114968. if( ppOffsetList ){
  114969. *ppOffsetList = pReader->pOffsetList;
  114970. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  114971. }
  114972. /* List may have been edited in place by fts3EvalNearTrim() */
  114973. while( p<pEnd && *p==0 ) p++;
  114974. /* If there are no more entries in the doclist, set pOffsetList to
  114975. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  114976. ** Fts3SegReader.pOffsetList to point to the next offset list before
  114977. ** returning.
  114978. */
  114979. if( p>=pEnd ){
  114980. pReader->pOffsetList = 0;
  114981. }else{
  114982. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  114983. if( rc==SQLITE_OK ){
  114984. sqlite3_int64 iDelta;
  114985. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  114986. if( pTab->bDescIdx ){
  114987. pReader->iDocid -= iDelta;
  114988. }else{
  114989. pReader->iDocid += iDelta;
  114990. }
  114991. }
  114992. }
  114993. }
  114994. return SQLITE_OK;
  114995. }
  114996. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  114997. Fts3Cursor *pCsr,
  114998. Fts3MultiSegReader *pMsr,
  114999. int *pnOvfl
  115000. ){
  115001. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  115002. int nOvfl = 0;
  115003. int ii;
  115004. int rc = SQLITE_OK;
  115005. int pgsz = p->nPgsz;
  115006. assert( p->bFts4 );
  115007. assert( pgsz>0 );
  115008. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  115009. Fts3SegReader *pReader = pMsr->apSegment[ii];
  115010. if( !fts3SegReaderIsPending(pReader)
  115011. && !fts3SegReaderIsRootOnly(pReader)
  115012. ){
  115013. sqlite3_int64 jj;
  115014. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  115015. int nBlob;
  115016. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  115017. if( rc!=SQLITE_OK ) break;
  115018. if( (nBlob+35)>pgsz ){
  115019. nOvfl += (nBlob + 34)/pgsz;
  115020. }
  115021. }
  115022. }
  115023. }
  115024. *pnOvfl = nOvfl;
  115025. return rc;
  115026. }
  115027. /*
  115028. ** Free all allocations associated with the iterator passed as the
  115029. ** second argument.
  115030. */
  115031. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  115032. if( pReader && !fts3SegReaderIsPending(pReader) ){
  115033. sqlite3_free(pReader->zTerm);
  115034. if( !fts3SegReaderIsRootOnly(pReader) ){
  115035. sqlite3_free(pReader->aNode);
  115036. sqlite3_blob_close(pReader->pBlob);
  115037. }
  115038. }
  115039. sqlite3_free(pReader);
  115040. }
  115041. /*
  115042. ** Allocate a new SegReader object.
  115043. */
  115044. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  115045. int iAge, /* Segment "age". */
  115046. int bLookup, /* True for a lookup only */
  115047. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  115048. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  115049. sqlite3_int64 iEndBlock, /* Final block of segment */
  115050. const char *zRoot, /* Buffer containing root node */
  115051. int nRoot, /* Size of buffer containing root node */
  115052. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  115053. ){
  115054. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  115055. int nExtra = 0; /* Bytes to allocate segment root node */
  115056. assert( iStartLeaf<=iEndLeaf );
  115057. if( iStartLeaf==0 ){
  115058. nExtra = nRoot + FTS3_NODE_PADDING;
  115059. }
  115060. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  115061. if( !pReader ){
  115062. return SQLITE_NOMEM;
  115063. }
  115064. memset(pReader, 0, sizeof(Fts3SegReader));
  115065. pReader->iIdx = iAge;
  115066. pReader->bLookup = bLookup!=0;
  115067. pReader->iStartBlock = iStartLeaf;
  115068. pReader->iLeafEndBlock = iEndLeaf;
  115069. pReader->iEndBlock = iEndBlock;
  115070. if( nExtra ){
  115071. /* The entire segment is stored in the root node. */
  115072. pReader->aNode = (char *)&pReader[1];
  115073. pReader->rootOnly = 1;
  115074. pReader->nNode = nRoot;
  115075. memcpy(pReader->aNode, zRoot, nRoot);
  115076. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  115077. }else{
  115078. pReader->iCurrentBlock = iStartLeaf-1;
  115079. }
  115080. *ppReader = pReader;
  115081. return SQLITE_OK;
  115082. }
  115083. /*
  115084. ** This is a comparison function used as a qsort() callback when sorting
  115085. ** an array of pending terms by term. This occurs as part of flushing
  115086. ** the contents of the pending-terms hash table to the database.
  115087. */
  115088. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  115089. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  115090. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  115091. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  115092. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  115093. int n = (n1<n2 ? n1 : n2);
  115094. int c = memcmp(z1, z2, n);
  115095. if( c==0 ){
  115096. c = n1 - n2;
  115097. }
  115098. return c;
  115099. }
  115100. /*
  115101. ** This function is used to allocate an Fts3SegReader that iterates through
  115102. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  115103. **
  115104. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  115105. ** through each term in the pending-terms table. Or, if isPrefixIter is
  115106. ** non-zero, it iterates through each term and its prefixes. For example, if
  115107. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  115108. ** "firebird", then the iterator visits the following 'terms' (in the order
  115109. ** shown):
  115110. **
  115111. ** f fi fir fire fireb firebi firebir firebird
  115112. ** m my mys mysq mysql
  115113. ** s sq sql sqli sqlit sqlite
  115114. **
  115115. ** Whereas if isPrefixIter is zero, the terms visited are:
  115116. **
  115117. ** firebird mysql sqlite
  115118. */
  115119. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  115120. Fts3Table *p, /* Virtual table handle */
  115121. int iIndex, /* Index for p->aIndex */
  115122. const char *zTerm, /* Term to search for */
  115123. int nTerm, /* Size of buffer zTerm */
  115124. int bPrefix, /* True for a prefix iterator */
  115125. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  115126. ){
  115127. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  115128. Fts3HashElem *pE; /* Iterator variable */
  115129. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  115130. int nElem = 0; /* Size of array at aElem */
  115131. int rc = SQLITE_OK; /* Return Code */
  115132. Fts3Hash *pHash;
  115133. pHash = &p->aIndex[iIndex].hPending;
  115134. if( bPrefix ){
  115135. int nAlloc = 0; /* Size of allocated array at aElem */
  115136. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  115137. char *zKey = (char *)fts3HashKey(pE);
  115138. int nKey = fts3HashKeysize(pE);
  115139. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  115140. if( nElem==nAlloc ){
  115141. Fts3HashElem **aElem2;
  115142. nAlloc += 16;
  115143. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  115144. aElem, nAlloc*sizeof(Fts3HashElem *)
  115145. );
  115146. if( !aElem2 ){
  115147. rc = SQLITE_NOMEM;
  115148. nElem = 0;
  115149. break;
  115150. }
  115151. aElem = aElem2;
  115152. }
  115153. aElem[nElem++] = pE;
  115154. }
  115155. }
  115156. /* If more than one term matches the prefix, sort the Fts3HashElem
  115157. ** objects in term order using qsort(). This uses the same comparison
  115158. ** callback as is used when flushing terms to disk.
  115159. */
  115160. if( nElem>1 ){
  115161. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  115162. }
  115163. }else{
  115164. /* The query is a simple term lookup that matches at most one term in
  115165. ** the index. All that is required is a straight hash-lookup.
  115166. **
  115167. ** Because the stack address of pE may be accessed via the aElem pointer
  115168. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  115169. ** within this entire function, not just this "else{...}" block.
  115170. */
  115171. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  115172. if( pE ){
  115173. aElem = &pE;
  115174. nElem = 1;
  115175. }
  115176. }
  115177. if( nElem>0 ){
  115178. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  115179. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  115180. if( !pReader ){
  115181. rc = SQLITE_NOMEM;
  115182. }else{
  115183. memset(pReader, 0, nByte);
  115184. pReader->iIdx = 0x7FFFFFFF;
  115185. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  115186. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  115187. }
  115188. }
  115189. if( bPrefix ){
  115190. sqlite3_free(aElem);
  115191. }
  115192. *ppReader = pReader;
  115193. return rc;
  115194. }
  115195. /*
  115196. ** Compare the entries pointed to by two Fts3SegReader structures.
  115197. ** Comparison is as follows:
  115198. **
  115199. ** 1) EOF is greater than not EOF.
  115200. **
  115201. ** 2) The current terms (if any) are compared using memcmp(). If one
  115202. ** term is a prefix of another, the longer term is considered the
  115203. ** larger.
  115204. **
  115205. ** 3) By segment age. An older segment is considered larger.
  115206. */
  115207. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115208. int rc;
  115209. if( pLhs->aNode && pRhs->aNode ){
  115210. int rc2 = pLhs->nTerm - pRhs->nTerm;
  115211. if( rc2<0 ){
  115212. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  115213. }else{
  115214. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  115215. }
  115216. if( rc==0 ){
  115217. rc = rc2;
  115218. }
  115219. }else{
  115220. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  115221. }
  115222. if( rc==0 ){
  115223. rc = pRhs->iIdx - pLhs->iIdx;
  115224. }
  115225. assert( rc!=0 );
  115226. return rc;
  115227. }
  115228. /*
  115229. ** A different comparison function for SegReader structures. In this
  115230. ** version, it is assumed that each SegReader points to an entry in
  115231. ** a doclist for identical terms. Comparison is made as follows:
  115232. **
  115233. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  115234. **
  115235. ** 2) By current docid.
  115236. **
  115237. ** 3) By segment age. An older segment is considered larger.
  115238. */
  115239. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115240. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  115241. if( rc==0 ){
  115242. if( pLhs->iDocid==pRhs->iDocid ){
  115243. rc = pRhs->iIdx - pLhs->iIdx;
  115244. }else{
  115245. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  115246. }
  115247. }
  115248. assert( pLhs->aNode && pRhs->aNode );
  115249. return rc;
  115250. }
  115251. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115252. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  115253. if( rc==0 ){
  115254. if( pLhs->iDocid==pRhs->iDocid ){
  115255. rc = pRhs->iIdx - pLhs->iIdx;
  115256. }else{
  115257. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  115258. }
  115259. }
  115260. assert( pLhs->aNode && pRhs->aNode );
  115261. return rc;
  115262. }
  115263. /*
  115264. ** Compare the term that the Fts3SegReader object passed as the first argument
  115265. ** points to with the term specified by arguments zTerm and nTerm.
  115266. **
  115267. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  115268. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  115269. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  115270. */
  115271. static int fts3SegReaderTermCmp(
  115272. Fts3SegReader *pSeg, /* Segment reader object */
  115273. const char *zTerm, /* Term to compare to */
  115274. int nTerm /* Size of term zTerm in bytes */
  115275. ){
  115276. int res = 0;
  115277. if( pSeg->aNode ){
  115278. if( pSeg->nTerm>nTerm ){
  115279. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  115280. }else{
  115281. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  115282. }
  115283. if( res==0 ){
  115284. res = pSeg->nTerm-nTerm;
  115285. }
  115286. }
  115287. return res;
  115288. }
  115289. /*
  115290. ** Argument apSegment is an array of nSegment elements. It is known that
  115291. ** the final (nSegment-nSuspect) members are already in sorted order
  115292. ** (according to the comparison function provided). This function shuffles
  115293. ** the array around until all entries are in sorted order.
  115294. */
  115295. static void fts3SegReaderSort(
  115296. Fts3SegReader **apSegment, /* Array to sort entries of */
  115297. int nSegment, /* Size of apSegment array */
  115298. int nSuspect, /* Unsorted entry count */
  115299. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  115300. ){
  115301. int i; /* Iterator variable */
  115302. assert( nSuspect<=nSegment );
  115303. if( nSuspect==nSegment ) nSuspect--;
  115304. for(i=nSuspect-1; i>=0; i--){
  115305. int j;
  115306. for(j=i; j<(nSegment-1); j++){
  115307. Fts3SegReader *pTmp;
  115308. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  115309. pTmp = apSegment[j+1];
  115310. apSegment[j+1] = apSegment[j];
  115311. apSegment[j] = pTmp;
  115312. }
  115313. }
  115314. #ifndef NDEBUG
  115315. /* Check that the list really is sorted now. */
  115316. for(i=0; i<(nSuspect-1); i++){
  115317. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  115318. }
  115319. #endif
  115320. }
  115321. /*
  115322. ** Insert a record into the %_segments table.
  115323. */
  115324. static int fts3WriteSegment(
  115325. Fts3Table *p, /* Virtual table handle */
  115326. sqlite3_int64 iBlock, /* Block id for new block */
  115327. char *z, /* Pointer to buffer containing block data */
  115328. int n /* Size of buffer z in bytes */
  115329. ){
  115330. sqlite3_stmt *pStmt;
  115331. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  115332. if( rc==SQLITE_OK ){
  115333. sqlite3_bind_int64(pStmt, 1, iBlock);
  115334. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  115335. sqlite3_step(pStmt);
  115336. rc = sqlite3_reset(pStmt);
  115337. }
  115338. return rc;
  115339. }
  115340. /*
  115341. ** Find the largest relative level number in the table. If successful, set
  115342. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  115343. ** set *pnMax to zero and return an SQLite error code.
  115344. */
  115345. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  115346. int rc;
  115347. int mxLevel = 0;
  115348. sqlite3_stmt *pStmt = 0;
  115349. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  115350. if( rc==SQLITE_OK ){
  115351. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115352. mxLevel = sqlite3_column_int(pStmt, 0);
  115353. }
  115354. rc = sqlite3_reset(pStmt);
  115355. }
  115356. *pnMax = mxLevel;
  115357. return rc;
  115358. }
  115359. /*
  115360. ** Insert a record into the %_segdir table.
  115361. */
  115362. static int fts3WriteSegdir(
  115363. Fts3Table *p, /* Virtual table handle */
  115364. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  115365. int iIdx, /* Value for "idx" field */
  115366. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  115367. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  115368. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  115369. char *zRoot, /* Blob value for "root" field */
  115370. int nRoot /* Number of bytes in buffer zRoot */
  115371. ){
  115372. sqlite3_stmt *pStmt;
  115373. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  115374. if( rc==SQLITE_OK ){
  115375. sqlite3_bind_int64(pStmt, 1, iLevel);
  115376. sqlite3_bind_int(pStmt, 2, iIdx);
  115377. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  115378. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  115379. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  115380. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  115381. sqlite3_step(pStmt);
  115382. rc = sqlite3_reset(pStmt);
  115383. }
  115384. return rc;
  115385. }
  115386. /*
  115387. ** Return the size of the common prefix (if any) shared by zPrev and
  115388. ** zNext, in bytes. For example,
  115389. **
  115390. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  115391. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  115392. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  115393. */
  115394. static int fts3PrefixCompress(
  115395. const char *zPrev, /* Buffer containing previous term */
  115396. int nPrev, /* Size of buffer zPrev in bytes */
  115397. const char *zNext, /* Buffer containing next term */
  115398. int nNext /* Size of buffer zNext in bytes */
  115399. ){
  115400. int n;
  115401. UNUSED_PARAMETER(nNext);
  115402. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  115403. return n;
  115404. }
  115405. /*
  115406. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  115407. ** (according to memcmp) than the previous term.
  115408. */
  115409. static int fts3NodeAddTerm(
  115410. Fts3Table *p, /* Virtual table handle */
  115411. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  115412. int isCopyTerm, /* True if zTerm/nTerm is transient */
  115413. const char *zTerm, /* Pointer to buffer containing term */
  115414. int nTerm /* Size of term in bytes */
  115415. ){
  115416. SegmentNode *pTree = *ppTree;
  115417. int rc;
  115418. SegmentNode *pNew;
  115419. /* First try to append the term to the current node. Return early if
  115420. ** this is possible.
  115421. */
  115422. if( pTree ){
  115423. int nData = pTree->nData; /* Current size of node in bytes */
  115424. int nReq = nData; /* Required space after adding zTerm */
  115425. int nPrefix; /* Number of bytes of prefix compression */
  115426. int nSuffix; /* Suffix length */
  115427. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  115428. nSuffix = nTerm-nPrefix;
  115429. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  115430. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  115431. if( nReq>p->nNodeSize ){
  115432. /* An unusual case: this is the first term to be added to the node
  115433. ** and the static node buffer (p->nNodeSize bytes) is not large
  115434. ** enough. Use a separately malloced buffer instead This wastes
  115435. ** p->nNodeSize bytes, but since this scenario only comes about when
  115436. ** the database contain two terms that share a prefix of almost 2KB,
  115437. ** this is not expected to be a serious problem.
  115438. */
  115439. assert( pTree->aData==(char *)&pTree[1] );
  115440. pTree->aData = (char *)sqlite3_malloc(nReq);
  115441. if( !pTree->aData ){
  115442. return SQLITE_NOMEM;
  115443. }
  115444. }
  115445. if( pTree->zTerm ){
  115446. /* There is no prefix-length field for first term in a node */
  115447. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  115448. }
  115449. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  115450. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  115451. pTree->nData = nData + nSuffix;
  115452. pTree->nEntry++;
  115453. if( isCopyTerm ){
  115454. if( pTree->nMalloc<nTerm ){
  115455. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  115456. if( !zNew ){
  115457. return SQLITE_NOMEM;
  115458. }
  115459. pTree->nMalloc = nTerm*2;
  115460. pTree->zMalloc = zNew;
  115461. }
  115462. pTree->zTerm = pTree->zMalloc;
  115463. memcpy(pTree->zTerm, zTerm, nTerm);
  115464. pTree->nTerm = nTerm;
  115465. }else{
  115466. pTree->zTerm = (char *)zTerm;
  115467. pTree->nTerm = nTerm;
  115468. }
  115469. return SQLITE_OK;
  115470. }
  115471. }
  115472. /* If control flows to here, it was not possible to append zTerm to the
  115473. ** current node. Create a new node (a right-sibling of the current node).
  115474. ** If this is the first node in the tree, the term is added to it.
  115475. **
  115476. ** Otherwise, the term is not added to the new node, it is left empty for
  115477. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  115478. ** has no parent, one is created here.
  115479. */
  115480. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  115481. if( !pNew ){
  115482. return SQLITE_NOMEM;
  115483. }
  115484. memset(pNew, 0, sizeof(SegmentNode));
  115485. pNew->nData = 1 + FTS3_VARINT_MAX;
  115486. pNew->aData = (char *)&pNew[1];
  115487. if( pTree ){
  115488. SegmentNode *pParent = pTree->pParent;
  115489. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  115490. if( pTree->pParent==0 ){
  115491. pTree->pParent = pParent;
  115492. }
  115493. pTree->pRight = pNew;
  115494. pNew->pLeftmost = pTree->pLeftmost;
  115495. pNew->pParent = pParent;
  115496. pNew->zMalloc = pTree->zMalloc;
  115497. pNew->nMalloc = pTree->nMalloc;
  115498. pTree->zMalloc = 0;
  115499. }else{
  115500. pNew->pLeftmost = pNew;
  115501. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  115502. }
  115503. *ppTree = pNew;
  115504. return rc;
  115505. }
  115506. /*
  115507. ** Helper function for fts3NodeWrite().
  115508. */
  115509. static int fts3TreeFinishNode(
  115510. SegmentNode *pTree,
  115511. int iHeight,
  115512. sqlite3_int64 iLeftChild
  115513. ){
  115514. int nStart;
  115515. assert( iHeight>=1 && iHeight<128 );
  115516. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  115517. pTree->aData[nStart] = (char)iHeight;
  115518. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  115519. return nStart;
  115520. }
  115521. /*
  115522. ** Write the buffer for the segment node pTree and all of its peers to the
  115523. ** database. Then call this function recursively to write the parent of
  115524. ** pTree and its peers to the database.
  115525. **
  115526. ** Except, if pTree is a root node, do not write it to the database. Instead,
  115527. ** set output variables *paRoot and *pnRoot to contain the root node.
  115528. **
  115529. ** If successful, SQLITE_OK is returned and output variable *piLast is
  115530. ** set to the largest blockid written to the database (or zero if no
  115531. ** blocks were written to the db). Otherwise, an SQLite error code is
  115532. ** returned.
  115533. */
  115534. static int fts3NodeWrite(
  115535. Fts3Table *p, /* Virtual table handle */
  115536. SegmentNode *pTree, /* SegmentNode handle */
  115537. int iHeight, /* Height of this node in tree */
  115538. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  115539. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  115540. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  115541. char **paRoot, /* OUT: Data for root node */
  115542. int *pnRoot /* OUT: Size of root node in bytes */
  115543. ){
  115544. int rc = SQLITE_OK;
  115545. if( !pTree->pParent ){
  115546. /* Root node of the tree. */
  115547. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  115548. *piLast = iFree-1;
  115549. *pnRoot = pTree->nData - nStart;
  115550. *paRoot = &pTree->aData[nStart];
  115551. }else{
  115552. SegmentNode *pIter;
  115553. sqlite3_int64 iNextFree = iFree;
  115554. sqlite3_int64 iNextLeaf = iLeaf;
  115555. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  115556. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  115557. int nWrite = pIter->nData - nStart;
  115558. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  115559. iNextFree++;
  115560. iNextLeaf += (pIter->nEntry+1);
  115561. }
  115562. if( rc==SQLITE_OK ){
  115563. assert( iNextLeaf==iFree );
  115564. rc = fts3NodeWrite(
  115565. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  115566. );
  115567. }
  115568. }
  115569. return rc;
  115570. }
  115571. /*
  115572. ** Free all memory allocations associated with the tree pTree.
  115573. */
  115574. static void fts3NodeFree(SegmentNode *pTree){
  115575. if( pTree ){
  115576. SegmentNode *p = pTree->pLeftmost;
  115577. fts3NodeFree(p->pParent);
  115578. while( p ){
  115579. SegmentNode *pRight = p->pRight;
  115580. if( p->aData!=(char *)&p[1] ){
  115581. sqlite3_free(p->aData);
  115582. }
  115583. assert( pRight==0 || p->zMalloc==0 );
  115584. sqlite3_free(p->zMalloc);
  115585. sqlite3_free(p);
  115586. p = pRight;
  115587. }
  115588. }
  115589. }
  115590. /*
  115591. ** Add a term to the segment being constructed by the SegmentWriter object
  115592. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  115593. ** be passed NULL. This function will allocate a new SegmentWriter object
  115594. ** and return it via the input/output variable *ppWriter in this case.
  115595. **
  115596. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  115597. */
  115598. static int fts3SegWriterAdd(
  115599. Fts3Table *p, /* Virtual table handle */
  115600. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  115601. int isCopyTerm, /* True if buffer zTerm must be copied */
  115602. const char *zTerm, /* Pointer to buffer containing term */
  115603. int nTerm, /* Size of term in bytes */
  115604. const char *aDoclist, /* Pointer to buffer containing doclist */
  115605. int nDoclist /* Size of doclist in bytes */
  115606. ){
  115607. int nPrefix; /* Size of term prefix in bytes */
  115608. int nSuffix; /* Size of term suffix in bytes */
  115609. int nReq; /* Number of bytes required on leaf page */
  115610. int nData;
  115611. SegmentWriter *pWriter = *ppWriter;
  115612. if( !pWriter ){
  115613. int rc;
  115614. sqlite3_stmt *pStmt;
  115615. /* Allocate the SegmentWriter structure */
  115616. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  115617. if( !pWriter ) return SQLITE_NOMEM;
  115618. memset(pWriter, 0, sizeof(SegmentWriter));
  115619. *ppWriter = pWriter;
  115620. /* Allocate a buffer in which to accumulate data */
  115621. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  115622. if( !pWriter->aData ) return SQLITE_NOMEM;
  115623. pWriter->nSize = p->nNodeSize;
  115624. /* Find the next free blockid in the %_segments table */
  115625. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  115626. if( rc!=SQLITE_OK ) return rc;
  115627. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115628. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  115629. pWriter->iFirst = pWriter->iFree;
  115630. }
  115631. rc = sqlite3_reset(pStmt);
  115632. if( rc!=SQLITE_OK ) return rc;
  115633. }
  115634. nData = pWriter->nData;
  115635. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  115636. nSuffix = nTerm-nPrefix;
  115637. /* Figure out how many bytes are required by this new entry */
  115638. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  115639. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  115640. nSuffix + /* Term suffix */
  115641. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  115642. nDoclist; /* Doclist data */
  115643. if( nData>0 && nData+nReq>p->nNodeSize ){
  115644. int rc;
  115645. /* The current leaf node is full. Write it out to the database. */
  115646. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  115647. if( rc!=SQLITE_OK ) return rc;
  115648. p->nLeafAdd++;
  115649. /* Add the current term to the interior node tree. The term added to
  115650. ** the interior tree must:
  115651. **
  115652. ** a) be greater than the largest term on the leaf node just written
  115653. ** to the database (still available in pWriter->zTerm), and
  115654. **
  115655. ** b) be less than or equal to the term about to be added to the new
  115656. ** leaf node (zTerm/nTerm).
  115657. **
  115658. ** In other words, it must be the prefix of zTerm 1 byte longer than
  115659. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  115660. */
  115661. assert( nPrefix<nTerm );
  115662. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  115663. if( rc!=SQLITE_OK ) return rc;
  115664. nData = 0;
  115665. pWriter->nTerm = 0;
  115666. nPrefix = 0;
  115667. nSuffix = nTerm;
  115668. nReq = 1 + /* varint containing prefix size */
  115669. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  115670. nTerm + /* Term suffix */
  115671. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  115672. nDoclist; /* Doclist data */
  115673. }
  115674. /* If the buffer currently allocated is too small for this entry, realloc
  115675. ** the buffer to make it large enough.
  115676. */
  115677. if( nReq>pWriter->nSize ){
  115678. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  115679. if( !aNew ) return SQLITE_NOMEM;
  115680. pWriter->aData = aNew;
  115681. pWriter->nSize = nReq;
  115682. }
  115683. assert( nData+nReq<=pWriter->nSize );
  115684. /* Append the prefix-compressed term and doclist to the buffer. */
  115685. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  115686. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  115687. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  115688. nData += nSuffix;
  115689. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  115690. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  115691. pWriter->nData = nData + nDoclist;
  115692. /* Save the current term so that it can be used to prefix-compress the next.
  115693. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  115694. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  115695. ** store a copy of the pointer.
  115696. */
  115697. if( isCopyTerm ){
  115698. if( nTerm>pWriter->nMalloc ){
  115699. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  115700. if( !zNew ){
  115701. return SQLITE_NOMEM;
  115702. }
  115703. pWriter->nMalloc = nTerm*2;
  115704. pWriter->zMalloc = zNew;
  115705. pWriter->zTerm = zNew;
  115706. }
  115707. assert( pWriter->zTerm==pWriter->zMalloc );
  115708. memcpy(pWriter->zTerm, zTerm, nTerm);
  115709. }else{
  115710. pWriter->zTerm = (char *)zTerm;
  115711. }
  115712. pWriter->nTerm = nTerm;
  115713. return SQLITE_OK;
  115714. }
  115715. /*
  115716. ** Flush all data associated with the SegmentWriter object pWriter to the
  115717. ** database. This function must be called after all terms have been added
  115718. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  115719. ** returned. Otherwise, an SQLite error code.
  115720. */
  115721. static int fts3SegWriterFlush(
  115722. Fts3Table *p, /* Virtual table handle */
  115723. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  115724. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  115725. int iIdx /* Value for 'idx' column of %_segdir */
  115726. ){
  115727. int rc; /* Return code */
  115728. if( pWriter->pTree ){
  115729. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  115730. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  115731. char *zRoot = NULL; /* Pointer to buffer containing root node */
  115732. int nRoot = 0; /* Size of buffer zRoot */
  115733. iLastLeaf = pWriter->iFree;
  115734. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  115735. if( rc==SQLITE_OK ){
  115736. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  115737. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  115738. }
  115739. if( rc==SQLITE_OK ){
  115740. rc = fts3WriteSegdir(
  115741. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  115742. }
  115743. }else{
  115744. /* The entire tree fits on the root node. Write it to the segdir table. */
  115745. rc = fts3WriteSegdir(
  115746. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  115747. }
  115748. p->nLeafAdd++;
  115749. return rc;
  115750. }
  115751. /*
  115752. ** Release all memory held by the SegmentWriter object passed as the
  115753. ** first argument.
  115754. */
  115755. static void fts3SegWriterFree(SegmentWriter *pWriter){
  115756. if( pWriter ){
  115757. sqlite3_free(pWriter->aData);
  115758. sqlite3_free(pWriter->zMalloc);
  115759. fts3NodeFree(pWriter->pTree);
  115760. sqlite3_free(pWriter);
  115761. }
  115762. }
  115763. /*
  115764. ** The first value in the apVal[] array is assumed to contain an integer.
  115765. ** This function tests if there exist any documents with docid values that
  115766. ** are different from that integer. i.e. if deleting the document with docid
  115767. ** pRowid would mean the FTS3 table were empty.
  115768. **
  115769. ** If successful, *pisEmpty is set to true if the table is empty except for
  115770. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  115771. ** error occurs, an SQLite error code is returned.
  115772. */
  115773. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  115774. sqlite3_stmt *pStmt;
  115775. int rc;
  115776. if( p->zContentTbl ){
  115777. /* If using the content=xxx option, assume the table is never empty */
  115778. *pisEmpty = 0;
  115779. rc = SQLITE_OK;
  115780. }else{
  115781. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  115782. if( rc==SQLITE_OK ){
  115783. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115784. *pisEmpty = sqlite3_column_int(pStmt, 0);
  115785. }
  115786. rc = sqlite3_reset(pStmt);
  115787. }
  115788. }
  115789. return rc;
  115790. }
  115791. /*
  115792. ** Set *pnMax to the largest segment level in the database for the index
  115793. ** iIndex.
  115794. **
  115795. ** Segment levels are stored in the 'level' column of the %_segdir table.
  115796. **
  115797. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  115798. */
  115799. static int fts3SegmentMaxLevel(
  115800. Fts3Table *p,
  115801. int iLangid,
  115802. int iIndex,
  115803. sqlite3_int64 *pnMax
  115804. ){
  115805. sqlite3_stmt *pStmt;
  115806. int rc;
  115807. assert( iIndex>=0 && iIndex<p->nIndex );
  115808. /* Set pStmt to the compiled version of:
  115809. **
  115810. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  115811. **
  115812. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  115813. */
  115814. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  115815. if( rc!=SQLITE_OK ) return rc;
  115816. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  115817. sqlite3_bind_int64(pStmt, 2,
  115818. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  115819. );
  115820. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115821. *pnMax = sqlite3_column_int64(pStmt, 0);
  115822. }
  115823. return sqlite3_reset(pStmt);
  115824. }
  115825. /*
  115826. ** Delete all entries in the %_segments table associated with the segment
  115827. ** opened with seg-reader pSeg. This function does not affect the contents
  115828. ** of the %_segdir table.
  115829. */
  115830. static int fts3DeleteSegment(
  115831. Fts3Table *p, /* FTS table handle */
  115832. Fts3SegReader *pSeg /* Segment to delete */
  115833. ){
  115834. int rc = SQLITE_OK; /* Return code */
  115835. if( pSeg->iStartBlock ){
  115836. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  115837. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  115838. if( rc==SQLITE_OK ){
  115839. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  115840. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  115841. sqlite3_step(pDelete);
  115842. rc = sqlite3_reset(pDelete);
  115843. }
  115844. }
  115845. return rc;
  115846. }
  115847. /*
  115848. ** This function is used after merging multiple segments into a single large
  115849. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  115850. ** it:
  115851. **
  115852. ** 1) Deletes all %_segments entries for the segments associated with
  115853. ** each of the SegReader objects in the array passed as the third
  115854. ** argument, and
  115855. **
  115856. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  115857. ** entries regardless of level if (iLevel<0).
  115858. **
  115859. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  115860. */
  115861. static int fts3DeleteSegdir(
  115862. Fts3Table *p, /* Virtual table handle */
  115863. int iLangid, /* Language id */
  115864. int iIndex, /* Index for p->aIndex */
  115865. int iLevel, /* Level of %_segdir entries to delete */
  115866. Fts3SegReader **apSegment, /* Array of SegReader objects */
  115867. int nReader /* Size of array apSegment */
  115868. ){
  115869. int rc = SQLITE_OK; /* Return Code */
  115870. int i; /* Iterator variable */
  115871. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  115872. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  115873. rc = fts3DeleteSegment(p, apSegment[i]);
  115874. }
  115875. if( rc!=SQLITE_OK ){
  115876. return rc;
  115877. }
  115878. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  115879. if( iLevel==FTS3_SEGCURSOR_ALL ){
  115880. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  115881. if( rc==SQLITE_OK ){
  115882. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  115883. sqlite3_bind_int64(pDelete, 2,
  115884. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  115885. );
  115886. }
  115887. }else{
  115888. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  115889. if( rc==SQLITE_OK ){
  115890. sqlite3_bind_int64(
  115891. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  115892. );
  115893. }
  115894. }
  115895. if( rc==SQLITE_OK ){
  115896. sqlite3_step(pDelete);
  115897. rc = sqlite3_reset(pDelete);
  115898. }
  115899. return rc;
  115900. }
  115901. /*
  115902. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  115903. ** a position list that may (or may not) feature multiple columns. This
  115904. ** function adjusts the pointer *ppList and the length *pnList so that they
  115905. ** identify the subset of the position list that corresponds to column iCol.
  115906. **
  115907. ** If there are no entries in the input position list for column iCol, then
  115908. ** *pnList is set to zero before returning.
  115909. **
  115910. ** If parameter bZero is non-zero, then any part of the input list following
  115911. ** the end of the output list is zeroed before returning.
  115912. */
  115913. static void fts3ColumnFilter(
  115914. int iCol, /* Column to filter on */
  115915. int bZero, /* Zero out anything following *ppList */
  115916. char **ppList, /* IN/OUT: Pointer to position list */
  115917. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  115918. ){
  115919. char *pList = *ppList;
  115920. int nList = *pnList;
  115921. char *pEnd = &pList[nList];
  115922. int iCurrent = 0;
  115923. char *p = pList;
  115924. assert( iCol>=0 );
  115925. while( 1 ){
  115926. char c = 0;
  115927. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  115928. if( iCol==iCurrent ){
  115929. nList = (int)(p - pList);
  115930. break;
  115931. }
  115932. nList -= (int)(p - pList);
  115933. pList = p;
  115934. if( nList==0 ){
  115935. break;
  115936. }
  115937. p = &pList[1];
  115938. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  115939. }
  115940. if( bZero && &pList[nList]!=pEnd ){
  115941. memset(&pList[nList], 0, pEnd - &pList[nList]);
  115942. }
  115943. *ppList = pList;
  115944. *pnList = nList;
  115945. }
  115946. /*
  115947. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  115948. ** existing data). Grow the buffer if required.
  115949. **
  115950. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  115951. ** trying to resize the buffer, return SQLITE_NOMEM.
  115952. */
  115953. static int fts3MsrBufferData(
  115954. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  115955. char *pList,
  115956. int nList
  115957. ){
  115958. if( nList>pMsr->nBuffer ){
  115959. char *pNew;
  115960. pMsr->nBuffer = nList*2;
  115961. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  115962. if( !pNew ) return SQLITE_NOMEM;
  115963. pMsr->aBuffer = pNew;
  115964. }
  115965. memcpy(pMsr->aBuffer, pList, nList);
  115966. return SQLITE_OK;
  115967. }
  115968. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  115969. Fts3Table *p, /* Virtual table handle */
  115970. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  115971. sqlite3_int64 *piDocid, /* OUT: Docid value */
  115972. char **paPoslist, /* OUT: Pointer to position list */
  115973. int *pnPoslist /* OUT: Size of position list in bytes */
  115974. ){
  115975. int nMerge = pMsr->nAdvance;
  115976. Fts3SegReader **apSegment = pMsr->apSegment;
  115977. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  115978. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  115979. );
  115980. if( nMerge==0 ){
  115981. *paPoslist = 0;
  115982. return SQLITE_OK;
  115983. }
  115984. while( 1 ){
  115985. Fts3SegReader *pSeg;
  115986. pSeg = pMsr->apSegment[0];
  115987. if( pSeg->pOffsetList==0 ){
  115988. *paPoslist = 0;
  115989. break;
  115990. }else{
  115991. int rc;
  115992. char *pList;
  115993. int nList;
  115994. int j;
  115995. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  115996. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  115997. j = 1;
  115998. while( rc==SQLITE_OK
  115999. && j<nMerge
  116000. && apSegment[j]->pOffsetList
  116001. && apSegment[j]->iDocid==iDocid
  116002. ){
  116003. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  116004. j++;
  116005. }
  116006. if( rc!=SQLITE_OK ) return rc;
  116007. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  116008. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  116009. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  116010. if( rc!=SQLITE_OK ) return rc;
  116011. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  116012. pList = pMsr->aBuffer;
  116013. }
  116014. if( pMsr->iColFilter>=0 ){
  116015. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  116016. }
  116017. if( nList>0 ){
  116018. *paPoslist = pList;
  116019. *piDocid = iDocid;
  116020. *pnPoslist = nList;
  116021. break;
  116022. }
  116023. }
  116024. }
  116025. return SQLITE_OK;
  116026. }
  116027. static int fts3SegReaderStart(
  116028. Fts3Table *p, /* Virtual table handle */
  116029. Fts3MultiSegReader *pCsr, /* Cursor object */
  116030. const char *zTerm, /* Term searched for (or NULL) */
  116031. int nTerm /* Length of zTerm in bytes */
  116032. ){
  116033. int i;
  116034. int nSeg = pCsr->nSegment;
  116035. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  116036. ** for, then advance each segment iterator until it points to a term of
  116037. ** equal or greater value than the specified term. This prevents many
  116038. ** unnecessary merge/sort operations for the case where single segment
  116039. ** b-tree leaf nodes contain more than one term.
  116040. */
  116041. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  116042. int res = 0;
  116043. Fts3SegReader *pSeg = pCsr->apSegment[i];
  116044. do {
  116045. int rc = fts3SegReaderNext(p, pSeg, 0);
  116046. if( rc!=SQLITE_OK ) return rc;
  116047. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  116048. if( pSeg->bLookup && res!=0 ){
  116049. fts3SegReaderSetEof(pSeg);
  116050. }
  116051. }
  116052. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  116053. return SQLITE_OK;
  116054. }
  116055. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  116056. Fts3Table *p, /* Virtual table handle */
  116057. Fts3MultiSegReader *pCsr, /* Cursor object */
  116058. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  116059. ){
  116060. pCsr->pFilter = pFilter;
  116061. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  116062. }
  116063. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  116064. Fts3Table *p, /* Virtual table handle */
  116065. Fts3MultiSegReader *pCsr, /* Cursor object */
  116066. int iCol, /* Column to match on. */
  116067. const char *zTerm, /* Term to iterate through a doclist for */
  116068. int nTerm /* Number of bytes in zTerm */
  116069. ){
  116070. int i;
  116071. int rc;
  116072. int nSegment = pCsr->nSegment;
  116073. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  116074. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  116075. );
  116076. assert( pCsr->pFilter==0 );
  116077. assert( zTerm && nTerm>0 );
  116078. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  116079. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  116080. if( rc!=SQLITE_OK ) return rc;
  116081. /* Determine how many of the segments actually point to zTerm/nTerm. */
  116082. for(i=0; i<nSegment; i++){
  116083. Fts3SegReader *pSeg = pCsr->apSegment[i];
  116084. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  116085. break;
  116086. }
  116087. }
  116088. pCsr->nAdvance = i;
  116089. /* Advance each of the segments to point to the first docid. */
  116090. for(i=0; i<pCsr->nAdvance; i++){
  116091. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  116092. if( rc!=SQLITE_OK ) return rc;
  116093. }
  116094. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  116095. assert( iCol<0 || iCol<p->nColumn );
  116096. pCsr->iColFilter = iCol;
  116097. return SQLITE_OK;
  116098. }
  116099. /*
  116100. ** This function is called on a MultiSegReader that has been started using
  116101. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  116102. ** have been made. Calling this function puts the MultiSegReader in such
  116103. ** a state that if the next two calls are:
  116104. **
  116105. ** sqlite3Fts3SegReaderStart()
  116106. ** sqlite3Fts3SegReaderStep()
  116107. **
  116108. ** then the entire doclist for the term is available in
  116109. ** MultiSegReader.aDoclist/nDoclist.
  116110. */
  116111. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  116112. int i; /* Used to iterate through segment-readers */
  116113. assert( pCsr->zTerm==0 );
  116114. assert( pCsr->nTerm==0 );
  116115. assert( pCsr->aDoclist==0 );
  116116. assert( pCsr->nDoclist==0 );
  116117. pCsr->nAdvance = 0;
  116118. pCsr->bRestart = 1;
  116119. for(i=0; i<pCsr->nSegment; i++){
  116120. pCsr->apSegment[i]->pOffsetList = 0;
  116121. pCsr->apSegment[i]->nOffsetList = 0;
  116122. pCsr->apSegment[i]->iDocid = 0;
  116123. }
  116124. return SQLITE_OK;
  116125. }
  116126. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  116127. Fts3Table *p, /* Virtual table handle */
  116128. Fts3MultiSegReader *pCsr /* Cursor object */
  116129. ){
  116130. int rc = SQLITE_OK;
  116131. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  116132. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  116133. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  116134. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  116135. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  116136. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  116137. Fts3SegReader **apSegment = pCsr->apSegment;
  116138. int nSegment = pCsr->nSegment;
  116139. Fts3SegFilter *pFilter = pCsr->pFilter;
  116140. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  116141. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  116142. );
  116143. if( pCsr->nSegment==0 ) return SQLITE_OK;
  116144. do {
  116145. int nMerge;
  116146. int i;
  116147. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  116148. ** forward. Then sort the list in order of current term again.
  116149. */
  116150. for(i=0; i<pCsr->nAdvance; i++){
  116151. Fts3SegReader *pSeg = apSegment[i];
  116152. if( pSeg->bLookup ){
  116153. fts3SegReaderSetEof(pSeg);
  116154. }else{
  116155. rc = fts3SegReaderNext(p, pSeg, 0);
  116156. }
  116157. if( rc!=SQLITE_OK ) return rc;
  116158. }
  116159. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  116160. pCsr->nAdvance = 0;
  116161. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  116162. assert( rc==SQLITE_OK );
  116163. if( apSegment[0]->aNode==0 ) break;
  116164. pCsr->nTerm = apSegment[0]->nTerm;
  116165. pCsr->zTerm = apSegment[0]->zTerm;
  116166. /* If this is a prefix-search, and if the term that apSegment[0] points
  116167. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  116168. ** required callbacks have been made. In this case exit early.
  116169. **
  116170. ** Similarly, if this is a search for an exact match, and the first term
  116171. ** of segment apSegment[0] is not a match, exit early.
  116172. */
  116173. if( pFilter->zTerm && !isScan ){
  116174. if( pCsr->nTerm<pFilter->nTerm
  116175. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  116176. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  116177. ){
  116178. break;
  116179. }
  116180. }
  116181. nMerge = 1;
  116182. while( nMerge<nSegment
  116183. && apSegment[nMerge]->aNode
  116184. && apSegment[nMerge]->nTerm==pCsr->nTerm
  116185. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  116186. ){
  116187. nMerge++;
  116188. }
  116189. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  116190. if( nMerge==1
  116191. && !isIgnoreEmpty
  116192. && !isFirst
  116193. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  116194. ){
  116195. pCsr->nDoclist = apSegment[0]->nDoclist;
  116196. if( fts3SegReaderIsPending(apSegment[0]) ){
  116197. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  116198. pCsr->aDoclist = pCsr->aBuffer;
  116199. }else{
  116200. pCsr->aDoclist = apSegment[0]->aDoclist;
  116201. }
  116202. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  116203. }else{
  116204. int nDoclist = 0; /* Size of doclist */
  116205. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  116206. /* The current term of the first nMerge entries in the array
  116207. ** of Fts3SegReader objects is the same. The doclists must be merged
  116208. ** and a single term returned with the merged doclist.
  116209. */
  116210. for(i=0; i<nMerge; i++){
  116211. fts3SegReaderFirstDocid(p, apSegment[i]);
  116212. }
  116213. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  116214. while( apSegment[0]->pOffsetList ){
  116215. int j; /* Number of segments that share a docid */
  116216. char *pList = 0;
  116217. int nList = 0;
  116218. int nByte;
  116219. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  116220. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  116221. j = 1;
  116222. while( j<nMerge
  116223. && apSegment[j]->pOffsetList
  116224. && apSegment[j]->iDocid==iDocid
  116225. ){
  116226. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  116227. j++;
  116228. }
  116229. if( isColFilter ){
  116230. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  116231. }
  116232. if( !isIgnoreEmpty || nList>0 ){
  116233. /* Calculate the 'docid' delta value to write into the merged
  116234. ** doclist. */
  116235. sqlite3_int64 iDelta;
  116236. if( p->bDescIdx && nDoclist>0 ){
  116237. iDelta = iPrev - iDocid;
  116238. }else{
  116239. iDelta = iDocid - iPrev;
  116240. }
  116241. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  116242. assert( nDoclist>0 || iDelta==iDocid );
  116243. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  116244. if( nDoclist+nByte>pCsr->nBuffer ){
  116245. char *aNew;
  116246. pCsr->nBuffer = (nDoclist+nByte)*2;
  116247. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  116248. if( !aNew ){
  116249. return SQLITE_NOMEM;
  116250. }
  116251. pCsr->aBuffer = aNew;
  116252. }
  116253. if( isFirst ){
  116254. char *a = &pCsr->aBuffer[nDoclist];
  116255. int nWrite;
  116256. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  116257. if( nWrite ){
  116258. iPrev = iDocid;
  116259. nDoclist += nWrite;
  116260. }
  116261. }else{
  116262. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  116263. iPrev = iDocid;
  116264. if( isRequirePos ){
  116265. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  116266. nDoclist += nList;
  116267. pCsr->aBuffer[nDoclist++] = '\0';
  116268. }
  116269. }
  116270. }
  116271. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  116272. }
  116273. if( nDoclist>0 ){
  116274. pCsr->aDoclist = pCsr->aBuffer;
  116275. pCsr->nDoclist = nDoclist;
  116276. rc = SQLITE_ROW;
  116277. }
  116278. }
  116279. pCsr->nAdvance = nMerge;
  116280. }while( rc==SQLITE_OK );
  116281. return rc;
  116282. }
  116283. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  116284. Fts3MultiSegReader *pCsr /* Cursor object */
  116285. ){
  116286. if( pCsr ){
  116287. int i;
  116288. for(i=0; i<pCsr->nSegment; i++){
  116289. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  116290. }
  116291. sqlite3_free(pCsr->apSegment);
  116292. sqlite3_free(pCsr->aBuffer);
  116293. pCsr->nSegment = 0;
  116294. pCsr->apSegment = 0;
  116295. pCsr->aBuffer = 0;
  116296. }
  116297. }
  116298. /*
  116299. ** Merge all level iLevel segments in the database into a single
  116300. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  116301. ** single segment with a level equal to the numerically largest level
  116302. ** currently present in the database.
  116303. **
  116304. ** If this function is called with iLevel<0, but there is only one
  116305. ** segment in the database, SQLITE_DONE is returned immediately.
  116306. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  116307. ** an SQLite error code is returned.
  116308. */
  116309. static int fts3SegmentMerge(
  116310. Fts3Table *p,
  116311. int iLangid, /* Language id to merge */
  116312. int iIndex, /* Index in p->aIndex[] to merge */
  116313. int iLevel /* Level to merge */
  116314. ){
  116315. int rc; /* Return code */
  116316. int iIdx = 0; /* Index of new segment */
  116317. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  116318. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  116319. Fts3SegFilter filter; /* Segment term filter condition */
  116320. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  116321. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  116322. assert( iLevel==FTS3_SEGCURSOR_ALL
  116323. || iLevel==FTS3_SEGCURSOR_PENDING
  116324. || iLevel>=0
  116325. );
  116326. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  116327. assert( iIndex>=0 && iIndex<p->nIndex );
  116328. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  116329. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  116330. if( iLevel==FTS3_SEGCURSOR_ALL ){
  116331. /* This call is to merge all segments in the database to a single
  116332. ** segment. The level of the new segment is equal to the numerically
  116333. ** greatest segment level currently present in the database for this
  116334. ** index. The idx of the new segment is always 0. */
  116335. if( csr.nSegment==1 ){
  116336. rc = SQLITE_DONE;
  116337. goto finished;
  116338. }
  116339. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  116340. bIgnoreEmpty = 1;
  116341. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  116342. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  116343. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  116344. }else{
  116345. /* This call is to merge all segments at level iLevel. find the next
  116346. ** available segment index at level iLevel+1. The call to
  116347. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  116348. ** a single iLevel+2 segment if necessary. */
  116349. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  116350. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  116351. }
  116352. if( rc!=SQLITE_OK ) goto finished;
  116353. assert( csr.nSegment>0 );
  116354. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  116355. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  116356. memset(&filter, 0, sizeof(Fts3SegFilter));
  116357. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  116358. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  116359. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  116360. while( SQLITE_OK==rc ){
  116361. rc = sqlite3Fts3SegReaderStep(p, &csr);
  116362. if( rc!=SQLITE_ROW ) break;
  116363. rc = fts3SegWriterAdd(p, &pWriter, 1,
  116364. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  116365. }
  116366. if( rc!=SQLITE_OK ) goto finished;
  116367. assert( pWriter );
  116368. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  116369. rc = fts3DeleteSegdir(
  116370. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  116371. );
  116372. if( rc!=SQLITE_OK ) goto finished;
  116373. }
  116374. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  116375. finished:
  116376. fts3SegWriterFree(pWriter);
  116377. sqlite3Fts3SegReaderFinish(&csr);
  116378. return rc;
  116379. }
  116380. /*
  116381. ** Flush the contents of pendingTerms to level 0 segments.
  116382. */
  116383. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  116384. int rc = SQLITE_OK;
  116385. int i;
  116386. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  116387. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  116388. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  116389. }
  116390. sqlite3Fts3PendingTermsClear(p);
  116391. /* Determine the auto-incr-merge setting if unknown. If enabled,
  116392. ** estimate the number of leaf blocks of content to be written
  116393. */
  116394. if( rc==SQLITE_OK && p->bHasStat
  116395. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  116396. ){
  116397. sqlite3_stmt *pStmt = 0;
  116398. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  116399. if( rc==SQLITE_OK ){
  116400. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  116401. rc = sqlite3_step(pStmt);
  116402. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  116403. rc = sqlite3_reset(pStmt);
  116404. }
  116405. }
  116406. return rc;
  116407. }
  116408. /*
  116409. ** Encode N integers as varints into a blob.
  116410. */
  116411. static void fts3EncodeIntArray(
  116412. int N, /* The number of integers to encode */
  116413. u32 *a, /* The integer values */
  116414. char *zBuf, /* Write the BLOB here */
  116415. int *pNBuf /* Write number of bytes if zBuf[] used here */
  116416. ){
  116417. int i, j;
  116418. for(i=j=0; i<N; i++){
  116419. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  116420. }
  116421. *pNBuf = j;
  116422. }
  116423. /*
  116424. ** Decode a blob of varints into N integers
  116425. */
  116426. static void fts3DecodeIntArray(
  116427. int N, /* The number of integers to decode */
  116428. u32 *a, /* Write the integer values */
  116429. const char *zBuf, /* The BLOB containing the varints */
  116430. int nBuf /* size of the BLOB */
  116431. ){
  116432. int i, j;
  116433. UNUSED_PARAMETER(nBuf);
  116434. for(i=j=0; i<N; i++){
  116435. sqlite3_int64 x;
  116436. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  116437. assert(j<=nBuf);
  116438. a[i] = (u32)(x & 0xffffffff);
  116439. }
  116440. }
  116441. /*
  116442. ** Insert the sizes (in tokens) for each column of the document
  116443. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  116444. ** a blob of varints.
  116445. */
  116446. static void fts3InsertDocsize(
  116447. int *pRC, /* Result code */
  116448. Fts3Table *p, /* Table into which to insert */
  116449. u32 *aSz /* Sizes of each column, in tokens */
  116450. ){
  116451. char *pBlob; /* The BLOB encoding of the document size */
  116452. int nBlob; /* Number of bytes in the BLOB */
  116453. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  116454. int rc; /* Result code from subfunctions */
  116455. if( *pRC ) return;
  116456. pBlob = sqlite3_malloc( 10*p->nColumn );
  116457. if( pBlob==0 ){
  116458. *pRC = SQLITE_NOMEM;
  116459. return;
  116460. }
  116461. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  116462. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  116463. if( rc ){
  116464. sqlite3_free(pBlob);
  116465. *pRC = rc;
  116466. return;
  116467. }
  116468. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  116469. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  116470. sqlite3_step(pStmt);
  116471. *pRC = sqlite3_reset(pStmt);
  116472. }
  116473. /*
  116474. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  116475. ** where N is the number of user defined columns in the fts3 table plus
  116476. ** two. If nCol is the number of user defined columns, then values of the
  116477. ** varints are set as follows:
  116478. **
  116479. ** Varint 0: Total number of rows in the table.
  116480. **
  116481. ** Varint 1..nCol: For each column, the total number of tokens stored in
  116482. ** the column for all rows of the table.
  116483. **
  116484. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  116485. ** columns of all rows of the table.
  116486. **
  116487. */
  116488. static void fts3UpdateDocTotals(
  116489. int *pRC, /* The result code */
  116490. Fts3Table *p, /* Table being updated */
  116491. u32 *aSzIns, /* Size increases */
  116492. u32 *aSzDel, /* Size decreases */
  116493. int nChng /* Change in the number of documents */
  116494. ){
  116495. char *pBlob; /* Storage for BLOB written into %_stat */
  116496. int nBlob; /* Size of BLOB written into %_stat */
  116497. u32 *a; /* Array of integers that becomes the BLOB */
  116498. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  116499. int i; /* Loop counter */
  116500. int rc; /* Result code from subfunctions */
  116501. const int nStat = p->nColumn+2;
  116502. if( *pRC ) return;
  116503. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  116504. if( a==0 ){
  116505. *pRC = SQLITE_NOMEM;
  116506. return;
  116507. }
  116508. pBlob = (char*)&a[nStat];
  116509. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  116510. if( rc ){
  116511. sqlite3_free(a);
  116512. *pRC = rc;
  116513. return;
  116514. }
  116515. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  116516. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  116517. fts3DecodeIntArray(nStat, a,
  116518. sqlite3_column_blob(pStmt, 0),
  116519. sqlite3_column_bytes(pStmt, 0));
  116520. }else{
  116521. memset(a, 0, sizeof(u32)*(nStat) );
  116522. }
  116523. rc = sqlite3_reset(pStmt);
  116524. if( rc!=SQLITE_OK ){
  116525. sqlite3_free(a);
  116526. *pRC = rc;
  116527. return;
  116528. }
  116529. if( nChng<0 && a[0]<(u32)(-nChng) ){
  116530. a[0] = 0;
  116531. }else{
  116532. a[0] += nChng;
  116533. }
  116534. for(i=0; i<p->nColumn+1; i++){
  116535. u32 x = a[i+1];
  116536. if( x+aSzIns[i] < aSzDel[i] ){
  116537. x = 0;
  116538. }else{
  116539. x = x + aSzIns[i] - aSzDel[i];
  116540. }
  116541. a[i+1] = x;
  116542. }
  116543. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  116544. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  116545. if( rc ){
  116546. sqlite3_free(a);
  116547. *pRC = rc;
  116548. return;
  116549. }
  116550. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  116551. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  116552. sqlite3_step(pStmt);
  116553. *pRC = sqlite3_reset(pStmt);
  116554. sqlite3_free(a);
  116555. }
  116556. /*
  116557. ** Merge the entire database so that there is one segment for each
  116558. ** iIndex/iLangid combination.
  116559. */
  116560. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  116561. int bSeenDone = 0;
  116562. int rc;
  116563. sqlite3_stmt *pAllLangid = 0;
  116564. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  116565. if( rc==SQLITE_OK ){
  116566. int rc2;
  116567. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  116568. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  116569. int i;
  116570. int iLangid = sqlite3_column_int(pAllLangid, 0);
  116571. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  116572. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  116573. if( rc==SQLITE_DONE ){
  116574. bSeenDone = 1;
  116575. rc = SQLITE_OK;
  116576. }
  116577. }
  116578. }
  116579. rc2 = sqlite3_reset(pAllLangid);
  116580. if( rc==SQLITE_OK ) rc = rc2;
  116581. }
  116582. sqlite3Fts3SegmentsClose(p);
  116583. sqlite3Fts3PendingTermsClear(p);
  116584. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  116585. }
  116586. /*
  116587. ** This function is called when the user executes the following statement:
  116588. **
  116589. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  116590. **
  116591. ** The entire FTS index is discarded and rebuilt. If the table is one
  116592. ** created using the content=xxx option, then the new index is based on
  116593. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  116594. ** on the contents of the %_content table.
  116595. */
  116596. static int fts3DoRebuild(Fts3Table *p){
  116597. int rc; /* Return Code */
  116598. rc = fts3DeleteAll(p, 0);
  116599. if( rc==SQLITE_OK ){
  116600. u32 *aSz = 0;
  116601. u32 *aSzIns = 0;
  116602. u32 *aSzDel = 0;
  116603. sqlite3_stmt *pStmt = 0;
  116604. int nEntry = 0;
  116605. /* Compose and prepare an SQL statement to loop through the content table */
  116606. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  116607. if( !zSql ){
  116608. rc = SQLITE_NOMEM;
  116609. }else{
  116610. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  116611. sqlite3_free(zSql);
  116612. }
  116613. if( rc==SQLITE_OK ){
  116614. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  116615. aSz = (u32 *)sqlite3_malloc(nByte);
  116616. if( aSz==0 ){
  116617. rc = SQLITE_NOMEM;
  116618. }else{
  116619. memset(aSz, 0, nByte);
  116620. aSzIns = &aSz[p->nColumn+1];
  116621. aSzDel = &aSzIns[p->nColumn+1];
  116622. }
  116623. }
  116624. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  116625. int iCol;
  116626. int iLangid = langidFromSelect(p, pStmt);
  116627. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  116628. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  116629. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  116630. if( p->abNotindexed[iCol]==0 ){
  116631. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  116632. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  116633. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  116634. }
  116635. }
  116636. if( p->bHasDocsize ){
  116637. fts3InsertDocsize(&rc, p, aSz);
  116638. }
  116639. if( rc!=SQLITE_OK ){
  116640. sqlite3_finalize(pStmt);
  116641. pStmt = 0;
  116642. }else{
  116643. nEntry++;
  116644. for(iCol=0; iCol<=p->nColumn; iCol++){
  116645. aSzIns[iCol] += aSz[iCol];
  116646. }
  116647. }
  116648. }
  116649. if( p->bFts4 ){
  116650. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  116651. }
  116652. sqlite3_free(aSz);
  116653. if( pStmt ){
  116654. int rc2 = sqlite3_finalize(pStmt);
  116655. if( rc==SQLITE_OK ){
  116656. rc = rc2;
  116657. }
  116658. }
  116659. }
  116660. return rc;
  116661. }
  116662. /*
  116663. ** This function opens a cursor used to read the input data for an
  116664. ** incremental merge operation. Specifically, it opens a cursor to scan
  116665. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  116666. ** level iAbsLevel.
  116667. */
  116668. static int fts3IncrmergeCsr(
  116669. Fts3Table *p, /* FTS3 table handle */
  116670. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  116671. int nSeg, /* Number of segments to merge */
  116672. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  116673. ){
  116674. int rc; /* Return Code */
  116675. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  116676. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  116677. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  116678. memset(pCsr, 0, sizeof(*pCsr));
  116679. nByte = sizeof(Fts3SegReader *) * nSeg;
  116680. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  116681. if( pCsr->apSegment==0 ){
  116682. rc = SQLITE_NOMEM;
  116683. }else{
  116684. memset(pCsr->apSegment, 0, nByte);
  116685. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  116686. }
  116687. if( rc==SQLITE_OK ){
  116688. int i;
  116689. int rc2;
  116690. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  116691. assert( pCsr->nSegment==0 );
  116692. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  116693. rc = sqlite3Fts3SegReaderNew(i, 0,
  116694. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  116695. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  116696. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  116697. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  116698. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  116699. &pCsr->apSegment[i]
  116700. );
  116701. pCsr->nSegment++;
  116702. }
  116703. rc2 = sqlite3_reset(pStmt);
  116704. if( rc==SQLITE_OK ) rc = rc2;
  116705. }
  116706. return rc;
  116707. }
  116708. typedef struct IncrmergeWriter IncrmergeWriter;
  116709. typedef struct NodeWriter NodeWriter;
  116710. typedef struct Blob Blob;
  116711. typedef struct NodeReader NodeReader;
  116712. /*
  116713. ** An instance of the following structure is used as a dynamic buffer
  116714. ** to build up nodes or other blobs of data in.
  116715. **
  116716. ** The function blobGrowBuffer() is used to extend the allocation.
  116717. */
  116718. struct Blob {
  116719. char *a; /* Pointer to allocation */
  116720. int n; /* Number of valid bytes of data in a[] */
  116721. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  116722. };
  116723. /*
  116724. ** This structure is used to build up buffers containing segment b-tree
  116725. ** nodes (blocks).
  116726. */
  116727. struct NodeWriter {
  116728. sqlite3_int64 iBlock; /* Current block id */
  116729. Blob key; /* Last key written to the current block */
  116730. Blob block; /* Current block image */
  116731. };
  116732. /*
  116733. ** An object of this type contains the state required to create or append
  116734. ** to an appendable b-tree segment.
  116735. */
  116736. struct IncrmergeWriter {
  116737. int nLeafEst; /* Space allocated for leaf blocks */
  116738. int nWork; /* Number of leaf pages flushed */
  116739. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  116740. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  116741. sqlite3_int64 iStart; /* Block number of first allocated block */
  116742. sqlite3_int64 iEnd; /* Block number of last allocated block */
  116743. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  116744. };
  116745. /*
  116746. ** An object of the following type is used to read data from a single
  116747. ** FTS segment node. See the following functions:
  116748. **
  116749. ** nodeReaderInit()
  116750. ** nodeReaderNext()
  116751. ** nodeReaderRelease()
  116752. */
  116753. struct NodeReader {
  116754. const char *aNode;
  116755. int nNode;
  116756. int iOff; /* Current offset within aNode[] */
  116757. /* Output variables. Containing the current node entry. */
  116758. sqlite3_int64 iChild; /* Pointer to child node */
  116759. Blob term; /* Current term */
  116760. const char *aDoclist; /* Pointer to doclist */
  116761. int nDoclist; /* Size of doclist in bytes */
  116762. };
  116763. /*
  116764. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  116765. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  116766. ** bytes in size, extend (realloc) it to be so.
  116767. **
  116768. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  116769. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  116770. ** to reflect the new size of the pBlob->a[] buffer.
  116771. */
  116772. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  116773. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  116774. int nAlloc = nMin;
  116775. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  116776. if( a ){
  116777. pBlob->nAlloc = nAlloc;
  116778. pBlob->a = a;
  116779. }else{
  116780. *pRc = SQLITE_NOMEM;
  116781. }
  116782. }
  116783. }
  116784. /*
  116785. ** Attempt to advance the node-reader object passed as the first argument to
  116786. ** the next entry on the node.
  116787. **
  116788. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  116789. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  116790. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  116791. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  116792. ** variables for the new entry.
  116793. */
  116794. static int nodeReaderNext(NodeReader *p){
  116795. int bFirst = (p->term.n==0); /* True for first term on the node */
  116796. int nPrefix = 0; /* Bytes to copy from previous term */
  116797. int nSuffix = 0; /* Bytes to append to the prefix */
  116798. int rc = SQLITE_OK; /* Return code */
  116799. assert( p->aNode );
  116800. if( p->iChild && bFirst==0 ) p->iChild++;
  116801. if( p->iOff>=p->nNode ){
  116802. /* EOF */
  116803. p->aNode = 0;
  116804. }else{
  116805. if( bFirst==0 ){
  116806. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  116807. }
  116808. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  116809. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  116810. if( rc==SQLITE_OK ){
  116811. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  116812. p->term.n = nPrefix+nSuffix;
  116813. p->iOff += nSuffix;
  116814. if( p->iChild==0 ){
  116815. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  116816. p->aDoclist = &p->aNode[p->iOff];
  116817. p->iOff += p->nDoclist;
  116818. }
  116819. }
  116820. }
  116821. assert( p->iOff<=p->nNode );
  116822. return rc;
  116823. }
  116824. /*
  116825. ** Release all dynamic resources held by node-reader object *p.
  116826. */
  116827. static void nodeReaderRelease(NodeReader *p){
  116828. sqlite3_free(p->term.a);
  116829. }
  116830. /*
  116831. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  116832. **
  116833. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  116834. ** point to the first entry on the node (if any). Otherwise, an SQLite
  116835. ** error code is returned.
  116836. */
  116837. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  116838. memset(p, 0, sizeof(NodeReader));
  116839. p->aNode = aNode;
  116840. p->nNode = nNode;
  116841. /* Figure out if this is a leaf or an internal node. */
  116842. if( p->aNode[0] ){
  116843. /* An internal node. */
  116844. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  116845. }else{
  116846. p->iOff = 1;
  116847. }
  116848. return nodeReaderNext(p);
  116849. }
  116850. /*
  116851. ** This function is called while writing an FTS segment each time a leaf o
  116852. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  116853. ** to be greater than the largest key on the node just written, but smaller
  116854. ** than or equal to the first key that will be written to the next leaf
  116855. ** node.
  116856. **
  116857. ** The block id of the leaf node just written to disk may be found in
  116858. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  116859. */
  116860. static int fts3IncrmergePush(
  116861. Fts3Table *p, /* Fts3 table handle */
  116862. IncrmergeWriter *pWriter, /* Writer object */
  116863. const char *zTerm, /* Term to write to internal node */
  116864. int nTerm /* Bytes at zTerm */
  116865. ){
  116866. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  116867. int iLayer;
  116868. assert( nTerm>0 );
  116869. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  116870. sqlite3_int64 iNextPtr = 0;
  116871. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  116872. int rc = SQLITE_OK;
  116873. int nPrefix;
  116874. int nSuffix;
  116875. int nSpace;
  116876. /* Figure out how much space the key will consume if it is written to
  116877. ** the current node of layer iLayer. Due to the prefix compression,
  116878. ** the space required changes depending on which node the key is to
  116879. ** be added to. */
  116880. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  116881. nSuffix = nTerm - nPrefix;
  116882. nSpace = sqlite3Fts3VarintLen(nPrefix);
  116883. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  116884. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  116885. /* If the current node of layer iLayer contains zero keys, or if adding
  116886. ** the key to it will not cause it to grow to larger than nNodeSize
  116887. ** bytes in size, write the key here. */
  116888. Blob *pBlk = &pNode->block;
  116889. if( pBlk->n==0 ){
  116890. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  116891. if( rc==SQLITE_OK ){
  116892. pBlk->a[0] = (char)iLayer;
  116893. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  116894. }
  116895. }
  116896. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  116897. blobGrowBuffer(&pNode->key, nTerm, &rc);
  116898. if( rc==SQLITE_OK ){
  116899. if( pNode->key.n ){
  116900. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  116901. }
  116902. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  116903. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  116904. pBlk->n += nSuffix;
  116905. memcpy(pNode->key.a, zTerm, nTerm);
  116906. pNode->key.n = nTerm;
  116907. }
  116908. }else{
  116909. /* Otherwise, flush the current node of layer iLayer to disk.
  116910. ** Then allocate a new, empty sibling node. The key will be written
  116911. ** into the parent of this node. */
  116912. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  116913. assert( pNode->block.nAlloc>=p->nNodeSize );
  116914. pNode->block.a[0] = (char)iLayer;
  116915. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  116916. iNextPtr = pNode->iBlock;
  116917. pNode->iBlock++;
  116918. pNode->key.n = 0;
  116919. }
  116920. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  116921. iPtr = iNextPtr;
  116922. }
  116923. assert( 0 );
  116924. return 0;
  116925. }
  116926. /*
  116927. ** Append a term and (optionally) doclist to the FTS segment node currently
  116928. ** stored in blob *pNode. The node need not contain any terms, but the
  116929. ** header must be written before this function is called.
  116930. **
  116931. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  116932. ** followed by the left-hand-child varint for an internal node.
  116933. **
  116934. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  116935. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  116936. ** node, both aDoclist and nDoclist must be passed 0.
  116937. **
  116938. ** If the size of the value in blob pPrev is zero, then this is the first
  116939. ** term written to the node. Otherwise, pPrev contains a copy of the
  116940. ** previous term. Before this function returns, it is updated to contain a
  116941. ** copy of zTerm/nTerm.
  116942. **
  116943. ** It is assumed that the buffer associated with pNode is already large
  116944. ** enough to accommodate the new entry. The buffer associated with pPrev
  116945. ** is extended by this function if requrired.
  116946. **
  116947. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  116948. ** returned. Otherwise, SQLITE_OK.
  116949. */
  116950. static int fts3AppendToNode(
  116951. Blob *pNode, /* Current node image to append to */
  116952. Blob *pPrev, /* Buffer containing previous term written */
  116953. const char *zTerm, /* New term to write */
  116954. int nTerm, /* Size of zTerm in bytes */
  116955. const char *aDoclist, /* Doclist (or NULL) to write */
  116956. int nDoclist /* Size of aDoclist in bytes */
  116957. ){
  116958. int rc = SQLITE_OK; /* Return code */
  116959. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  116960. int nPrefix; /* Size of term prefix in bytes */
  116961. int nSuffix; /* Size of term suffix in bytes */
  116962. /* Node must have already been started. There must be a doclist for a
  116963. ** leaf node, and there must not be a doclist for an internal node. */
  116964. assert( pNode->n>0 );
  116965. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  116966. blobGrowBuffer(pPrev, nTerm, &rc);
  116967. if( rc!=SQLITE_OK ) return rc;
  116968. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  116969. nSuffix = nTerm - nPrefix;
  116970. memcpy(pPrev->a, zTerm, nTerm);
  116971. pPrev->n = nTerm;
  116972. if( bFirst==0 ){
  116973. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  116974. }
  116975. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  116976. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  116977. pNode->n += nSuffix;
  116978. if( aDoclist ){
  116979. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  116980. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  116981. pNode->n += nDoclist;
  116982. }
  116983. assert( pNode->n<=pNode->nAlloc );
  116984. return SQLITE_OK;
  116985. }
  116986. /*
  116987. ** Append the current term and doclist pointed to by cursor pCsr to the
  116988. ** appendable b-tree segment opened for writing by pWriter.
  116989. **
  116990. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  116991. */
  116992. static int fts3IncrmergeAppend(
  116993. Fts3Table *p, /* Fts3 table handle */
  116994. IncrmergeWriter *pWriter, /* Writer object */
  116995. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  116996. ){
  116997. const char *zTerm = pCsr->zTerm;
  116998. int nTerm = pCsr->nTerm;
  116999. const char *aDoclist = pCsr->aDoclist;
  117000. int nDoclist = pCsr->nDoclist;
  117001. int rc = SQLITE_OK; /* Return code */
  117002. int nSpace; /* Total space in bytes required on leaf */
  117003. int nPrefix; /* Size of prefix shared with previous term */
  117004. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  117005. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  117006. pLeaf = &pWriter->aNodeWriter[0];
  117007. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  117008. nSuffix = nTerm - nPrefix;
  117009. nSpace = sqlite3Fts3VarintLen(nPrefix);
  117010. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  117011. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  117012. /* If the current block is not empty, and if adding this term/doclist
  117013. ** to the current block would make it larger than Fts3Table.nNodeSize
  117014. ** bytes, write this block out to the database. */
  117015. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  117016. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  117017. pWriter->nWork++;
  117018. /* Add the current term to the parent node. The term added to the
  117019. ** parent must:
  117020. **
  117021. ** a) be greater than the largest term on the leaf node just written
  117022. ** to the database (still available in pLeaf->key), and
  117023. **
  117024. ** b) be less than or equal to the term about to be added to the new
  117025. ** leaf node (zTerm/nTerm).
  117026. **
  117027. ** In other words, it must be the prefix of zTerm 1 byte longer than
  117028. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  117029. */
  117030. if( rc==SQLITE_OK ){
  117031. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  117032. }
  117033. /* Advance to the next output block */
  117034. pLeaf->iBlock++;
  117035. pLeaf->key.n = 0;
  117036. pLeaf->block.n = 0;
  117037. nSuffix = nTerm;
  117038. nSpace = 1;
  117039. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  117040. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  117041. }
  117042. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  117043. if( rc==SQLITE_OK ){
  117044. if( pLeaf->block.n==0 ){
  117045. pLeaf->block.n = 1;
  117046. pLeaf->block.a[0] = '\0';
  117047. }
  117048. rc = fts3AppendToNode(
  117049. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  117050. );
  117051. }
  117052. return rc;
  117053. }
  117054. /*
  117055. ** This function is called to release all dynamic resources held by the
  117056. ** merge-writer object pWriter, and if no error has occurred, to flush
  117057. ** all outstanding node buffers held by pWriter to disk.
  117058. **
  117059. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  117060. ** is made to write any data to disk. Instead, this function serves only
  117061. ** to release outstanding resources.
  117062. **
  117063. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  117064. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  117065. ** returning.
  117066. */
  117067. static void fts3IncrmergeRelease(
  117068. Fts3Table *p, /* FTS3 table handle */
  117069. IncrmergeWriter *pWriter, /* Merge-writer object */
  117070. int *pRc /* IN/OUT: Error code */
  117071. ){
  117072. int i; /* Used to iterate through non-root layers */
  117073. int iRoot; /* Index of root in pWriter->aNodeWriter */
  117074. NodeWriter *pRoot; /* NodeWriter for root node */
  117075. int rc = *pRc; /* Error code */
  117076. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  117077. ** root node. If the segment fits entirely on a single leaf node, iRoot
  117078. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  117079. ** will be 1. And so on. */
  117080. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  117081. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  117082. if( pNode->block.n>0 ) break;
  117083. assert( *pRc || pNode->block.nAlloc==0 );
  117084. assert( *pRc || pNode->key.nAlloc==0 );
  117085. sqlite3_free(pNode->block.a);
  117086. sqlite3_free(pNode->key.a);
  117087. }
  117088. /* Empty output segment. This is a no-op. */
  117089. if( iRoot<0 ) return;
  117090. /* The entire output segment fits on a single node. Normally, this means
  117091. ** the node would be stored as a blob in the "root" column of the %_segdir
  117092. ** table. However, this is not permitted in this case. The problem is that
  117093. ** space has already been reserved in the %_segments table, and so the
  117094. ** start_block and end_block fields of the %_segdir table must be populated.
  117095. ** And, by design or by accident, released versions of FTS cannot handle
  117096. ** segments that fit entirely on the root node with start_block!=0.
  117097. **
  117098. ** Instead, create a synthetic root node that contains nothing but a
  117099. ** pointer to the single content node. So that the segment consists of a
  117100. ** single leaf and a single interior (root) node.
  117101. **
  117102. ** Todo: Better might be to defer allocating space in the %_segments
  117103. ** table until we are sure it is needed.
  117104. */
  117105. if( iRoot==0 ){
  117106. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  117107. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  117108. if( rc==SQLITE_OK ){
  117109. pBlock->a[0] = 0x01;
  117110. pBlock->n = 1 + sqlite3Fts3PutVarint(
  117111. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  117112. );
  117113. }
  117114. iRoot = 1;
  117115. }
  117116. pRoot = &pWriter->aNodeWriter[iRoot];
  117117. /* Flush all currently outstanding nodes to disk. */
  117118. for(i=0; i<iRoot; i++){
  117119. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  117120. if( pNode->block.n>0 && rc==SQLITE_OK ){
  117121. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  117122. }
  117123. sqlite3_free(pNode->block.a);
  117124. sqlite3_free(pNode->key.a);
  117125. }
  117126. /* Write the %_segdir record. */
  117127. if( rc==SQLITE_OK ){
  117128. rc = fts3WriteSegdir(p,
  117129. pWriter->iAbsLevel+1, /* level */
  117130. pWriter->iIdx, /* idx */
  117131. pWriter->iStart, /* start_block */
  117132. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  117133. pWriter->iEnd, /* end_block */
  117134. pRoot->block.a, pRoot->block.n /* root */
  117135. );
  117136. }
  117137. sqlite3_free(pRoot->block.a);
  117138. sqlite3_free(pRoot->key.a);
  117139. *pRc = rc;
  117140. }
  117141. /*
  117142. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  117143. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  117144. ** the other, it is considered to be smaller than the other.
  117145. **
  117146. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  117147. ** if it is greater.
  117148. */
  117149. static int fts3TermCmp(
  117150. const char *zLhs, int nLhs, /* LHS of comparison */
  117151. const char *zRhs, int nRhs /* RHS of comparison */
  117152. ){
  117153. int nCmp = MIN(nLhs, nRhs);
  117154. int res;
  117155. res = memcmp(zLhs, zRhs, nCmp);
  117156. if( res==0 ) res = nLhs - nRhs;
  117157. return res;
  117158. }
  117159. /*
  117160. ** Query to see if the entry in the %_segments table with blockid iEnd is
  117161. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  117162. ** returning. Otherwise, set *pbRes to 0.
  117163. **
  117164. ** Or, if an error occurs while querying the database, return an SQLite
  117165. ** error code. The final value of *pbRes is undefined in this case.
  117166. **
  117167. ** This is used to test if a segment is an "appendable" segment. If it
  117168. ** is, then a NULL entry has been inserted into the %_segments table
  117169. ** with blockid %_segdir.end_block.
  117170. */
  117171. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  117172. int bRes = 0; /* Result to set *pbRes to */
  117173. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  117174. int rc; /* Return code */
  117175. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  117176. if( rc==SQLITE_OK ){
  117177. sqlite3_bind_int64(pCheck, 1, iEnd);
  117178. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  117179. rc = sqlite3_reset(pCheck);
  117180. }
  117181. *pbRes = bRes;
  117182. return rc;
  117183. }
  117184. /*
  117185. ** This function is called when initializing an incremental-merge operation.
  117186. ** It checks if the existing segment with index value iIdx at absolute level
  117187. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  117188. ** merge-writer object *pWriter is initialized to write to it.
  117189. **
  117190. ** An existing segment can be appended to by an incremental merge if:
  117191. **
  117192. ** * It was initially created as an appendable segment (with all required
  117193. ** space pre-allocated), and
  117194. **
  117195. ** * The first key read from the input (arguments zKey and nKey) is
  117196. ** greater than the largest key currently stored in the potential
  117197. ** output segment.
  117198. */
  117199. static int fts3IncrmergeLoad(
  117200. Fts3Table *p, /* Fts3 table handle */
  117201. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  117202. int iIdx, /* Index of candidate output segment */
  117203. const char *zKey, /* First key to write */
  117204. int nKey, /* Number of bytes in nKey */
  117205. IncrmergeWriter *pWriter /* Populate this object */
  117206. ){
  117207. int rc; /* Return code */
  117208. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  117209. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  117210. if( rc==SQLITE_OK ){
  117211. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  117212. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  117213. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  117214. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  117215. int nRoot = 0; /* Size of aRoot[] in bytes */
  117216. int rc2; /* Return code from sqlite3_reset() */
  117217. int bAppendable = 0; /* Set to true if segment is appendable */
  117218. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  117219. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  117220. sqlite3_bind_int(pSelect, 2, iIdx);
  117221. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  117222. iStart = sqlite3_column_int64(pSelect, 1);
  117223. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  117224. iEnd = sqlite3_column_int64(pSelect, 3);
  117225. nRoot = sqlite3_column_bytes(pSelect, 4);
  117226. aRoot = sqlite3_column_blob(pSelect, 4);
  117227. }else{
  117228. return sqlite3_reset(pSelect);
  117229. }
  117230. /* Check for the zero-length marker in the %_segments table */
  117231. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  117232. /* Check that zKey/nKey is larger than the largest key the candidate */
  117233. if( rc==SQLITE_OK && bAppendable ){
  117234. char *aLeaf = 0;
  117235. int nLeaf = 0;
  117236. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  117237. if( rc==SQLITE_OK ){
  117238. NodeReader reader;
  117239. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  117240. rc==SQLITE_OK && reader.aNode;
  117241. rc = nodeReaderNext(&reader)
  117242. ){
  117243. assert( reader.aNode );
  117244. }
  117245. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  117246. bAppendable = 0;
  117247. }
  117248. nodeReaderRelease(&reader);
  117249. }
  117250. sqlite3_free(aLeaf);
  117251. }
  117252. if( rc==SQLITE_OK && bAppendable ){
  117253. /* It is possible to append to this segment. Set up the IncrmergeWriter
  117254. ** object to do so. */
  117255. int i;
  117256. int nHeight = (int)aRoot[0];
  117257. NodeWriter *pNode;
  117258. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  117259. pWriter->iStart = iStart;
  117260. pWriter->iEnd = iEnd;
  117261. pWriter->iAbsLevel = iAbsLevel;
  117262. pWriter->iIdx = iIdx;
  117263. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  117264. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  117265. }
  117266. pNode = &pWriter->aNodeWriter[nHeight];
  117267. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  117268. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  117269. if( rc==SQLITE_OK ){
  117270. memcpy(pNode->block.a, aRoot, nRoot);
  117271. pNode->block.n = nRoot;
  117272. }
  117273. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  117274. NodeReader reader;
  117275. pNode = &pWriter->aNodeWriter[i];
  117276. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  117277. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  117278. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  117279. if( rc==SQLITE_OK ){
  117280. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  117281. pNode->key.n = reader.term.n;
  117282. if( i>0 ){
  117283. char *aBlock = 0;
  117284. int nBlock = 0;
  117285. pNode = &pWriter->aNodeWriter[i-1];
  117286. pNode->iBlock = reader.iChild;
  117287. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  117288. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  117289. if( rc==SQLITE_OK ){
  117290. memcpy(pNode->block.a, aBlock, nBlock);
  117291. pNode->block.n = nBlock;
  117292. }
  117293. sqlite3_free(aBlock);
  117294. }
  117295. }
  117296. nodeReaderRelease(&reader);
  117297. }
  117298. }
  117299. rc2 = sqlite3_reset(pSelect);
  117300. if( rc==SQLITE_OK ) rc = rc2;
  117301. }
  117302. return rc;
  117303. }
  117304. /*
  117305. ** Determine the largest segment index value that exists within absolute
  117306. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  117307. ** one before returning SQLITE_OK. Or, if there are no segments at all
  117308. ** within level iAbsLevel, set *piIdx to zero.
  117309. **
  117310. ** If an error occurs, return an SQLite error code. The final value of
  117311. ** *piIdx is undefined in this case.
  117312. */
  117313. static int fts3IncrmergeOutputIdx(
  117314. Fts3Table *p, /* FTS Table handle */
  117315. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  117316. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  117317. ){
  117318. int rc;
  117319. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  117320. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  117321. if( rc==SQLITE_OK ){
  117322. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  117323. sqlite3_step(pOutputIdx);
  117324. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  117325. rc = sqlite3_reset(pOutputIdx);
  117326. }
  117327. return rc;
  117328. }
  117329. /*
  117330. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  117331. ** with idx value iIdx.
  117332. **
  117333. ** In the %_segdir table, a segment is defined by the values in three
  117334. ** columns:
  117335. **
  117336. ** start_block
  117337. ** leaves_end_block
  117338. ** end_block
  117339. **
  117340. ** When an appendable segment is allocated, it is estimated that the
  117341. ** maximum number of leaf blocks that may be required is the sum of the
  117342. ** number of leaf blocks consumed by the input segments, plus the number
  117343. ** of input segments, multiplied by two. This value is stored in stack
  117344. ** variable nLeafEst.
  117345. **
  117346. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  117347. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  117348. ** array of leaf nodes starts at the first block allocated. The array
  117349. ** of interior nodes that are parents of the leaf nodes start at block
  117350. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  117351. **
  117352. ** In the actual code below, the value "16" is replaced with the
  117353. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  117354. */
  117355. static int fts3IncrmergeWriter(
  117356. Fts3Table *p, /* Fts3 table handle */
  117357. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  117358. int iIdx, /* Index of new output segment */
  117359. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  117360. IncrmergeWriter *pWriter /* Populate this object */
  117361. ){
  117362. int rc; /* Return Code */
  117363. int i; /* Iterator variable */
  117364. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  117365. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  117366. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  117367. /* Calculate nLeafEst. */
  117368. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  117369. if( rc==SQLITE_OK ){
  117370. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  117371. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  117372. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  117373. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  117374. }
  117375. rc = sqlite3_reset(pLeafEst);
  117376. }
  117377. if( rc!=SQLITE_OK ) return rc;
  117378. /* Calculate the first block to use in the output segment */
  117379. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  117380. if( rc==SQLITE_OK ){
  117381. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  117382. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  117383. pWriter->iEnd = pWriter->iStart - 1;
  117384. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  117385. }
  117386. rc = sqlite3_reset(pFirstBlock);
  117387. }
  117388. if( rc!=SQLITE_OK ) return rc;
  117389. /* Insert the marker in the %_segments table to make sure nobody tries
  117390. ** to steal the space just allocated. This is also used to identify
  117391. ** appendable segments. */
  117392. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  117393. if( rc!=SQLITE_OK ) return rc;
  117394. pWriter->iAbsLevel = iAbsLevel;
  117395. pWriter->nLeafEst = nLeafEst;
  117396. pWriter->iIdx = iIdx;
  117397. /* Set up the array of NodeWriter objects */
  117398. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  117399. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  117400. }
  117401. return SQLITE_OK;
  117402. }
  117403. /*
  117404. ** Remove an entry from the %_segdir table. This involves running the
  117405. ** following two statements:
  117406. **
  117407. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  117408. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  117409. **
  117410. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  117411. ** statement ensures that the remaining segments have contiguously allocated
  117412. ** idx values.
  117413. */
  117414. static int fts3RemoveSegdirEntry(
  117415. Fts3Table *p, /* FTS3 table handle */
  117416. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  117417. int iIdx /* Index of %_segdir entry to delete */
  117418. ){
  117419. int rc; /* Return code */
  117420. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  117421. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  117422. if( rc==SQLITE_OK ){
  117423. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  117424. sqlite3_bind_int(pDelete, 2, iIdx);
  117425. sqlite3_step(pDelete);
  117426. rc = sqlite3_reset(pDelete);
  117427. }
  117428. return rc;
  117429. }
  117430. /*
  117431. ** One or more segments have just been removed from absolute level iAbsLevel.
  117432. ** Update the 'idx' values of the remaining segments in the level so that
  117433. ** the idx values are a contiguous sequence starting from 0.
  117434. */
  117435. static int fts3RepackSegdirLevel(
  117436. Fts3Table *p, /* FTS3 table handle */
  117437. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  117438. ){
  117439. int rc; /* Return code */
  117440. int *aIdx = 0; /* Array of remaining idx values */
  117441. int nIdx = 0; /* Valid entries in aIdx[] */
  117442. int nAlloc = 0; /* Allocated size of aIdx[] */
  117443. int i; /* Iterator variable */
  117444. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  117445. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  117446. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  117447. if( rc==SQLITE_OK ){
  117448. int rc2;
  117449. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  117450. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  117451. if( nIdx>=nAlloc ){
  117452. int *aNew;
  117453. nAlloc += 16;
  117454. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  117455. if( !aNew ){
  117456. rc = SQLITE_NOMEM;
  117457. break;
  117458. }
  117459. aIdx = aNew;
  117460. }
  117461. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  117462. }
  117463. rc2 = sqlite3_reset(pSelect);
  117464. if( rc==SQLITE_OK ) rc = rc2;
  117465. }
  117466. if( rc==SQLITE_OK ){
  117467. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  117468. }
  117469. if( rc==SQLITE_OK ){
  117470. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  117471. }
  117472. assert( p->bIgnoreSavepoint==0 );
  117473. p->bIgnoreSavepoint = 1;
  117474. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  117475. if( aIdx[i]!=i ){
  117476. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  117477. sqlite3_bind_int(pUpdate, 1, i);
  117478. sqlite3_step(pUpdate);
  117479. rc = sqlite3_reset(pUpdate);
  117480. }
  117481. }
  117482. p->bIgnoreSavepoint = 0;
  117483. sqlite3_free(aIdx);
  117484. return rc;
  117485. }
  117486. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  117487. pNode->a[0] = (char)iHeight;
  117488. if( iChild ){
  117489. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  117490. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  117491. }else{
  117492. assert( pNode->nAlloc>=1 );
  117493. pNode->n = 1;
  117494. }
  117495. }
  117496. /*
  117497. ** The first two arguments are a pointer to and the size of a segment b-tree
  117498. ** node. The node may be a leaf or an internal node.
  117499. **
  117500. ** This function creates a new node image in blob object *pNew by copying
  117501. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  117502. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  117503. */
  117504. static int fts3TruncateNode(
  117505. const char *aNode, /* Current node image */
  117506. int nNode, /* Size of aNode in bytes */
  117507. Blob *pNew, /* OUT: Write new node image here */
  117508. const char *zTerm, /* Omit all terms smaller than this */
  117509. int nTerm, /* Size of zTerm in bytes */
  117510. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  117511. ){
  117512. NodeReader reader; /* Reader object */
  117513. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  117514. int rc = SQLITE_OK; /* Return code */
  117515. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  117516. /* Allocate required output space */
  117517. blobGrowBuffer(pNew, nNode, &rc);
  117518. if( rc!=SQLITE_OK ) return rc;
  117519. pNew->n = 0;
  117520. /* Populate new node buffer */
  117521. for(rc = nodeReaderInit(&reader, aNode, nNode);
  117522. rc==SQLITE_OK && reader.aNode;
  117523. rc = nodeReaderNext(&reader)
  117524. ){
  117525. if( pNew->n==0 ){
  117526. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  117527. if( res<0 || (bLeaf==0 && res==0) ) continue;
  117528. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  117529. *piBlock = reader.iChild;
  117530. }
  117531. rc = fts3AppendToNode(
  117532. pNew, &prev, reader.term.a, reader.term.n,
  117533. reader.aDoclist, reader.nDoclist
  117534. );
  117535. if( rc!=SQLITE_OK ) break;
  117536. }
  117537. if( pNew->n==0 ){
  117538. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  117539. *piBlock = reader.iChild;
  117540. }
  117541. assert( pNew->n<=pNew->nAlloc );
  117542. nodeReaderRelease(&reader);
  117543. sqlite3_free(prev.a);
  117544. return rc;
  117545. }
  117546. /*
  117547. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  117548. ** level iAbsLevel. This may involve deleting entries from the %_segments
  117549. ** table, and modifying existing entries in both the %_segments and %_segdir
  117550. ** tables.
  117551. **
  117552. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  117553. ** SQLite error code otherwise.
  117554. */
  117555. static int fts3TruncateSegment(
  117556. Fts3Table *p, /* FTS3 table handle */
  117557. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  117558. int iIdx, /* Index within level of segment to modify */
  117559. const char *zTerm, /* Remove terms smaller than this */
  117560. int nTerm /* Number of bytes in buffer zTerm */
  117561. ){
  117562. int rc = SQLITE_OK; /* Return code */
  117563. Blob root = {0,0,0}; /* New root page image */
  117564. Blob block = {0,0,0}; /* Buffer used for any other block */
  117565. sqlite3_int64 iBlock = 0; /* Block id */
  117566. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  117567. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  117568. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  117569. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  117570. if( rc==SQLITE_OK ){
  117571. int rc2; /* sqlite3_reset() return code */
  117572. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  117573. sqlite3_bind_int(pFetch, 2, iIdx);
  117574. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  117575. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  117576. int nRoot = sqlite3_column_bytes(pFetch, 4);
  117577. iOldStart = sqlite3_column_int64(pFetch, 1);
  117578. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  117579. }
  117580. rc2 = sqlite3_reset(pFetch);
  117581. if( rc==SQLITE_OK ) rc = rc2;
  117582. }
  117583. while( rc==SQLITE_OK && iBlock ){
  117584. char *aBlock = 0;
  117585. int nBlock = 0;
  117586. iNewStart = iBlock;
  117587. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  117588. if( rc==SQLITE_OK ){
  117589. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  117590. }
  117591. if( rc==SQLITE_OK ){
  117592. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  117593. }
  117594. sqlite3_free(aBlock);
  117595. }
  117596. /* Variable iNewStart now contains the first valid leaf node. */
  117597. if( rc==SQLITE_OK && iNewStart ){
  117598. sqlite3_stmt *pDel = 0;
  117599. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  117600. if( rc==SQLITE_OK ){
  117601. sqlite3_bind_int64(pDel, 1, iOldStart);
  117602. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  117603. sqlite3_step(pDel);
  117604. rc = sqlite3_reset(pDel);
  117605. }
  117606. }
  117607. if( rc==SQLITE_OK ){
  117608. sqlite3_stmt *pChomp = 0;
  117609. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  117610. if( rc==SQLITE_OK ){
  117611. sqlite3_bind_int64(pChomp, 1, iNewStart);
  117612. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  117613. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  117614. sqlite3_bind_int(pChomp, 4, iIdx);
  117615. sqlite3_step(pChomp);
  117616. rc = sqlite3_reset(pChomp);
  117617. }
  117618. }
  117619. sqlite3_free(root.a);
  117620. sqlite3_free(block.a);
  117621. return rc;
  117622. }
  117623. /*
  117624. ** This function is called after an incrmental-merge operation has run to
  117625. ** merge (or partially merge) two or more segments from absolute level
  117626. ** iAbsLevel.
  117627. **
  117628. ** Each input segment is either removed from the db completely (if all of
  117629. ** its data was copied to the output segment by the incrmerge operation)
  117630. ** or modified in place so that it no longer contains those entries that
  117631. ** have been duplicated in the output segment.
  117632. */
  117633. static int fts3IncrmergeChomp(
  117634. Fts3Table *p, /* FTS table handle */
  117635. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  117636. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  117637. int *pnRem /* Number of segments not deleted */
  117638. ){
  117639. int i;
  117640. int nRem = 0;
  117641. int rc = SQLITE_OK;
  117642. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  117643. Fts3SegReader *pSeg = 0;
  117644. int j;
  117645. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  117646. ** somewhere in the pCsr->apSegment[] array. */
  117647. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  117648. pSeg = pCsr->apSegment[j];
  117649. if( pSeg->iIdx==i ) break;
  117650. }
  117651. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  117652. if( pSeg->aNode==0 ){
  117653. /* Seg-reader is at EOF. Remove the entire input segment. */
  117654. rc = fts3DeleteSegment(p, pSeg);
  117655. if( rc==SQLITE_OK ){
  117656. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  117657. }
  117658. *pnRem = 0;
  117659. }else{
  117660. /* The incremental merge did not copy all the data from this
  117661. ** segment to the upper level. The segment is modified in place
  117662. ** so that it contains no keys smaller than zTerm/nTerm. */
  117663. const char *zTerm = pSeg->zTerm;
  117664. int nTerm = pSeg->nTerm;
  117665. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  117666. nRem++;
  117667. }
  117668. }
  117669. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  117670. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  117671. }
  117672. *pnRem = nRem;
  117673. return rc;
  117674. }
  117675. /*
  117676. ** Store an incr-merge hint in the database.
  117677. */
  117678. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  117679. sqlite3_stmt *pReplace = 0;
  117680. int rc; /* Return code */
  117681. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  117682. if( rc==SQLITE_OK ){
  117683. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  117684. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  117685. sqlite3_step(pReplace);
  117686. rc = sqlite3_reset(pReplace);
  117687. }
  117688. return rc;
  117689. }
  117690. /*
  117691. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  117692. ** exists, is stored in the rowid==1 row of the %_stat table.
  117693. **
  117694. ** If successful, populate blob *pHint with the value read from the %_stat
  117695. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  117696. ** SQLite error code.
  117697. */
  117698. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  117699. sqlite3_stmt *pSelect = 0;
  117700. int rc;
  117701. pHint->n = 0;
  117702. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  117703. if( rc==SQLITE_OK ){
  117704. int rc2;
  117705. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  117706. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  117707. const char *aHint = sqlite3_column_blob(pSelect, 0);
  117708. int nHint = sqlite3_column_bytes(pSelect, 0);
  117709. if( aHint ){
  117710. blobGrowBuffer(pHint, nHint, &rc);
  117711. if( rc==SQLITE_OK ){
  117712. memcpy(pHint->a, aHint, nHint);
  117713. pHint->n = nHint;
  117714. }
  117715. }
  117716. }
  117717. rc2 = sqlite3_reset(pSelect);
  117718. if( rc==SQLITE_OK ) rc = rc2;
  117719. }
  117720. return rc;
  117721. }
  117722. /*
  117723. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  117724. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  117725. ** consists of two varints, the absolute level number of the input segments
  117726. ** and the number of input segments.
  117727. **
  117728. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  117729. ** set *pRc to an SQLite error code before returning.
  117730. */
  117731. static void fts3IncrmergeHintPush(
  117732. Blob *pHint, /* Hint blob to append to */
  117733. i64 iAbsLevel, /* First varint to store in hint */
  117734. int nInput, /* Second varint to store in hint */
  117735. int *pRc /* IN/OUT: Error code */
  117736. ){
  117737. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  117738. if( *pRc==SQLITE_OK ){
  117739. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  117740. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  117741. }
  117742. }
  117743. /*
  117744. ** Read the last entry (most recently pushed) from the hint blob *pHint
  117745. ** and then remove the entry. Write the two values read to *piAbsLevel and
  117746. ** *pnInput before returning.
  117747. **
  117748. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  117749. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  117750. */
  117751. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  117752. const int nHint = pHint->n;
  117753. int i;
  117754. i = pHint->n-2;
  117755. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  117756. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  117757. pHint->n = i;
  117758. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  117759. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  117760. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  117761. return SQLITE_OK;
  117762. }
  117763. /*
  117764. ** Attempt an incremental merge that writes nMerge leaf blocks.
  117765. **
  117766. ** Incremental merges happen nMin segments at a time. The two
  117767. ** segments to be merged are the nMin oldest segments (the ones with
  117768. ** the smallest indexes) in the highest level that contains at least
  117769. ** nMin segments. Multiple merges might occur in an attempt to write the
  117770. ** quota of nMerge leaf blocks.
  117771. */
  117772. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  117773. int rc; /* Return code */
  117774. int nRem = nMerge; /* Number of leaf pages yet to be written */
  117775. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  117776. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  117777. IncrmergeWriter *pWriter; /* Writer object */
  117778. int nSeg = 0; /* Number of input segments */
  117779. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  117780. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  117781. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  117782. /* Allocate space for the cursor, filter and writer objects */
  117783. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  117784. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  117785. if( !pWriter ) return SQLITE_NOMEM;
  117786. pFilter = (Fts3SegFilter *)&pWriter[1];
  117787. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  117788. rc = fts3IncrmergeHintLoad(p, &hint);
  117789. while( rc==SQLITE_OK && nRem>0 ){
  117790. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  117791. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  117792. int bUseHint = 0; /* True if attempting to append */
  117793. /* Search the %_segdir table for the absolute level with the smallest
  117794. ** relative level number that contains at least nMin segments, if any.
  117795. ** If one is found, set iAbsLevel to the absolute level number and
  117796. ** nSeg to nMin. If no level with at least nMin segments can be found,
  117797. ** set nSeg to -1.
  117798. */
  117799. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  117800. sqlite3_bind_int(pFindLevel, 1, nMin);
  117801. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  117802. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  117803. nSeg = nMin;
  117804. }else{
  117805. nSeg = -1;
  117806. }
  117807. rc = sqlite3_reset(pFindLevel);
  117808. /* If the hint read from the %_stat table is not empty, check if the
  117809. ** last entry in it specifies a relative level smaller than or equal
  117810. ** to the level identified by the block above (if any). If so, this
  117811. ** iteration of the loop will work on merging at the hinted level.
  117812. */
  117813. if( rc==SQLITE_OK && hint.n ){
  117814. int nHint = hint.n;
  117815. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  117816. int nHintSeg = 0; /* Hint number of segments */
  117817. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  117818. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  117819. iAbsLevel = iHintAbsLevel;
  117820. nSeg = nHintSeg;
  117821. bUseHint = 1;
  117822. bDirtyHint = 1;
  117823. }else{
  117824. /* This undoes the effect of the HintPop() above - so that no entry
  117825. ** is removed from the hint blob. */
  117826. hint.n = nHint;
  117827. }
  117828. }
  117829. /* If nSeg is less that zero, then there is no level with at least
  117830. ** nMin segments and no hint in the %_stat table. No work to do.
  117831. ** Exit early in this case. */
  117832. if( nSeg<0 ) break;
  117833. /* Open a cursor to iterate through the contents of the oldest nSeg
  117834. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  117835. ** the 'hint' parameters, it is possible that there are less than nSeg
  117836. ** segments available in level iAbsLevel. In this case, no work is
  117837. ** done on iAbsLevel - fall through to the next iteration of the loop
  117838. ** to start work on some other level. */
  117839. memset(pWriter, 0, nAlloc);
  117840. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  117841. if( rc==SQLITE_OK ){
  117842. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  117843. }
  117844. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  117845. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  117846. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  117847. ){
  117848. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  117849. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  117850. if( rc==SQLITE_OK ){
  117851. if( bUseHint && iIdx>0 ){
  117852. const char *zKey = pCsr->zTerm;
  117853. int nKey = pCsr->nTerm;
  117854. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  117855. }else{
  117856. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  117857. }
  117858. }
  117859. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  117860. fts3LogMerge(nSeg, iAbsLevel);
  117861. do {
  117862. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  117863. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  117864. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  117865. }while( rc==SQLITE_ROW );
  117866. /* Update or delete the input segments */
  117867. if( rc==SQLITE_OK ){
  117868. nRem -= (1 + pWriter->nWork);
  117869. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  117870. if( nSeg!=0 ){
  117871. bDirtyHint = 1;
  117872. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  117873. }
  117874. }
  117875. }
  117876. fts3IncrmergeRelease(p, pWriter, &rc);
  117877. }
  117878. sqlite3Fts3SegReaderFinish(pCsr);
  117879. }
  117880. /* Write the hint values into the %_stat table for the next incr-merger */
  117881. if( bDirtyHint && rc==SQLITE_OK ){
  117882. rc = fts3IncrmergeHintStore(p, &hint);
  117883. }
  117884. sqlite3_free(pWriter);
  117885. sqlite3_free(hint.a);
  117886. return rc;
  117887. }
  117888. /*
  117889. ** Convert the text beginning at *pz into an integer and return
  117890. ** its value. Advance *pz to point to the first character past
  117891. ** the integer.
  117892. */
  117893. static int fts3Getint(const char **pz){
  117894. const char *z = *pz;
  117895. int i = 0;
  117896. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  117897. *pz = z;
  117898. return i;
  117899. }
  117900. /*
  117901. ** Process statements of the form:
  117902. **
  117903. ** INSERT INTO table(table) VALUES('merge=A,B');
  117904. **
  117905. ** A and B are integers that decode to be the number of leaf pages
  117906. ** written for the merge, and the minimum number of segments on a level
  117907. ** before it will be selected for a merge, respectively.
  117908. */
  117909. static int fts3DoIncrmerge(
  117910. Fts3Table *p, /* FTS3 table handle */
  117911. const char *zParam /* Nul-terminated string containing "A,B" */
  117912. ){
  117913. int rc;
  117914. int nMin = (FTS3_MERGE_COUNT / 2);
  117915. int nMerge = 0;
  117916. const char *z = zParam;
  117917. /* Read the first integer value */
  117918. nMerge = fts3Getint(&z);
  117919. /* If the first integer value is followed by a ',', read the second
  117920. ** integer value. */
  117921. if( z[0]==',' && z[1]!='\0' ){
  117922. z++;
  117923. nMin = fts3Getint(&z);
  117924. }
  117925. if( z[0]!='\0' || nMin<2 ){
  117926. rc = SQLITE_ERROR;
  117927. }else{
  117928. rc = SQLITE_OK;
  117929. if( !p->bHasStat ){
  117930. assert( p->bFts4==0 );
  117931. sqlite3Fts3CreateStatTable(&rc, p);
  117932. }
  117933. if( rc==SQLITE_OK ){
  117934. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  117935. }
  117936. sqlite3Fts3SegmentsClose(p);
  117937. }
  117938. return rc;
  117939. }
  117940. /*
  117941. ** Process statements of the form:
  117942. **
  117943. ** INSERT INTO table(table) VALUES('automerge=X');
  117944. **
  117945. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  117946. ** turn it on. The setting is persistent.
  117947. */
  117948. static int fts3DoAutoincrmerge(
  117949. Fts3Table *p, /* FTS3 table handle */
  117950. const char *zParam /* Nul-terminated string containing boolean */
  117951. ){
  117952. int rc = SQLITE_OK;
  117953. sqlite3_stmt *pStmt = 0;
  117954. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  117955. if( !p->bHasStat ){
  117956. assert( p->bFts4==0 );
  117957. sqlite3Fts3CreateStatTable(&rc, p);
  117958. if( rc ) return rc;
  117959. }
  117960. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  117961. if( rc ) return rc;
  117962. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  117963. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  117964. sqlite3_step(pStmt);
  117965. rc = sqlite3_reset(pStmt);
  117966. return rc;
  117967. }
  117968. /*
  117969. ** Return a 64-bit checksum for the FTS index entry specified by the
  117970. ** arguments to this function.
  117971. */
  117972. static u64 fts3ChecksumEntry(
  117973. const char *zTerm, /* Pointer to buffer containing term */
  117974. int nTerm, /* Size of zTerm in bytes */
  117975. int iLangid, /* Language id for current row */
  117976. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  117977. i64 iDocid, /* Docid for current row. */
  117978. int iCol, /* Column number */
  117979. int iPos /* Position */
  117980. ){
  117981. int i;
  117982. u64 ret = (u64)iDocid;
  117983. ret += (ret<<3) + iLangid;
  117984. ret += (ret<<3) + iIndex;
  117985. ret += (ret<<3) + iCol;
  117986. ret += (ret<<3) + iPos;
  117987. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  117988. return ret;
  117989. }
  117990. /*
  117991. ** Return a checksum of all entries in the FTS index that correspond to
  117992. ** language id iLangid. The checksum is calculated by XORing the checksums
  117993. ** of each individual entry (see fts3ChecksumEntry()) together.
  117994. **
  117995. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  117996. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  117997. ** return value is undefined in this case.
  117998. */
  117999. static u64 fts3ChecksumIndex(
  118000. Fts3Table *p, /* FTS3 table handle */
  118001. int iLangid, /* Language id to return cksum for */
  118002. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  118003. int *pRc /* OUT: Return code */
  118004. ){
  118005. Fts3SegFilter filter;
  118006. Fts3MultiSegReader csr;
  118007. int rc;
  118008. u64 cksum = 0;
  118009. assert( *pRc==SQLITE_OK );
  118010. memset(&filter, 0, sizeof(filter));
  118011. memset(&csr, 0, sizeof(csr));
  118012. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  118013. filter.flags |= FTS3_SEGMENT_SCAN;
  118014. rc = sqlite3Fts3SegReaderCursor(
  118015. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  118016. );
  118017. if( rc==SQLITE_OK ){
  118018. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  118019. }
  118020. if( rc==SQLITE_OK ){
  118021. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  118022. char *pCsr = csr.aDoclist;
  118023. char *pEnd = &pCsr[csr.nDoclist];
  118024. i64 iDocid = 0;
  118025. i64 iCol = 0;
  118026. i64 iPos = 0;
  118027. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  118028. while( pCsr<pEnd ){
  118029. i64 iVal = 0;
  118030. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  118031. if( pCsr<pEnd ){
  118032. if( iVal==0 || iVal==1 ){
  118033. iCol = 0;
  118034. iPos = 0;
  118035. if( iVal ){
  118036. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  118037. }else{
  118038. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  118039. iDocid += iVal;
  118040. }
  118041. }else{
  118042. iPos += (iVal - 2);
  118043. cksum = cksum ^ fts3ChecksumEntry(
  118044. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  118045. (int)iCol, (int)iPos
  118046. );
  118047. }
  118048. }
  118049. }
  118050. }
  118051. }
  118052. sqlite3Fts3SegReaderFinish(&csr);
  118053. *pRc = rc;
  118054. return cksum;
  118055. }
  118056. /*
  118057. ** Check if the contents of the FTS index match the current contents of the
  118058. ** content table. If no error occurs and the contents do match, set *pbOk
  118059. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  118060. ** to false before returning.
  118061. **
  118062. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  118063. ** code. The final value of *pbOk is undefined in this case.
  118064. */
  118065. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  118066. int rc = SQLITE_OK; /* Return code */
  118067. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  118068. u64 cksum2 = 0; /* Checksum based on %_content contents */
  118069. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  118070. /* This block calculates the checksum according to the FTS index. */
  118071. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  118072. if( rc==SQLITE_OK ){
  118073. int rc2;
  118074. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  118075. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  118076. int iLangid = sqlite3_column_int(pAllLangid, 0);
  118077. int i;
  118078. for(i=0; i<p->nIndex; i++){
  118079. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  118080. }
  118081. }
  118082. rc2 = sqlite3_reset(pAllLangid);
  118083. if( rc==SQLITE_OK ) rc = rc2;
  118084. }
  118085. /* This block calculates the checksum according to the %_content table */
  118086. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  118087. if( rc==SQLITE_OK ){
  118088. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  118089. sqlite3_stmt *pStmt = 0;
  118090. char *zSql;
  118091. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  118092. if( !zSql ){
  118093. rc = SQLITE_NOMEM;
  118094. }else{
  118095. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  118096. sqlite3_free(zSql);
  118097. }
  118098. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  118099. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  118100. int iLang = langidFromSelect(p, pStmt);
  118101. int iCol;
  118102. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  118103. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  118104. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  118105. sqlite3_tokenizer_cursor *pT = 0;
  118106. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  118107. while( rc==SQLITE_OK ){
  118108. char const *zToken; /* Buffer containing token */
  118109. int nToken = 0; /* Number of bytes in token */
  118110. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  118111. int iPos = 0; /* Position of token in zText */
  118112. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  118113. if( rc==SQLITE_OK ){
  118114. int i;
  118115. cksum2 = cksum2 ^ fts3ChecksumEntry(
  118116. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  118117. );
  118118. for(i=1; i<p->nIndex; i++){
  118119. if( p->aIndex[i].nPrefix<=nToken ){
  118120. cksum2 = cksum2 ^ fts3ChecksumEntry(
  118121. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  118122. );
  118123. }
  118124. }
  118125. }
  118126. }
  118127. if( pT ) pModule->xClose(pT);
  118128. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  118129. }
  118130. }
  118131. sqlite3_finalize(pStmt);
  118132. }
  118133. *pbOk = (cksum1==cksum2);
  118134. return rc;
  118135. }
  118136. /*
  118137. ** Run the integrity-check. If no error occurs and the current contents of
  118138. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  118139. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  118140. **
  118141. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  118142. ** error code.
  118143. **
  118144. ** The integrity-check works as follows. For each token and indexed token
  118145. ** prefix in the document set, a 64-bit checksum is calculated (by code
  118146. ** in fts3ChecksumEntry()) based on the following:
  118147. **
  118148. ** + The index number (0 for the main index, 1 for the first prefix
  118149. ** index etc.),
  118150. ** + The token (or token prefix) text itself,
  118151. ** + The language-id of the row it appears in,
  118152. ** + The docid of the row it appears in,
  118153. ** + The column it appears in, and
  118154. ** + The tokens position within that column.
  118155. **
  118156. ** The checksums for all entries in the index are XORed together to create
  118157. ** a single checksum for the entire index.
  118158. **
  118159. ** The integrity-check code calculates the same checksum in two ways:
  118160. **
  118161. ** 1. By scanning the contents of the FTS index, and
  118162. ** 2. By scanning and tokenizing the content table.
  118163. **
  118164. ** If the two checksums are identical, the integrity-check is deemed to have
  118165. ** passed.
  118166. */
  118167. static int fts3DoIntegrityCheck(
  118168. Fts3Table *p /* FTS3 table handle */
  118169. ){
  118170. int rc;
  118171. int bOk = 0;
  118172. rc = fts3IntegrityCheck(p, &bOk);
  118173. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  118174. return rc;
  118175. }
  118176. /*
  118177. ** Handle a 'special' INSERT of the form:
  118178. **
  118179. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  118180. **
  118181. ** Argument pVal contains the result of <expr>. Currently the only
  118182. ** meaningful value to insert is the text 'optimize'.
  118183. */
  118184. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  118185. int rc; /* Return Code */
  118186. const char *zVal = (const char *)sqlite3_value_text(pVal);
  118187. int nVal = sqlite3_value_bytes(pVal);
  118188. if( !zVal ){
  118189. return SQLITE_NOMEM;
  118190. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  118191. rc = fts3DoOptimize(p, 0);
  118192. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  118193. rc = fts3DoRebuild(p);
  118194. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  118195. rc = fts3DoIntegrityCheck(p);
  118196. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  118197. rc = fts3DoIncrmerge(p, &zVal[6]);
  118198. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  118199. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  118200. #ifdef SQLITE_TEST
  118201. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  118202. p->nNodeSize = atoi(&zVal[9]);
  118203. rc = SQLITE_OK;
  118204. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  118205. p->nMaxPendingData = atoi(&zVal[11]);
  118206. rc = SQLITE_OK;
  118207. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  118208. p->bNoIncrDoclist = atoi(&zVal[21]);
  118209. rc = SQLITE_OK;
  118210. #endif
  118211. }else{
  118212. rc = SQLITE_ERROR;
  118213. }
  118214. return rc;
  118215. }
  118216. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  118217. /*
  118218. ** Delete all cached deferred doclists. Deferred doclists are cached
  118219. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  118220. */
  118221. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  118222. Fts3DeferredToken *pDef;
  118223. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  118224. fts3PendingListDelete(pDef->pList);
  118225. pDef->pList = 0;
  118226. }
  118227. }
  118228. /*
  118229. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  118230. ** this list using sqlite3Fts3DeferToken().
  118231. */
  118232. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  118233. Fts3DeferredToken *pDef;
  118234. Fts3DeferredToken *pNext;
  118235. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  118236. pNext = pDef->pNext;
  118237. fts3PendingListDelete(pDef->pList);
  118238. sqlite3_free(pDef);
  118239. }
  118240. pCsr->pDeferred = 0;
  118241. }
  118242. /*
  118243. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  118244. ** based on the row that pCsr currently points to.
  118245. **
  118246. ** A deferred-doclist is like any other doclist with position information
  118247. ** included, except that it only contains entries for a single row of the
  118248. ** table, not for all rows.
  118249. */
  118250. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  118251. int rc = SQLITE_OK; /* Return code */
  118252. if( pCsr->pDeferred ){
  118253. int i; /* Used to iterate through table columns */
  118254. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  118255. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  118256. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  118257. sqlite3_tokenizer *pT = p->pTokenizer;
  118258. sqlite3_tokenizer_module const *pModule = pT->pModule;
  118259. assert( pCsr->isRequireSeek==0 );
  118260. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  118261. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  118262. if( p->abNotindexed[i]==0 ){
  118263. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  118264. sqlite3_tokenizer_cursor *pTC = 0;
  118265. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  118266. while( rc==SQLITE_OK ){
  118267. char const *zToken; /* Buffer containing token */
  118268. int nToken = 0; /* Number of bytes in token */
  118269. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  118270. int iPos = 0; /* Position of token in zText */
  118271. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  118272. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  118273. Fts3PhraseToken *pPT = pDef->pToken;
  118274. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  118275. && (pPT->bFirst==0 || iPos==0)
  118276. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  118277. && (0==memcmp(zToken, pPT->z, pPT->n))
  118278. ){
  118279. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  118280. }
  118281. }
  118282. }
  118283. if( pTC ) pModule->xClose(pTC);
  118284. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  118285. }
  118286. }
  118287. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  118288. if( pDef->pList ){
  118289. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  118290. }
  118291. }
  118292. }
  118293. return rc;
  118294. }
  118295. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  118296. Fts3DeferredToken *p,
  118297. char **ppData,
  118298. int *pnData
  118299. ){
  118300. char *pRet;
  118301. int nSkip;
  118302. sqlite3_int64 dummy;
  118303. *ppData = 0;
  118304. *pnData = 0;
  118305. if( p->pList==0 ){
  118306. return SQLITE_OK;
  118307. }
  118308. pRet = (char *)sqlite3_malloc(p->pList->nData);
  118309. if( !pRet ) return SQLITE_NOMEM;
  118310. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  118311. *pnData = p->pList->nData - nSkip;
  118312. *ppData = pRet;
  118313. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  118314. return SQLITE_OK;
  118315. }
  118316. /*
  118317. ** Add an entry for token pToken to the pCsr->pDeferred list.
  118318. */
  118319. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  118320. Fts3Cursor *pCsr, /* Fts3 table cursor */
  118321. Fts3PhraseToken *pToken, /* Token to defer */
  118322. int iCol /* Column that token must appear in (or -1) */
  118323. ){
  118324. Fts3DeferredToken *pDeferred;
  118325. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  118326. if( !pDeferred ){
  118327. return SQLITE_NOMEM;
  118328. }
  118329. memset(pDeferred, 0, sizeof(*pDeferred));
  118330. pDeferred->pToken = pToken;
  118331. pDeferred->pNext = pCsr->pDeferred;
  118332. pDeferred->iCol = iCol;
  118333. pCsr->pDeferred = pDeferred;
  118334. assert( pToken->pDeferred==0 );
  118335. pToken->pDeferred = pDeferred;
  118336. return SQLITE_OK;
  118337. }
  118338. #endif
  118339. /*
  118340. ** SQLite value pRowid contains the rowid of a row that may or may not be
  118341. ** present in the FTS3 table. If it is, delete it and adjust the contents
  118342. ** of subsiduary data structures accordingly.
  118343. */
  118344. static int fts3DeleteByRowid(
  118345. Fts3Table *p,
  118346. sqlite3_value *pRowid,
  118347. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  118348. u32 *aSzDel
  118349. ){
  118350. int rc = SQLITE_OK; /* Return code */
  118351. int bFound = 0; /* True if *pRowid really is in the table */
  118352. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  118353. if( bFound && rc==SQLITE_OK ){
  118354. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  118355. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  118356. if( rc==SQLITE_OK ){
  118357. if( isEmpty ){
  118358. /* Deleting this row means the whole table is empty. In this case
  118359. ** delete the contents of all three tables and throw away any
  118360. ** data in the pendingTerms hash table. */
  118361. rc = fts3DeleteAll(p, 1);
  118362. *pnChng = 0;
  118363. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  118364. }else{
  118365. *pnChng = *pnChng - 1;
  118366. if( p->zContentTbl==0 ){
  118367. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  118368. }
  118369. if( p->bHasDocsize ){
  118370. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  118371. }
  118372. }
  118373. }
  118374. }
  118375. return rc;
  118376. }
  118377. /*
  118378. ** This function does the work for the xUpdate method of FTS3 virtual
  118379. ** tables. The schema of the virtual table being:
  118380. **
  118381. ** CREATE TABLE <table name>(
  118382. ** <user columns>,
  118383. ** <table name> HIDDEN,
  118384. ** docid HIDDEN,
  118385. ** <langid> HIDDEN
  118386. ** );
  118387. **
  118388. **
  118389. */
  118390. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  118391. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  118392. int nArg, /* Size of argument array */
  118393. sqlite3_value **apVal, /* Array of arguments */
  118394. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  118395. ){
  118396. Fts3Table *p = (Fts3Table *)pVtab;
  118397. int rc = SQLITE_OK; /* Return Code */
  118398. int isRemove = 0; /* True for an UPDATE or DELETE */
  118399. u32 *aSzIns = 0; /* Sizes of inserted documents */
  118400. u32 *aSzDel = 0; /* Sizes of deleted documents */
  118401. int nChng = 0; /* Net change in number of documents */
  118402. int bInsertDone = 0;
  118403. assert( p->pSegments==0 );
  118404. assert(
  118405. nArg==1 /* DELETE operations */
  118406. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  118407. );
  118408. /* Check for a "special" INSERT operation. One of the form:
  118409. **
  118410. ** INSERT INTO xyz(xyz) VALUES('command');
  118411. */
  118412. if( nArg>1
  118413. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  118414. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  118415. ){
  118416. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  118417. goto update_out;
  118418. }
  118419. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  118420. rc = SQLITE_CONSTRAINT;
  118421. goto update_out;
  118422. }
  118423. /* Allocate space to hold the change in document sizes */
  118424. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  118425. if( aSzDel==0 ){
  118426. rc = SQLITE_NOMEM;
  118427. goto update_out;
  118428. }
  118429. aSzIns = &aSzDel[p->nColumn+1];
  118430. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  118431. rc = fts3Writelock(p);
  118432. if( rc!=SQLITE_OK ) goto update_out;
  118433. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  118434. ** value, then this operation requires constraint handling.
  118435. **
  118436. ** If the on-conflict mode is REPLACE, this means that the existing row
  118437. ** should be deleted from the database before inserting the new row. Or,
  118438. ** if the on-conflict mode is other than REPLACE, then this method must
  118439. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  118440. ** modify the database file.
  118441. */
  118442. if( nArg>1 && p->zContentTbl==0 ){
  118443. /* Find the value object that holds the new rowid value. */
  118444. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  118445. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  118446. pNewRowid = apVal[1];
  118447. }
  118448. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  118449. sqlite3_value_type(apVal[0])==SQLITE_NULL
  118450. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  118451. )){
  118452. /* The new rowid is not NULL (in this case the rowid will be
  118453. ** automatically assigned and there is no chance of a conflict), and
  118454. ** the statement is either an INSERT or an UPDATE that modifies the
  118455. ** rowid column. So if the conflict mode is REPLACE, then delete any
  118456. ** existing row with rowid=pNewRowid.
  118457. **
  118458. ** Or, if the conflict mode is not REPLACE, insert the new record into
  118459. ** the %_content table. If we hit the duplicate rowid constraint (or any
  118460. ** other error) while doing so, return immediately.
  118461. **
  118462. ** This branch may also run if pNewRowid contains a value that cannot
  118463. ** be losslessly converted to an integer. In this case, the eventual
  118464. ** call to fts3InsertData() (either just below or further on in this
  118465. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  118466. ** invoked, it will delete zero rows (since no row will have
  118467. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  118468. */
  118469. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  118470. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  118471. }else{
  118472. rc = fts3InsertData(p, apVal, pRowid);
  118473. bInsertDone = 1;
  118474. }
  118475. }
  118476. }
  118477. if( rc!=SQLITE_OK ){
  118478. goto update_out;
  118479. }
  118480. /* If this is a DELETE or UPDATE operation, remove the old record. */
  118481. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  118482. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  118483. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  118484. isRemove = 1;
  118485. }
  118486. /* If this is an INSERT or UPDATE operation, insert the new record. */
  118487. if( nArg>1 && rc==SQLITE_OK ){
  118488. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  118489. if( bInsertDone==0 ){
  118490. rc = fts3InsertData(p, apVal, pRowid);
  118491. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  118492. rc = FTS_CORRUPT_VTAB;
  118493. }
  118494. }
  118495. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  118496. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  118497. }
  118498. if( rc==SQLITE_OK ){
  118499. assert( p->iPrevDocid==*pRowid );
  118500. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  118501. }
  118502. if( p->bHasDocsize ){
  118503. fts3InsertDocsize(&rc, p, aSzIns);
  118504. }
  118505. nChng++;
  118506. }
  118507. if( p->bFts4 ){
  118508. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  118509. }
  118510. update_out:
  118511. sqlite3_free(aSzDel);
  118512. sqlite3Fts3SegmentsClose(p);
  118513. return rc;
  118514. }
  118515. /*
  118516. ** Flush any data in the pending-terms hash table to disk. If successful,
  118517. ** merge all segments in the database (including the new segment, if
  118518. ** there was any data to flush) into a single segment.
  118519. */
  118520. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  118521. int rc;
  118522. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  118523. if( rc==SQLITE_OK ){
  118524. rc = fts3DoOptimize(p, 1);
  118525. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  118526. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  118527. if( rc2!=SQLITE_OK ) rc = rc2;
  118528. }else{
  118529. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  118530. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  118531. }
  118532. }
  118533. sqlite3Fts3SegmentsClose(p);
  118534. return rc;
  118535. }
  118536. #endif
  118537. /************** End of fts3_write.c ******************************************/
  118538. /************** Begin file fts3_snippet.c ************************************/
  118539. /*
  118540. ** 2009 Oct 23
  118541. **
  118542. ** The author disclaims copyright to this source code. In place of
  118543. ** a legal notice, here is a blessing:
  118544. **
  118545. ** May you do good and not evil.
  118546. ** May you find forgiveness for yourself and forgive others.
  118547. ** May you share freely, never taking more than you give.
  118548. **
  118549. ******************************************************************************
  118550. */
  118551. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  118552. /* #include <string.h> */
  118553. /* #include <assert.h> */
  118554. /*
  118555. ** Characters that may appear in the second argument to matchinfo().
  118556. */
  118557. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  118558. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  118559. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  118560. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  118561. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  118562. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  118563. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  118564. /*
  118565. ** The default value for the second argument to matchinfo().
  118566. */
  118567. #define FTS3_MATCHINFO_DEFAULT "pcx"
  118568. /*
  118569. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  118570. ** Fts3Expr.aDoclist[]/nDoclist.
  118571. */
  118572. typedef struct LoadDoclistCtx LoadDoclistCtx;
  118573. struct LoadDoclistCtx {
  118574. Fts3Cursor *pCsr; /* FTS3 Cursor */
  118575. int nPhrase; /* Number of phrases seen so far */
  118576. int nToken; /* Number of tokens seen so far */
  118577. };
  118578. /*
  118579. ** The following types are used as part of the implementation of the
  118580. ** fts3BestSnippet() routine.
  118581. */
  118582. typedef struct SnippetIter SnippetIter;
  118583. typedef struct SnippetPhrase SnippetPhrase;
  118584. typedef struct SnippetFragment SnippetFragment;
  118585. struct SnippetIter {
  118586. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  118587. int iCol; /* Extract snippet from this column */
  118588. int nSnippet; /* Requested snippet length (in tokens) */
  118589. int nPhrase; /* Number of phrases in query */
  118590. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  118591. int iCurrent; /* First token of current snippet */
  118592. };
  118593. struct SnippetPhrase {
  118594. int nToken; /* Number of tokens in phrase */
  118595. char *pList; /* Pointer to start of phrase position list */
  118596. int iHead; /* Next value in position list */
  118597. char *pHead; /* Position list data following iHead */
  118598. int iTail; /* Next value in trailing position list */
  118599. char *pTail; /* Position list data following iTail */
  118600. };
  118601. struct SnippetFragment {
  118602. int iCol; /* Column snippet is extracted from */
  118603. int iPos; /* Index of first token in snippet */
  118604. u64 covered; /* Mask of query phrases covered */
  118605. u64 hlmask; /* Mask of snippet terms to highlight */
  118606. };
  118607. /*
  118608. ** This type is used as an fts3ExprIterate() context object while
  118609. ** accumulating the data returned by the matchinfo() function.
  118610. */
  118611. typedef struct MatchInfo MatchInfo;
  118612. struct MatchInfo {
  118613. Fts3Cursor *pCursor; /* FTS3 Cursor */
  118614. int nCol; /* Number of columns in table */
  118615. int nPhrase; /* Number of matchable phrases in query */
  118616. sqlite3_int64 nDoc; /* Number of docs in database */
  118617. u32 *aMatchinfo; /* Pre-allocated buffer */
  118618. };
  118619. /*
  118620. ** The snippet() and offsets() functions both return text values. An instance
  118621. ** of the following structure is used to accumulate those values while the
  118622. ** functions are running. See fts3StringAppend() for details.
  118623. */
  118624. typedef struct StrBuffer StrBuffer;
  118625. struct StrBuffer {
  118626. char *z; /* Pointer to buffer containing string */
  118627. int n; /* Length of z in bytes (excl. nul-term) */
  118628. int nAlloc; /* Allocated size of buffer z in bytes */
  118629. };
  118630. /*
  118631. ** This function is used to help iterate through a position-list. A position
  118632. ** list is a list of unique integers, sorted from smallest to largest. Each
  118633. ** element of the list is represented by an FTS3 varint that takes the value
  118634. ** of the difference between the current element and the previous one plus
  118635. ** two. For example, to store the position-list:
  118636. **
  118637. ** 4 9 113
  118638. **
  118639. ** the three varints:
  118640. **
  118641. ** 6 7 106
  118642. **
  118643. ** are encoded.
  118644. **
  118645. ** When this function is called, *pp points to the start of an element of
  118646. ** the list. *piPos contains the value of the previous entry in the list.
  118647. ** After it returns, *piPos contains the value of the next element of the
  118648. ** list and *pp is advanced to the following varint.
  118649. */
  118650. static void fts3GetDeltaPosition(char **pp, int *piPos){
  118651. int iVal;
  118652. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  118653. *piPos += (iVal-2);
  118654. }
  118655. /*
  118656. ** Helper function for fts3ExprIterate() (see below).
  118657. */
  118658. static int fts3ExprIterate2(
  118659. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  118660. int *piPhrase, /* Pointer to phrase counter */
  118661. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  118662. void *pCtx /* Second argument to pass to callback */
  118663. ){
  118664. int rc; /* Return code */
  118665. int eType = pExpr->eType; /* Type of expression node pExpr */
  118666. if( eType!=FTSQUERY_PHRASE ){
  118667. assert( pExpr->pLeft && pExpr->pRight );
  118668. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  118669. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  118670. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  118671. }
  118672. }else{
  118673. rc = x(pExpr, *piPhrase, pCtx);
  118674. (*piPhrase)++;
  118675. }
  118676. return rc;
  118677. }
  118678. /*
  118679. ** Iterate through all phrase nodes in an FTS3 query, except those that
  118680. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  118681. ** For each phrase node found, the supplied callback function is invoked.
  118682. **
  118683. ** If the callback function returns anything other than SQLITE_OK,
  118684. ** the iteration is abandoned and the error code returned immediately.
  118685. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  118686. ** all eligible phrase nodes.
  118687. */
  118688. static int fts3ExprIterate(
  118689. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  118690. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  118691. void *pCtx /* Second argument to pass to callback */
  118692. ){
  118693. int iPhrase = 0; /* Variable used as the phrase counter */
  118694. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  118695. }
  118696. /*
  118697. ** This is an fts3ExprIterate() callback used while loading the doclists
  118698. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  118699. ** fts3ExprLoadDoclists().
  118700. */
  118701. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118702. int rc = SQLITE_OK;
  118703. Fts3Phrase *pPhrase = pExpr->pPhrase;
  118704. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  118705. UNUSED_PARAMETER(iPhrase);
  118706. p->nPhrase++;
  118707. p->nToken += pPhrase->nToken;
  118708. return rc;
  118709. }
  118710. /*
  118711. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  118712. ** pCsr.
  118713. **
  118714. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  118715. ** phrases in the expression (all phrases except those directly or
  118716. ** indirectly descended from the right-hand-side of a NOT operator). If
  118717. ** pnToken is not NULL, then it is set to the number of tokens in all
  118718. ** matchable phrases of the expression.
  118719. */
  118720. static int fts3ExprLoadDoclists(
  118721. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  118722. int *pnPhrase, /* OUT: Number of phrases in query */
  118723. int *pnToken /* OUT: Number of tokens in query */
  118724. ){
  118725. int rc; /* Return Code */
  118726. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  118727. sCtx.pCsr = pCsr;
  118728. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  118729. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  118730. if( pnToken ) *pnToken = sCtx.nToken;
  118731. return rc;
  118732. }
  118733. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118734. (*(int *)ctx)++;
  118735. UNUSED_PARAMETER(pExpr);
  118736. UNUSED_PARAMETER(iPhrase);
  118737. return SQLITE_OK;
  118738. }
  118739. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  118740. int nPhrase = 0;
  118741. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  118742. return nPhrase;
  118743. }
  118744. /*
  118745. ** Advance the position list iterator specified by the first two
  118746. ** arguments so that it points to the first element with a value greater
  118747. ** than or equal to parameter iNext.
  118748. */
  118749. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  118750. char *pIter = *ppIter;
  118751. if( pIter ){
  118752. int iIter = *piIter;
  118753. while( iIter<iNext ){
  118754. if( 0==(*pIter & 0xFE) ){
  118755. iIter = -1;
  118756. pIter = 0;
  118757. break;
  118758. }
  118759. fts3GetDeltaPosition(&pIter, &iIter);
  118760. }
  118761. *piIter = iIter;
  118762. *ppIter = pIter;
  118763. }
  118764. }
  118765. /*
  118766. ** Advance the snippet iterator to the next candidate snippet.
  118767. */
  118768. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  118769. int i; /* Loop counter */
  118770. if( pIter->iCurrent<0 ){
  118771. /* The SnippetIter object has just been initialized. The first snippet
  118772. ** candidate always starts at offset 0 (even if this candidate has a
  118773. ** score of 0.0).
  118774. */
  118775. pIter->iCurrent = 0;
  118776. /* Advance the 'head' iterator of each phrase to the first offset that
  118777. ** is greater than or equal to (iNext+nSnippet).
  118778. */
  118779. for(i=0; i<pIter->nPhrase; i++){
  118780. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118781. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  118782. }
  118783. }else{
  118784. int iStart;
  118785. int iEnd = 0x7FFFFFFF;
  118786. for(i=0; i<pIter->nPhrase; i++){
  118787. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118788. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  118789. iEnd = pPhrase->iHead;
  118790. }
  118791. }
  118792. if( iEnd==0x7FFFFFFF ){
  118793. return 1;
  118794. }
  118795. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  118796. for(i=0; i<pIter->nPhrase; i++){
  118797. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118798. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  118799. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  118800. }
  118801. }
  118802. return 0;
  118803. }
  118804. /*
  118805. ** Retrieve information about the current candidate snippet of snippet
  118806. ** iterator pIter.
  118807. */
  118808. static void fts3SnippetDetails(
  118809. SnippetIter *pIter, /* Snippet iterator */
  118810. u64 mCovered, /* Bitmask of phrases already covered */
  118811. int *piToken, /* OUT: First token of proposed snippet */
  118812. int *piScore, /* OUT: "Score" for this snippet */
  118813. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  118814. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  118815. ){
  118816. int iStart = pIter->iCurrent; /* First token of snippet */
  118817. int iScore = 0; /* Score of this snippet */
  118818. int i; /* Loop counter */
  118819. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  118820. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  118821. for(i=0; i<pIter->nPhrase; i++){
  118822. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118823. if( pPhrase->pTail ){
  118824. char *pCsr = pPhrase->pTail;
  118825. int iCsr = pPhrase->iTail;
  118826. while( iCsr<(iStart+pIter->nSnippet) ){
  118827. int j;
  118828. u64 mPhrase = (u64)1 << i;
  118829. u64 mPos = (u64)1 << (iCsr - iStart);
  118830. assert( iCsr>=iStart );
  118831. if( (mCover|mCovered)&mPhrase ){
  118832. iScore++;
  118833. }else{
  118834. iScore += 1000;
  118835. }
  118836. mCover |= mPhrase;
  118837. for(j=0; j<pPhrase->nToken; j++){
  118838. mHighlight |= (mPos>>j);
  118839. }
  118840. if( 0==(*pCsr & 0x0FE) ) break;
  118841. fts3GetDeltaPosition(&pCsr, &iCsr);
  118842. }
  118843. }
  118844. }
  118845. /* Set the output variables before returning. */
  118846. *piToken = iStart;
  118847. *piScore = iScore;
  118848. *pmCover = mCover;
  118849. *pmHighlight = mHighlight;
  118850. }
  118851. /*
  118852. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  118853. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  118854. */
  118855. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118856. SnippetIter *p = (SnippetIter *)ctx;
  118857. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  118858. char *pCsr;
  118859. int rc;
  118860. pPhrase->nToken = pExpr->pPhrase->nToken;
  118861. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  118862. assert( rc==SQLITE_OK || pCsr==0 );
  118863. if( pCsr ){
  118864. int iFirst = 0;
  118865. pPhrase->pList = pCsr;
  118866. fts3GetDeltaPosition(&pCsr, &iFirst);
  118867. assert( iFirst>=0 );
  118868. pPhrase->pHead = pCsr;
  118869. pPhrase->pTail = pCsr;
  118870. pPhrase->iHead = iFirst;
  118871. pPhrase->iTail = iFirst;
  118872. }else{
  118873. assert( rc!=SQLITE_OK || (
  118874. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  118875. ));
  118876. }
  118877. return rc;
  118878. }
  118879. /*
  118880. ** Select the fragment of text consisting of nFragment contiguous tokens
  118881. ** from column iCol that represent the "best" snippet. The best snippet
  118882. ** is the snippet with the highest score, where scores are calculated
  118883. ** by adding:
  118884. **
  118885. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  118886. **
  118887. ** (b) +1000 points for the first occurrence of each matchable phrase in
  118888. ** the snippet for which the corresponding mCovered bit is not set.
  118889. **
  118890. ** The selected snippet parameters are stored in structure *pFragment before
  118891. ** returning. The score of the selected snippet is stored in *piScore
  118892. ** before returning.
  118893. */
  118894. static int fts3BestSnippet(
  118895. int nSnippet, /* Desired snippet length */
  118896. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  118897. int iCol, /* Index of column to create snippet from */
  118898. u64 mCovered, /* Mask of phrases already covered */
  118899. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  118900. SnippetFragment *pFragment, /* OUT: Best snippet found */
  118901. int *piScore /* OUT: Score of snippet pFragment */
  118902. ){
  118903. int rc; /* Return Code */
  118904. int nList; /* Number of phrases in expression */
  118905. SnippetIter sIter; /* Iterates through snippet candidates */
  118906. int nByte; /* Number of bytes of space to allocate */
  118907. int iBestScore = -1; /* Best snippet score found so far */
  118908. int i; /* Loop counter */
  118909. memset(&sIter, 0, sizeof(sIter));
  118910. /* Iterate through the phrases in the expression to count them. The same
  118911. ** callback makes sure the doclists are loaded for each phrase.
  118912. */
  118913. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  118914. if( rc!=SQLITE_OK ){
  118915. return rc;
  118916. }
  118917. /* Now that it is known how many phrases there are, allocate and zero
  118918. ** the required space using malloc().
  118919. */
  118920. nByte = sizeof(SnippetPhrase) * nList;
  118921. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  118922. if( !sIter.aPhrase ){
  118923. return SQLITE_NOMEM;
  118924. }
  118925. memset(sIter.aPhrase, 0, nByte);
  118926. /* Initialize the contents of the SnippetIter object. Then iterate through
  118927. ** the set of phrases in the expression to populate the aPhrase[] array.
  118928. */
  118929. sIter.pCsr = pCsr;
  118930. sIter.iCol = iCol;
  118931. sIter.nSnippet = nSnippet;
  118932. sIter.nPhrase = nList;
  118933. sIter.iCurrent = -1;
  118934. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  118935. /* Set the *pmSeen output variable. */
  118936. for(i=0; i<nList; i++){
  118937. if( sIter.aPhrase[i].pHead ){
  118938. *pmSeen |= (u64)1 << i;
  118939. }
  118940. }
  118941. /* Loop through all candidate snippets. Store the best snippet in
  118942. ** *pFragment. Store its associated 'score' in iBestScore.
  118943. */
  118944. pFragment->iCol = iCol;
  118945. while( !fts3SnippetNextCandidate(&sIter) ){
  118946. int iPos;
  118947. int iScore;
  118948. u64 mCover;
  118949. u64 mHighlight;
  118950. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  118951. assert( iScore>=0 );
  118952. if( iScore>iBestScore ){
  118953. pFragment->iPos = iPos;
  118954. pFragment->hlmask = mHighlight;
  118955. pFragment->covered = mCover;
  118956. iBestScore = iScore;
  118957. }
  118958. }
  118959. sqlite3_free(sIter.aPhrase);
  118960. *piScore = iBestScore;
  118961. return SQLITE_OK;
  118962. }
  118963. /*
  118964. ** Append a string to the string-buffer passed as the first argument.
  118965. **
  118966. ** If nAppend is negative, then the length of the string zAppend is
  118967. ** determined using strlen().
  118968. */
  118969. static int fts3StringAppend(
  118970. StrBuffer *pStr, /* Buffer to append to */
  118971. const char *zAppend, /* Pointer to data to append to buffer */
  118972. int nAppend /* Size of zAppend in bytes (or -1) */
  118973. ){
  118974. if( nAppend<0 ){
  118975. nAppend = (int)strlen(zAppend);
  118976. }
  118977. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  118978. ** to grow the buffer until so that it is big enough to accomadate the
  118979. ** appended data.
  118980. */
  118981. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  118982. int nAlloc = pStr->nAlloc+nAppend+100;
  118983. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  118984. if( !zNew ){
  118985. return SQLITE_NOMEM;
  118986. }
  118987. pStr->z = zNew;
  118988. pStr->nAlloc = nAlloc;
  118989. }
  118990. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  118991. /* Append the data to the string buffer. */
  118992. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  118993. pStr->n += nAppend;
  118994. pStr->z[pStr->n] = '\0';
  118995. return SQLITE_OK;
  118996. }
  118997. /*
  118998. ** The fts3BestSnippet() function often selects snippets that end with a
  118999. ** query term. That is, the final term of the snippet is always a term
  119000. ** that requires highlighting. For example, if 'X' is a highlighted term
  119001. ** and '.' is a non-highlighted term, BestSnippet() may select:
  119002. **
  119003. ** ........X.....X
  119004. **
  119005. ** This function "shifts" the beginning of the snippet forward in the
  119006. ** document so that there are approximately the same number of
  119007. ** non-highlighted terms to the right of the final highlighted term as there
  119008. ** are to the left of the first highlighted term. For example, to this:
  119009. **
  119010. ** ....X.....X....
  119011. **
  119012. ** This is done as part of extracting the snippet text, not when selecting
  119013. ** the snippet. Snippet selection is done based on doclists only, so there
  119014. ** is no way for fts3BestSnippet() to know whether or not the document
  119015. ** actually contains terms that follow the final highlighted term.
  119016. */
  119017. static int fts3SnippetShift(
  119018. Fts3Table *pTab, /* FTS3 table snippet comes from */
  119019. int iLangid, /* Language id to use in tokenizing */
  119020. int nSnippet, /* Number of tokens desired for snippet */
  119021. const char *zDoc, /* Document text to extract snippet from */
  119022. int nDoc, /* Size of buffer zDoc in bytes */
  119023. int *piPos, /* IN/OUT: First token of snippet */
  119024. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  119025. ){
  119026. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  119027. if( hlmask ){
  119028. int nLeft; /* Tokens to the left of first highlight */
  119029. int nRight; /* Tokens to the right of last highlight */
  119030. int nDesired; /* Ideal number of tokens to shift forward */
  119031. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  119032. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  119033. nDesired = (nLeft-nRight)/2;
  119034. /* Ideally, the start of the snippet should be pushed forward in the
  119035. ** document nDesired tokens. This block checks if there are actually
  119036. ** nDesired tokens to the right of the snippet. If so, *piPos and
  119037. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  119038. ** right. Otherwise, the snippet is shifted by the number of tokens
  119039. ** available.
  119040. */
  119041. if( nDesired>0 ){
  119042. int nShift; /* Number of tokens to shift snippet by */
  119043. int iCurrent = 0; /* Token counter */
  119044. int rc; /* Return Code */
  119045. sqlite3_tokenizer_module *pMod;
  119046. sqlite3_tokenizer_cursor *pC;
  119047. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  119048. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  119049. ** or more tokens in zDoc/nDoc.
  119050. */
  119051. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  119052. if( rc!=SQLITE_OK ){
  119053. return rc;
  119054. }
  119055. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  119056. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  119057. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  119058. }
  119059. pMod->xClose(pC);
  119060. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  119061. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  119062. assert( nShift<=nDesired );
  119063. if( nShift>0 ){
  119064. *piPos += nShift;
  119065. *pHlmask = hlmask >> nShift;
  119066. }
  119067. }
  119068. }
  119069. return SQLITE_OK;
  119070. }
  119071. /*
  119072. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  119073. ** append it to string buffer pOut.
  119074. */
  119075. static int fts3SnippetText(
  119076. Fts3Cursor *pCsr, /* FTS3 Cursor */
  119077. SnippetFragment *pFragment, /* Snippet to extract */
  119078. int iFragment, /* Fragment number */
  119079. int isLast, /* True for final fragment in snippet */
  119080. int nSnippet, /* Number of tokens in extracted snippet */
  119081. const char *zOpen, /* String inserted before highlighted term */
  119082. const char *zClose, /* String inserted after highlighted term */
  119083. const char *zEllipsis, /* String inserted between snippets */
  119084. StrBuffer *pOut /* Write output here */
  119085. ){
  119086. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119087. int rc; /* Return code */
  119088. const char *zDoc; /* Document text to extract snippet from */
  119089. int nDoc; /* Size of zDoc in bytes */
  119090. int iCurrent = 0; /* Current token number of document */
  119091. int iEnd = 0; /* Byte offset of end of current token */
  119092. int isShiftDone = 0; /* True after snippet is shifted */
  119093. int iPos = pFragment->iPos; /* First token of snippet */
  119094. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  119095. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  119096. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  119097. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  119098. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  119099. if( zDoc==0 ){
  119100. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  119101. return SQLITE_NOMEM;
  119102. }
  119103. return SQLITE_OK;
  119104. }
  119105. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  119106. /* Open a token cursor on the document. */
  119107. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  119108. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  119109. if( rc!=SQLITE_OK ){
  119110. return rc;
  119111. }
  119112. while( rc==SQLITE_OK ){
  119113. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  119114. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  119115. int iBegin = 0; /* Offset in zDoc of start of token */
  119116. int iFin = 0; /* Offset in zDoc of end of token */
  119117. int isHighlight = 0; /* True for highlighted terms */
  119118. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  119119. ** in the FTS code the variable that the third argument to xNext points to
  119120. ** is initialized to zero before the first (*but not necessarily
  119121. ** subsequent*) call to xNext(). This is done for a particular application
  119122. ** that needs to know whether or not the tokenizer is being used for
  119123. ** snippet generation or for some other purpose.
  119124. **
  119125. ** Extreme care is required when writing code to depend on this
  119126. ** initialization. It is not a documented part of the tokenizer interface.
  119127. ** If a tokenizer is used directly by any code outside of FTS, this
  119128. ** convention might not be respected. */
  119129. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  119130. if( rc!=SQLITE_OK ){
  119131. if( rc==SQLITE_DONE ){
  119132. /* Special case - the last token of the snippet is also the last token
  119133. ** of the column. Append any punctuation that occurred between the end
  119134. ** of the previous token and the end of the document to the output.
  119135. ** Then break out of the loop. */
  119136. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  119137. }
  119138. break;
  119139. }
  119140. if( iCurrent<iPos ){ continue; }
  119141. if( !isShiftDone ){
  119142. int n = nDoc - iBegin;
  119143. rc = fts3SnippetShift(
  119144. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  119145. );
  119146. isShiftDone = 1;
  119147. /* Now that the shift has been done, check if the initial "..." are
  119148. ** required. They are required if (a) this is not the first fragment,
  119149. ** or (b) this fragment does not begin at position 0 of its column.
  119150. */
  119151. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  119152. rc = fts3StringAppend(pOut, zEllipsis, -1);
  119153. }
  119154. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  119155. }
  119156. if( iCurrent>=(iPos+nSnippet) ){
  119157. if( isLast ){
  119158. rc = fts3StringAppend(pOut, zEllipsis, -1);
  119159. }
  119160. break;
  119161. }
  119162. /* Set isHighlight to true if this term should be highlighted. */
  119163. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  119164. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  119165. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  119166. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  119167. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  119168. iEnd = iFin;
  119169. }
  119170. pMod->xClose(pC);
  119171. return rc;
  119172. }
  119173. /*
  119174. ** This function is used to count the entries in a column-list (a
  119175. ** delta-encoded list of term offsets within a single column of a single
  119176. ** row). When this function is called, *ppCollist should point to the
  119177. ** beginning of the first varint in the column-list (the varint that
  119178. ** contains the position of the first matching term in the column data).
  119179. ** Before returning, *ppCollist is set to point to the first byte after
  119180. ** the last varint in the column-list (either the 0x00 signifying the end
  119181. ** of the position-list, or the 0x01 that precedes the column number of
  119182. ** the next column in the position-list).
  119183. **
  119184. ** The number of elements in the column-list is returned.
  119185. */
  119186. static int fts3ColumnlistCount(char **ppCollist){
  119187. char *pEnd = *ppCollist;
  119188. char c = 0;
  119189. int nEntry = 0;
  119190. /* A column-list is terminated by either a 0x01 or 0x00. */
  119191. while( 0xFE & (*pEnd | c) ){
  119192. c = *pEnd++ & 0x80;
  119193. if( !c ) nEntry++;
  119194. }
  119195. *ppCollist = pEnd;
  119196. return nEntry;
  119197. }
  119198. /*
  119199. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  119200. ** for a single query.
  119201. **
  119202. ** fts3ExprIterate() callback to load the 'global' elements of a
  119203. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  119204. ** of the matchinfo array that are constant for all rows returned by the
  119205. ** current query.
  119206. **
  119207. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  119208. ** function populates Matchinfo.aMatchinfo[] as follows:
  119209. **
  119210. ** for(iCol=0; iCol<nCol; iCol++){
  119211. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  119212. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  119213. ** }
  119214. **
  119215. ** where X is the number of matches for phrase iPhrase is column iCol of all
  119216. ** rows of the table. Y is the number of rows for which column iCol contains
  119217. ** at least one instance of phrase iPhrase.
  119218. **
  119219. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  119220. ** Y values are set to nDoc, where nDoc is the number of documents in the
  119221. ** file system. This is done because the full-text index doclist is required
  119222. ** to calculate these values properly, and the full-text index doclist is
  119223. ** not available for deferred tokens.
  119224. */
  119225. static int fts3ExprGlobalHitsCb(
  119226. Fts3Expr *pExpr, /* Phrase expression node */
  119227. int iPhrase, /* Phrase number (numbered from zero) */
  119228. void *pCtx /* Pointer to MatchInfo structure */
  119229. ){
  119230. MatchInfo *p = (MatchInfo *)pCtx;
  119231. return sqlite3Fts3EvalPhraseStats(
  119232. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  119233. );
  119234. }
  119235. /*
  119236. ** fts3ExprIterate() callback used to collect the "local" part of the
  119237. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  119238. ** array that are different for each row returned by the query.
  119239. */
  119240. static int fts3ExprLocalHitsCb(
  119241. Fts3Expr *pExpr, /* Phrase expression node */
  119242. int iPhrase, /* Phrase number */
  119243. void *pCtx /* Pointer to MatchInfo structure */
  119244. ){
  119245. int rc = SQLITE_OK;
  119246. MatchInfo *p = (MatchInfo *)pCtx;
  119247. int iStart = iPhrase * p->nCol * 3;
  119248. int i;
  119249. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  119250. char *pCsr;
  119251. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  119252. if( pCsr ){
  119253. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  119254. }else{
  119255. p->aMatchinfo[iStart+i*3] = 0;
  119256. }
  119257. }
  119258. return rc;
  119259. }
  119260. static int fts3MatchinfoCheck(
  119261. Fts3Table *pTab,
  119262. char cArg,
  119263. char **pzErr
  119264. ){
  119265. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  119266. || (cArg==FTS3_MATCHINFO_NCOL)
  119267. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  119268. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  119269. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  119270. || (cArg==FTS3_MATCHINFO_LCS)
  119271. || (cArg==FTS3_MATCHINFO_HITS)
  119272. ){
  119273. return SQLITE_OK;
  119274. }
  119275. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  119276. return SQLITE_ERROR;
  119277. }
  119278. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  119279. int nVal; /* Number of integers output by cArg */
  119280. switch( cArg ){
  119281. case FTS3_MATCHINFO_NDOC:
  119282. case FTS3_MATCHINFO_NPHRASE:
  119283. case FTS3_MATCHINFO_NCOL:
  119284. nVal = 1;
  119285. break;
  119286. case FTS3_MATCHINFO_AVGLENGTH:
  119287. case FTS3_MATCHINFO_LENGTH:
  119288. case FTS3_MATCHINFO_LCS:
  119289. nVal = pInfo->nCol;
  119290. break;
  119291. default:
  119292. assert( cArg==FTS3_MATCHINFO_HITS );
  119293. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  119294. break;
  119295. }
  119296. return nVal;
  119297. }
  119298. static int fts3MatchinfoSelectDoctotal(
  119299. Fts3Table *pTab,
  119300. sqlite3_stmt **ppStmt,
  119301. sqlite3_int64 *pnDoc,
  119302. const char **paLen
  119303. ){
  119304. sqlite3_stmt *pStmt;
  119305. const char *a;
  119306. sqlite3_int64 nDoc;
  119307. if( !*ppStmt ){
  119308. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  119309. if( rc!=SQLITE_OK ) return rc;
  119310. }
  119311. pStmt = *ppStmt;
  119312. assert( sqlite3_data_count(pStmt)==1 );
  119313. a = sqlite3_column_blob(pStmt, 0);
  119314. a += sqlite3Fts3GetVarint(a, &nDoc);
  119315. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  119316. *pnDoc = (u32)nDoc;
  119317. if( paLen ) *paLen = a;
  119318. return SQLITE_OK;
  119319. }
  119320. /*
  119321. ** An instance of the following structure is used to store state while
  119322. ** iterating through a multi-column position-list corresponding to the
  119323. ** hits for a single phrase on a single row in order to calculate the
  119324. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  119325. */
  119326. typedef struct LcsIterator LcsIterator;
  119327. struct LcsIterator {
  119328. Fts3Expr *pExpr; /* Pointer to phrase expression */
  119329. int iPosOffset; /* Tokens count up to end of this phrase */
  119330. char *pRead; /* Cursor used to iterate through aDoclist */
  119331. int iPos; /* Current position */
  119332. };
  119333. /*
  119334. ** If LcsIterator.iCol is set to the following value, the iterator has
  119335. ** finished iterating through all offsets for all columns.
  119336. */
  119337. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  119338. static int fts3MatchinfoLcsCb(
  119339. Fts3Expr *pExpr, /* Phrase expression node */
  119340. int iPhrase, /* Phrase number (numbered from zero) */
  119341. void *pCtx /* Pointer to MatchInfo structure */
  119342. ){
  119343. LcsIterator *aIter = (LcsIterator *)pCtx;
  119344. aIter[iPhrase].pExpr = pExpr;
  119345. return SQLITE_OK;
  119346. }
  119347. /*
  119348. ** Advance the iterator passed as an argument to the next position. Return
  119349. ** 1 if the iterator is at EOF or if it now points to the start of the
  119350. ** position list for the next column.
  119351. */
  119352. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  119353. char *pRead = pIter->pRead;
  119354. sqlite3_int64 iRead;
  119355. int rc = 0;
  119356. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  119357. if( iRead==0 || iRead==1 ){
  119358. pRead = 0;
  119359. rc = 1;
  119360. }else{
  119361. pIter->iPos += (int)(iRead-2);
  119362. }
  119363. pIter->pRead = pRead;
  119364. return rc;
  119365. }
  119366. /*
  119367. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  119368. **
  119369. ** If the call is successful, the longest-common-substring lengths for each
  119370. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  119371. ** array before returning. SQLITE_OK is returned in this case.
  119372. **
  119373. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  119374. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  119375. ** undefined.
  119376. */
  119377. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  119378. LcsIterator *aIter;
  119379. int i;
  119380. int iCol;
  119381. int nToken = 0;
  119382. /* Allocate and populate the array of LcsIterator objects. The array
  119383. ** contains one element for each matchable phrase in the query.
  119384. **/
  119385. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  119386. if( !aIter ) return SQLITE_NOMEM;
  119387. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  119388. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  119389. for(i=0; i<pInfo->nPhrase; i++){
  119390. LcsIterator *pIter = &aIter[i];
  119391. nToken -= pIter->pExpr->pPhrase->nToken;
  119392. pIter->iPosOffset = nToken;
  119393. }
  119394. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119395. int nLcs = 0; /* LCS value for this column */
  119396. int nLive = 0; /* Number of iterators in aIter not at EOF */
  119397. for(i=0; i<pInfo->nPhrase; i++){
  119398. int rc;
  119399. LcsIterator *pIt = &aIter[i];
  119400. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  119401. if( rc!=SQLITE_OK ) return rc;
  119402. if( pIt->pRead ){
  119403. pIt->iPos = pIt->iPosOffset;
  119404. fts3LcsIteratorAdvance(&aIter[i]);
  119405. nLive++;
  119406. }
  119407. }
  119408. while( nLive>0 ){
  119409. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  119410. int nThisLcs = 0; /* LCS for the current iterator positions */
  119411. for(i=0; i<pInfo->nPhrase; i++){
  119412. LcsIterator *pIter = &aIter[i];
  119413. if( pIter->pRead==0 ){
  119414. /* This iterator is already at EOF for this column. */
  119415. nThisLcs = 0;
  119416. }else{
  119417. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  119418. pAdv = pIter;
  119419. }
  119420. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  119421. nThisLcs++;
  119422. }else{
  119423. nThisLcs = 1;
  119424. }
  119425. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  119426. }
  119427. }
  119428. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  119429. }
  119430. pInfo->aMatchinfo[iCol] = nLcs;
  119431. }
  119432. sqlite3_free(aIter);
  119433. return SQLITE_OK;
  119434. }
  119435. /*
  119436. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  119437. ** be returned by the matchinfo() function. Argument zArg contains the
  119438. ** format string passed as the second argument to matchinfo (or the
  119439. ** default value "pcx" if no second argument was specified). The format
  119440. ** string has already been validated and the pInfo->aMatchinfo[] array
  119441. ** is guaranteed to be large enough for the output.
  119442. **
  119443. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  119444. ** If it is false, then assume that those fields that do not change between
  119445. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  119446. ** have already been populated.
  119447. **
  119448. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  119449. ** occurs. If a value other than SQLITE_OK is returned, the state the
  119450. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  119451. */
  119452. static int fts3MatchinfoValues(
  119453. Fts3Cursor *pCsr, /* FTS3 cursor object */
  119454. int bGlobal, /* True to grab the global stats */
  119455. MatchInfo *pInfo, /* Matchinfo context object */
  119456. const char *zArg /* Matchinfo format string */
  119457. ){
  119458. int rc = SQLITE_OK;
  119459. int i;
  119460. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119461. sqlite3_stmt *pSelect = 0;
  119462. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  119463. switch( zArg[i] ){
  119464. case FTS3_MATCHINFO_NPHRASE:
  119465. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  119466. break;
  119467. case FTS3_MATCHINFO_NCOL:
  119468. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  119469. break;
  119470. case FTS3_MATCHINFO_NDOC:
  119471. if( bGlobal ){
  119472. sqlite3_int64 nDoc = 0;
  119473. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  119474. pInfo->aMatchinfo[0] = (u32)nDoc;
  119475. }
  119476. break;
  119477. case FTS3_MATCHINFO_AVGLENGTH:
  119478. if( bGlobal ){
  119479. sqlite3_int64 nDoc; /* Number of rows in table */
  119480. const char *a; /* Aggregate column length array */
  119481. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  119482. if( rc==SQLITE_OK ){
  119483. int iCol;
  119484. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119485. u32 iVal;
  119486. sqlite3_int64 nToken;
  119487. a += sqlite3Fts3GetVarint(a, &nToken);
  119488. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  119489. pInfo->aMatchinfo[iCol] = iVal;
  119490. }
  119491. }
  119492. }
  119493. break;
  119494. case FTS3_MATCHINFO_LENGTH: {
  119495. sqlite3_stmt *pSelectDocsize = 0;
  119496. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  119497. if( rc==SQLITE_OK ){
  119498. int iCol;
  119499. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  119500. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119501. sqlite3_int64 nToken;
  119502. a += sqlite3Fts3GetVarint(a, &nToken);
  119503. pInfo->aMatchinfo[iCol] = (u32)nToken;
  119504. }
  119505. }
  119506. sqlite3_reset(pSelectDocsize);
  119507. break;
  119508. }
  119509. case FTS3_MATCHINFO_LCS:
  119510. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  119511. if( rc==SQLITE_OK ){
  119512. rc = fts3MatchinfoLcs(pCsr, pInfo);
  119513. }
  119514. break;
  119515. default: {
  119516. Fts3Expr *pExpr;
  119517. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  119518. pExpr = pCsr->pExpr;
  119519. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  119520. if( rc!=SQLITE_OK ) break;
  119521. if( bGlobal ){
  119522. if( pCsr->pDeferred ){
  119523. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  119524. if( rc!=SQLITE_OK ) break;
  119525. }
  119526. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  119527. if( rc!=SQLITE_OK ) break;
  119528. }
  119529. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  119530. break;
  119531. }
  119532. }
  119533. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  119534. }
  119535. sqlite3_reset(pSelect);
  119536. return rc;
  119537. }
  119538. /*
  119539. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  119540. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  119541. */
  119542. static int fts3GetMatchinfo(
  119543. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  119544. const char *zArg /* Second argument to matchinfo() function */
  119545. ){
  119546. MatchInfo sInfo;
  119547. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119548. int rc = SQLITE_OK;
  119549. int bGlobal = 0; /* Collect 'global' stats as well as local */
  119550. memset(&sInfo, 0, sizeof(MatchInfo));
  119551. sInfo.pCursor = pCsr;
  119552. sInfo.nCol = pTab->nColumn;
  119553. /* If there is cached matchinfo() data, but the format string for the
  119554. ** cache does not match the format string for this request, discard
  119555. ** the cached data. */
  119556. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  119557. assert( pCsr->aMatchinfo );
  119558. sqlite3_free(pCsr->aMatchinfo);
  119559. pCsr->zMatchinfo = 0;
  119560. pCsr->aMatchinfo = 0;
  119561. }
  119562. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  119563. ** matchinfo function has been called for this query. In this case
  119564. ** allocate the array used to accumulate the matchinfo data and
  119565. ** initialize those elements that are constant for every row.
  119566. */
  119567. if( pCsr->aMatchinfo==0 ){
  119568. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  119569. int nArg; /* Bytes in zArg */
  119570. int i; /* Used to iterate through zArg */
  119571. /* Determine the number of phrases in the query */
  119572. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  119573. sInfo.nPhrase = pCsr->nPhrase;
  119574. /* Determine the number of integers in the buffer returned by this call. */
  119575. for(i=0; zArg[i]; i++){
  119576. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  119577. }
  119578. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  119579. nArg = (int)strlen(zArg);
  119580. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  119581. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  119582. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  119583. pCsr->nMatchinfo = nMatchinfo;
  119584. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  119585. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  119586. pCsr->isMatchinfoNeeded = 1;
  119587. bGlobal = 1;
  119588. }
  119589. sInfo.aMatchinfo = pCsr->aMatchinfo;
  119590. sInfo.nPhrase = pCsr->nPhrase;
  119591. if( pCsr->isMatchinfoNeeded ){
  119592. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  119593. pCsr->isMatchinfoNeeded = 0;
  119594. }
  119595. return rc;
  119596. }
  119597. /*
  119598. ** Implementation of snippet() function.
  119599. */
  119600. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  119601. sqlite3_context *pCtx, /* SQLite function call context */
  119602. Fts3Cursor *pCsr, /* Cursor object */
  119603. const char *zStart, /* Snippet start text - "<b>" */
  119604. const char *zEnd, /* Snippet end text - "</b>" */
  119605. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  119606. int iCol, /* Extract snippet from this column */
  119607. int nToken /* Approximate number of tokens in snippet */
  119608. ){
  119609. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119610. int rc = SQLITE_OK;
  119611. int i;
  119612. StrBuffer res = {0, 0, 0};
  119613. /* The returned text includes up to four fragments of text extracted from
  119614. ** the data in the current row. The first iteration of the for(...) loop
  119615. ** below attempts to locate a single fragment of text nToken tokens in
  119616. ** size that contains at least one instance of all phrases in the query
  119617. ** expression that appear in the current row. If such a fragment of text
  119618. ** cannot be found, the second iteration of the loop attempts to locate
  119619. ** a pair of fragments, and so on.
  119620. */
  119621. int nSnippet = 0; /* Number of fragments in this snippet */
  119622. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  119623. int nFToken = -1; /* Number of tokens in each fragment */
  119624. if( !pCsr->pExpr ){
  119625. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  119626. return;
  119627. }
  119628. for(nSnippet=1; 1; nSnippet++){
  119629. int iSnip; /* Loop counter 0..nSnippet-1 */
  119630. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  119631. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  119632. if( nToken>=0 ){
  119633. nFToken = (nToken+nSnippet-1) / nSnippet;
  119634. }else{
  119635. nFToken = -1 * nToken;
  119636. }
  119637. for(iSnip=0; iSnip<nSnippet; iSnip++){
  119638. int iBestScore = -1; /* Best score of columns checked so far */
  119639. int iRead; /* Used to iterate through columns */
  119640. SnippetFragment *pFragment = &aSnippet[iSnip];
  119641. memset(pFragment, 0, sizeof(*pFragment));
  119642. /* Loop through all columns of the table being considered for snippets.
  119643. ** If the iCol argument to this function was negative, this means all
  119644. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  119645. */
  119646. for(iRead=0; iRead<pTab->nColumn; iRead++){
  119647. SnippetFragment sF = {0, 0, 0, 0};
  119648. int iS;
  119649. if( iCol>=0 && iRead!=iCol ) continue;
  119650. /* Find the best snippet of nFToken tokens in column iRead. */
  119651. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  119652. if( rc!=SQLITE_OK ){
  119653. goto snippet_out;
  119654. }
  119655. if( iS>iBestScore ){
  119656. *pFragment = sF;
  119657. iBestScore = iS;
  119658. }
  119659. }
  119660. mCovered |= pFragment->covered;
  119661. }
  119662. /* If all query phrases seen by fts3BestSnippet() are present in at least
  119663. ** one of the nSnippet snippet fragments, break out of the loop.
  119664. */
  119665. assert( (mCovered&mSeen)==mCovered );
  119666. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  119667. }
  119668. assert( nFToken>0 );
  119669. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  119670. rc = fts3SnippetText(pCsr, &aSnippet[i],
  119671. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  119672. );
  119673. }
  119674. snippet_out:
  119675. sqlite3Fts3SegmentsClose(pTab);
  119676. if( rc!=SQLITE_OK ){
  119677. sqlite3_result_error_code(pCtx, rc);
  119678. sqlite3_free(res.z);
  119679. }else{
  119680. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  119681. }
  119682. }
  119683. typedef struct TermOffset TermOffset;
  119684. typedef struct TermOffsetCtx TermOffsetCtx;
  119685. struct TermOffset {
  119686. char *pList; /* Position-list */
  119687. int iPos; /* Position just read from pList */
  119688. int iOff; /* Offset of this term from read positions */
  119689. };
  119690. struct TermOffsetCtx {
  119691. Fts3Cursor *pCsr;
  119692. int iCol; /* Column of table to populate aTerm for */
  119693. int iTerm;
  119694. sqlite3_int64 iDocid;
  119695. TermOffset *aTerm;
  119696. };
  119697. /*
  119698. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  119699. */
  119700. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  119701. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  119702. int nTerm; /* Number of tokens in phrase */
  119703. int iTerm; /* For looping through nTerm phrase terms */
  119704. char *pList; /* Pointer to position list for phrase */
  119705. int iPos = 0; /* First position in position-list */
  119706. int rc;
  119707. UNUSED_PARAMETER(iPhrase);
  119708. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  119709. nTerm = pExpr->pPhrase->nToken;
  119710. if( pList ){
  119711. fts3GetDeltaPosition(&pList, &iPos);
  119712. assert( iPos>=0 );
  119713. }
  119714. for(iTerm=0; iTerm<nTerm; iTerm++){
  119715. TermOffset *pT = &p->aTerm[p->iTerm++];
  119716. pT->iOff = nTerm-iTerm-1;
  119717. pT->pList = pList;
  119718. pT->iPos = iPos;
  119719. }
  119720. return rc;
  119721. }
  119722. /*
  119723. ** Implementation of offsets() function.
  119724. */
  119725. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  119726. sqlite3_context *pCtx, /* SQLite function call context */
  119727. Fts3Cursor *pCsr /* Cursor object */
  119728. ){
  119729. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119730. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  119731. int rc; /* Return Code */
  119732. int nToken; /* Number of tokens in query */
  119733. int iCol; /* Column currently being processed */
  119734. StrBuffer res = {0, 0, 0}; /* Result string */
  119735. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  119736. if( !pCsr->pExpr ){
  119737. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  119738. return;
  119739. }
  119740. memset(&sCtx, 0, sizeof(sCtx));
  119741. assert( pCsr->isRequireSeek==0 );
  119742. /* Count the number of terms in the query */
  119743. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  119744. if( rc!=SQLITE_OK ) goto offsets_out;
  119745. /* Allocate the array of TermOffset iterators. */
  119746. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  119747. if( 0==sCtx.aTerm ){
  119748. rc = SQLITE_NOMEM;
  119749. goto offsets_out;
  119750. }
  119751. sCtx.iDocid = pCsr->iPrevId;
  119752. sCtx.pCsr = pCsr;
  119753. /* Loop through the table columns, appending offset information to
  119754. ** string-buffer res for each column.
  119755. */
  119756. for(iCol=0; iCol<pTab->nColumn; iCol++){
  119757. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  119758. const char *ZDUMMY; /* Dummy argument used with xNext() */
  119759. int NDUMMY = 0; /* Dummy argument used with xNext() */
  119760. int iStart = 0;
  119761. int iEnd = 0;
  119762. int iCurrent = 0;
  119763. const char *zDoc;
  119764. int nDoc;
  119765. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  119766. ** no way that this operation can fail, so the return code from
  119767. ** fts3ExprIterate() can be discarded.
  119768. */
  119769. sCtx.iCol = iCol;
  119770. sCtx.iTerm = 0;
  119771. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  119772. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  119773. ** in column iCol, jump immediately to the next iteration of the loop.
  119774. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  119775. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  119776. ** to the caller.
  119777. */
  119778. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  119779. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  119780. if( zDoc==0 ){
  119781. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  119782. continue;
  119783. }
  119784. rc = SQLITE_NOMEM;
  119785. goto offsets_out;
  119786. }
  119787. /* Initialize a tokenizer iterator to iterate through column iCol. */
  119788. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  119789. zDoc, nDoc, &pC
  119790. );
  119791. if( rc!=SQLITE_OK ) goto offsets_out;
  119792. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  119793. while( rc==SQLITE_OK ){
  119794. int i; /* Used to loop through terms */
  119795. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  119796. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  119797. for(i=0; i<nToken; i++){
  119798. TermOffset *pT = &sCtx.aTerm[i];
  119799. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  119800. iMinPos = pT->iPos-pT->iOff;
  119801. pTerm = pT;
  119802. }
  119803. }
  119804. if( !pTerm ){
  119805. /* All offsets for this column have been gathered. */
  119806. rc = SQLITE_DONE;
  119807. }else{
  119808. assert( iCurrent<=iMinPos );
  119809. if( 0==(0xFE&*pTerm->pList) ){
  119810. pTerm->pList = 0;
  119811. }else{
  119812. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  119813. }
  119814. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  119815. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  119816. }
  119817. if( rc==SQLITE_OK ){
  119818. char aBuffer[64];
  119819. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  119820. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  119821. );
  119822. rc = fts3StringAppend(&res, aBuffer, -1);
  119823. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  119824. rc = FTS_CORRUPT_VTAB;
  119825. }
  119826. }
  119827. }
  119828. if( rc==SQLITE_DONE ){
  119829. rc = SQLITE_OK;
  119830. }
  119831. pMod->xClose(pC);
  119832. if( rc!=SQLITE_OK ) goto offsets_out;
  119833. }
  119834. offsets_out:
  119835. sqlite3_free(sCtx.aTerm);
  119836. assert( rc!=SQLITE_DONE );
  119837. sqlite3Fts3SegmentsClose(pTab);
  119838. if( rc!=SQLITE_OK ){
  119839. sqlite3_result_error_code(pCtx, rc);
  119840. sqlite3_free(res.z);
  119841. }else{
  119842. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  119843. }
  119844. return;
  119845. }
  119846. /*
  119847. ** Implementation of matchinfo() function.
  119848. */
  119849. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  119850. sqlite3_context *pContext, /* Function call context */
  119851. Fts3Cursor *pCsr, /* FTS3 table cursor */
  119852. const char *zArg /* Second arg to matchinfo() function */
  119853. ){
  119854. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119855. int rc;
  119856. int i;
  119857. const char *zFormat;
  119858. if( zArg ){
  119859. for(i=0; zArg[i]; i++){
  119860. char *zErr = 0;
  119861. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  119862. sqlite3_result_error(pContext, zErr, -1);
  119863. sqlite3_free(zErr);
  119864. return;
  119865. }
  119866. }
  119867. zFormat = zArg;
  119868. }else{
  119869. zFormat = FTS3_MATCHINFO_DEFAULT;
  119870. }
  119871. if( !pCsr->pExpr ){
  119872. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  119873. return;
  119874. }
  119875. /* Retrieve matchinfo() data. */
  119876. rc = fts3GetMatchinfo(pCsr, zFormat);
  119877. sqlite3Fts3SegmentsClose(pTab);
  119878. if( rc!=SQLITE_OK ){
  119879. sqlite3_result_error_code(pContext, rc);
  119880. }else{
  119881. int n = pCsr->nMatchinfo * sizeof(u32);
  119882. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  119883. }
  119884. }
  119885. #endif
  119886. /************** End of fts3_snippet.c ****************************************/
  119887. /************** Begin file fts3_unicode.c ************************************/
  119888. /*
  119889. ** 2012 May 24
  119890. **
  119891. ** The author disclaims copyright to this source code. In place of
  119892. ** a legal notice, here is a blessing:
  119893. **
  119894. ** May you do good and not evil.
  119895. ** May you find forgiveness for yourself and forgive others.
  119896. ** May you share freely, never taking more than you give.
  119897. **
  119898. ******************************************************************************
  119899. **
  119900. ** Implementation of the "unicode" full-text-search tokenizer.
  119901. */
  119902. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  119903. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119904. /* #include <assert.h> */
  119905. /* #include <stdlib.h> */
  119906. /* #include <stdio.h> */
  119907. /* #include <string.h> */
  119908. /*
  119909. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  119910. ** from the sqlite3 source file utf.c. If this file is compiled as part
  119911. ** of the amalgamation, they are not required.
  119912. */
  119913. #ifndef SQLITE_AMALGAMATION
  119914. static const unsigned char sqlite3Utf8Trans1[] = {
  119915. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119916. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  119917. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  119918. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  119919. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119920. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  119921. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119922. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  119923. };
  119924. #define READ_UTF8(zIn, zTerm, c) \
  119925. c = *(zIn++); \
  119926. if( c>=0xc0 ){ \
  119927. c = sqlite3Utf8Trans1[c-0xc0]; \
  119928. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  119929. c = (c<<6) + (0x3f & *(zIn++)); \
  119930. } \
  119931. if( c<0x80 \
  119932. || (c&0xFFFFF800)==0xD800 \
  119933. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  119934. }
  119935. #define WRITE_UTF8(zOut, c) { \
  119936. if( c<0x00080 ){ \
  119937. *zOut++ = (u8)(c&0xFF); \
  119938. } \
  119939. else if( c<0x00800 ){ \
  119940. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  119941. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119942. } \
  119943. else if( c<0x10000 ){ \
  119944. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  119945. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  119946. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119947. }else{ \
  119948. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  119949. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  119950. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  119951. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119952. } \
  119953. }
  119954. #endif /* ifndef SQLITE_AMALGAMATION */
  119955. typedef struct unicode_tokenizer unicode_tokenizer;
  119956. typedef struct unicode_cursor unicode_cursor;
  119957. struct unicode_tokenizer {
  119958. sqlite3_tokenizer base;
  119959. int bRemoveDiacritic;
  119960. int nException;
  119961. int *aiException;
  119962. };
  119963. struct unicode_cursor {
  119964. sqlite3_tokenizer_cursor base;
  119965. const unsigned char *aInput; /* Input text being tokenized */
  119966. int nInput; /* Size of aInput[] in bytes */
  119967. int iOff; /* Current offset within aInput[] */
  119968. int iToken; /* Index of next token to be returned */
  119969. char *zToken; /* storage for current token */
  119970. int nAlloc; /* space allocated at zToken */
  119971. };
  119972. /*
  119973. ** Destroy a tokenizer allocated by unicodeCreate().
  119974. */
  119975. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  119976. if( pTokenizer ){
  119977. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  119978. sqlite3_free(p->aiException);
  119979. sqlite3_free(p);
  119980. }
  119981. return SQLITE_OK;
  119982. }
  119983. /*
  119984. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  119985. ** statement has specified that the tokenizer for this table shall consider
  119986. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  119987. ** token characters (if bAlnum==1).
  119988. **
  119989. ** For each codepoint in the zIn/nIn string, this function checks if the
  119990. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  119991. ** If so, no action is taken. Otherwise, the codepoint is added to the
  119992. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  119993. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  119994. ** codepoints in the aiException[] array.
  119995. **
  119996. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  119997. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  119998. ** It is not possible to change the behavior of the tokenizer with respect
  119999. ** to these codepoints.
  120000. */
  120001. static int unicodeAddExceptions(
  120002. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  120003. int bAlnum, /* Replace Isalnum() return value with this */
  120004. const char *zIn, /* Array of characters to make exceptions */
  120005. int nIn /* Length of z in bytes */
  120006. ){
  120007. const unsigned char *z = (const unsigned char *)zIn;
  120008. const unsigned char *zTerm = &z[nIn];
  120009. int iCode;
  120010. int nEntry = 0;
  120011. assert( bAlnum==0 || bAlnum==1 );
  120012. while( z<zTerm ){
  120013. READ_UTF8(z, zTerm, iCode);
  120014. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  120015. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  120016. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  120017. ){
  120018. nEntry++;
  120019. }
  120020. }
  120021. if( nEntry ){
  120022. int *aNew; /* New aiException[] array */
  120023. int nNew; /* Number of valid entries in array aNew[] */
  120024. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  120025. if( aNew==0 ) return SQLITE_NOMEM;
  120026. nNew = p->nException;
  120027. z = (const unsigned char *)zIn;
  120028. while( z<zTerm ){
  120029. READ_UTF8(z, zTerm, iCode);
  120030. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  120031. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  120032. ){
  120033. int i, j;
  120034. for(i=0; i<nNew && aNew[i]<iCode; i++);
  120035. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  120036. aNew[i] = iCode;
  120037. nNew++;
  120038. }
  120039. }
  120040. p->aiException = aNew;
  120041. p->nException = nNew;
  120042. }
  120043. return SQLITE_OK;
  120044. }
  120045. /*
  120046. ** Return true if the p->aiException[] array contains the value iCode.
  120047. */
  120048. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  120049. if( p->nException>0 ){
  120050. int *a = p->aiException;
  120051. int iLo = 0;
  120052. int iHi = p->nException-1;
  120053. while( iHi>=iLo ){
  120054. int iTest = (iHi + iLo) / 2;
  120055. if( iCode==a[iTest] ){
  120056. return 1;
  120057. }else if( iCode>a[iTest] ){
  120058. iLo = iTest+1;
  120059. }else{
  120060. iHi = iTest-1;
  120061. }
  120062. }
  120063. }
  120064. return 0;
  120065. }
  120066. /*
  120067. ** Return true if, for the purposes of tokenization, codepoint iCode is
  120068. ** considered a token character (not a separator).
  120069. */
  120070. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  120071. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  120072. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  120073. }
  120074. /*
  120075. ** Create a new tokenizer instance.
  120076. */
  120077. static int unicodeCreate(
  120078. int nArg, /* Size of array argv[] */
  120079. const char * const *azArg, /* Tokenizer creation arguments */
  120080. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  120081. ){
  120082. unicode_tokenizer *pNew; /* New tokenizer object */
  120083. int i;
  120084. int rc = SQLITE_OK;
  120085. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  120086. if( pNew==NULL ) return SQLITE_NOMEM;
  120087. memset(pNew, 0, sizeof(unicode_tokenizer));
  120088. pNew->bRemoveDiacritic = 1;
  120089. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  120090. const char *z = azArg[i];
  120091. int n = strlen(z);
  120092. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  120093. pNew->bRemoveDiacritic = 1;
  120094. }
  120095. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  120096. pNew->bRemoveDiacritic = 0;
  120097. }
  120098. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  120099. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  120100. }
  120101. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  120102. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  120103. }
  120104. else{
  120105. /* Unrecognized argument */
  120106. rc = SQLITE_ERROR;
  120107. }
  120108. }
  120109. if( rc!=SQLITE_OK ){
  120110. unicodeDestroy((sqlite3_tokenizer *)pNew);
  120111. pNew = 0;
  120112. }
  120113. *pp = (sqlite3_tokenizer *)pNew;
  120114. return rc;
  120115. }
  120116. /*
  120117. ** Prepare to begin tokenizing a particular string. The input
  120118. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  120119. ** used to incrementally tokenize this string is returned in
  120120. ** *ppCursor.
  120121. */
  120122. static int unicodeOpen(
  120123. sqlite3_tokenizer *p, /* The tokenizer */
  120124. const char *aInput, /* Input string */
  120125. int nInput, /* Size of string aInput in bytes */
  120126. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  120127. ){
  120128. unicode_cursor *pCsr;
  120129. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  120130. if( pCsr==0 ){
  120131. return SQLITE_NOMEM;
  120132. }
  120133. memset(pCsr, 0, sizeof(unicode_cursor));
  120134. pCsr->aInput = (const unsigned char *)aInput;
  120135. if( aInput==0 ){
  120136. pCsr->nInput = 0;
  120137. }else if( nInput<0 ){
  120138. pCsr->nInput = (int)strlen(aInput);
  120139. }else{
  120140. pCsr->nInput = nInput;
  120141. }
  120142. *pp = &pCsr->base;
  120143. UNUSED_PARAMETER(p);
  120144. return SQLITE_OK;
  120145. }
  120146. /*
  120147. ** Close a tokenization cursor previously opened by a call to
  120148. ** simpleOpen() above.
  120149. */
  120150. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  120151. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  120152. sqlite3_free(pCsr->zToken);
  120153. sqlite3_free(pCsr);
  120154. return SQLITE_OK;
  120155. }
  120156. /*
  120157. ** Extract the next token from a tokenization cursor. The cursor must
  120158. ** have been opened by a prior call to simpleOpen().
  120159. */
  120160. static int unicodeNext(
  120161. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  120162. const char **paToken, /* OUT: Token text */
  120163. int *pnToken, /* OUT: Number of bytes at *paToken */
  120164. int *piStart, /* OUT: Starting offset of token */
  120165. int *piEnd, /* OUT: Ending offset of token */
  120166. int *piPos /* OUT: Position integer of token */
  120167. ){
  120168. unicode_cursor *pCsr = (unicode_cursor *)pC;
  120169. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  120170. int iCode;
  120171. char *zOut;
  120172. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  120173. const unsigned char *zStart = z;
  120174. const unsigned char *zEnd;
  120175. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  120176. /* Scan past any delimiter characters before the start of the next token.
  120177. ** Return SQLITE_DONE early if this takes us all the way to the end of
  120178. ** the input. */
  120179. while( z<zTerm ){
  120180. READ_UTF8(z, zTerm, iCode);
  120181. if( unicodeIsAlnum(p, iCode) ) break;
  120182. zStart = z;
  120183. }
  120184. if( zStart>=zTerm ) return SQLITE_DONE;
  120185. zOut = pCsr->zToken;
  120186. do {
  120187. int iOut;
  120188. /* Grow the output buffer if required. */
  120189. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  120190. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  120191. if( !zNew ) return SQLITE_NOMEM;
  120192. zOut = &zNew[zOut - pCsr->zToken];
  120193. pCsr->zToken = zNew;
  120194. pCsr->nAlloc += 64;
  120195. }
  120196. /* Write the folded case of the last character read to the output */
  120197. zEnd = z;
  120198. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  120199. if( iOut ){
  120200. WRITE_UTF8(zOut, iOut);
  120201. }
  120202. /* If the cursor is not at EOF, read the next character */
  120203. if( z>=zTerm ) break;
  120204. READ_UTF8(z, zTerm, iCode);
  120205. }while( unicodeIsAlnum(p, iCode)
  120206. || sqlite3FtsUnicodeIsdiacritic(iCode)
  120207. );
  120208. /* Set the output variables and return. */
  120209. pCsr->iOff = (z - pCsr->aInput);
  120210. *paToken = pCsr->zToken;
  120211. *pnToken = zOut - pCsr->zToken;
  120212. *piStart = (zStart - pCsr->aInput);
  120213. *piEnd = (zEnd - pCsr->aInput);
  120214. *piPos = pCsr->iToken++;
  120215. return SQLITE_OK;
  120216. }
  120217. /*
  120218. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  120219. ** structure for the unicode tokenizer.
  120220. */
  120221. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  120222. static const sqlite3_tokenizer_module module = {
  120223. 0,
  120224. unicodeCreate,
  120225. unicodeDestroy,
  120226. unicodeOpen,
  120227. unicodeClose,
  120228. unicodeNext,
  120229. 0,
  120230. };
  120231. *ppModule = &module;
  120232. }
  120233. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  120234. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  120235. /************** End of fts3_unicode.c ****************************************/
  120236. /************** Begin file fts3_unicode2.c ***********************************/
  120237. /*
  120238. ** 2012 May 25
  120239. **
  120240. ** The author disclaims copyright to this source code. In place of
  120241. ** a legal notice, here is a blessing:
  120242. **
  120243. ** May you do good and not evil.
  120244. ** May you find forgiveness for yourself and forgive others.
  120245. ** May you share freely, never taking more than you give.
  120246. **
  120247. ******************************************************************************
  120248. */
  120249. /*
  120250. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  120251. */
  120252. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  120253. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  120254. /* #include <assert.h> */
  120255. /*
  120256. ** Return true if the argument corresponds to a unicode codepoint
  120257. ** classified as either a letter or a number. Otherwise false.
  120258. **
  120259. ** The results are undefined if the value passed to this function
  120260. ** is less than zero.
  120261. */
  120262. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  120263. /* Each unsigned integer in the following array corresponds to a contiguous
  120264. ** range of unicode codepoints that are not either letters or numbers (i.e.
  120265. ** codepoints for which this function should return 0).
  120266. **
  120267. ** The most significant 22 bits in each 32-bit value contain the first
  120268. ** codepoint in the range. The least significant 10 bits are used to store
  120269. ** the size of the range (always at least 1). In other words, the value
  120270. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  120271. ** C. It is not possible to represent a range larger than 1023 codepoints
  120272. ** using this format.
  120273. */
  120274. const static unsigned int aEntry[] = {
  120275. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  120276. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  120277. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  120278. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  120279. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  120280. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  120281. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  120282. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  120283. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  120284. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  120285. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  120286. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  120287. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  120288. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  120289. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  120290. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  120291. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  120292. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  120293. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  120294. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  120295. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  120296. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  120297. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  120298. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  120299. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  120300. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  120301. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  120302. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  120303. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  120304. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  120305. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  120306. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  120307. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  120308. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  120309. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  120310. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  120311. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  120312. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  120313. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  120314. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  120315. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  120316. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  120317. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  120318. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  120319. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  120320. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  120321. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  120322. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  120323. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  120324. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  120325. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  120326. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  120327. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  120328. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  120329. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  120330. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  120331. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  120332. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  120333. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  120334. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  120335. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  120336. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  120337. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  120338. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  120339. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  120340. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  120341. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  120342. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  120343. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  120344. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  120345. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  120346. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  120347. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  120348. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  120349. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  120350. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  120351. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  120352. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  120353. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  120354. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  120355. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  120356. 0x380400F0,
  120357. };
  120358. static const unsigned int aAscii[4] = {
  120359. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  120360. };
  120361. if( c<128 ){
  120362. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  120363. }else if( c<(1<<22) ){
  120364. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  120365. int iRes;
  120366. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  120367. int iLo = 0;
  120368. while( iHi>=iLo ){
  120369. int iTest = (iHi + iLo) / 2;
  120370. if( key >= aEntry[iTest] ){
  120371. iRes = iTest;
  120372. iLo = iTest+1;
  120373. }else{
  120374. iHi = iTest-1;
  120375. }
  120376. }
  120377. assert( aEntry[0]<key );
  120378. assert( key>=aEntry[iRes] );
  120379. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  120380. }
  120381. return 1;
  120382. }
  120383. /*
  120384. ** If the argument is a codepoint corresponding to a lowercase letter
  120385. ** in the ASCII range with a diacritic added, return the codepoint
  120386. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  120387. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  120388. ** E"). The resuls of passing a codepoint that corresponds to an
  120389. ** uppercase letter are undefined.
  120390. */
  120391. static int remove_diacritic(int c){
  120392. unsigned short aDia[] = {
  120393. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  120394. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  120395. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  120396. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  120397. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  120398. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  120399. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  120400. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  120401. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  120402. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  120403. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  120404. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  120405. 62924, 63050, 63082, 63274, 63390,
  120406. };
  120407. char aChar[] = {
  120408. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  120409. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  120410. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  120411. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  120412. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  120413. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  120414. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  120415. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  120416. 'e', 'i', 'o', 'u', 'y',
  120417. };
  120418. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  120419. int iRes = 0;
  120420. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  120421. int iLo = 0;
  120422. while( iHi>=iLo ){
  120423. int iTest = (iHi + iLo) / 2;
  120424. if( key >= aDia[iTest] ){
  120425. iRes = iTest;
  120426. iLo = iTest+1;
  120427. }else{
  120428. iHi = iTest-1;
  120429. }
  120430. }
  120431. assert( key>=aDia[iRes] );
  120432. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  120433. };
  120434. /*
  120435. ** Return true if the argument interpreted as a unicode codepoint
  120436. ** is a diacritical modifier character.
  120437. */
  120438. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  120439. unsigned int mask0 = 0x08029FDF;
  120440. unsigned int mask1 = 0x000361F8;
  120441. if( c<768 || c>817 ) return 0;
  120442. return (c < 768+32) ?
  120443. (mask0 & (1 << (c-768))) :
  120444. (mask1 & (1 << (c-768-32)));
  120445. }
  120446. /*
  120447. ** Interpret the argument as a unicode codepoint. If the codepoint
  120448. ** is an upper case character that has a lower case equivalent,
  120449. ** return the codepoint corresponding to the lower case version.
  120450. ** Otherwise, return a copy of the argument.
  120451. **
  120452. ** The results are undefined if the value passed to this function
  120453. ** is less than zero.
  120454. */
  120455. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  120456. /* Each entry in the following array defines a rule for folding a range
  120457. ** of codepoints to lower case. The rule applies to a range of nRange
  120458. ** codepoints starting at codepoint iCode.
  120459. **
  120460. ** If the least significant bit in flags is clear, then the rule applies
  120461. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  120462. ** need to be folded). Or, if it is set, then the rule only applies to
  120463. ** every second codepoint in the range, starting with codepoint C.
  120464. **
  120465. ** The 7 most significant bits in flags are an index into the aiOff[]
  120466. ** array. If a specific codepoint C does require folding, then its lower
  120467. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  120468. **
  120469. ** The contents of this array are generated by parsing the CaseFolding.txt
  120470. ** file distributed as part of the "Unicode Character Database". See
  120471. ** http://www.unicode.org for details.
  120472. */
  120473. static const struct TableEntry {
  120474. unsigned short iCode;
  120475. unsigned char flags;
  120476. unsigned char nRange;
  120477. } aEntry[] = {
  120478. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  120479. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  120480. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  120481. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  120482. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  120483. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  120484. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  120485. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  120486. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  120487. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  120488. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  120489. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  120490. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  120491. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  120492. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  120493. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  120494. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  120495. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  120496. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  120497. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  120498. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  120499. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  120500. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  120501. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  120502. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  120503. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  120504. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  120505. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  120506. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  120507. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  120508. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  120509. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  120510. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  120511. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  120512. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  120513. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  120514. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  120515. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  120516. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  120517. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  120518. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  120519. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  120520. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  120521. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  120522. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  120523. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  120524. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  120525. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  120526. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  120527. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  120528. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  120529. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  120530. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  120531. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  120532. {65313, 14, 26},
  120533. };
  120534. static const unsigned short aiOff[] = {
  120535. 1, 2, 8, 15, 16, 26, 28, 32,
  120536. 37, 38, 40, 48, 63, 64, 69, 71,
  120537. 79, 80, 116, 202, 203, 205, 206, 207,
  120538. 209, 210, 211, 213, 214, 217, 218, 219,
  120539. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  120540. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  120541. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  120542. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  120543. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  120544. 65514, 65521, 65527, 65528, 65529,
  120545. };
  120546. int ret = c;
  120547. assert( c>=0 );
  120548. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  120549. if( c<128 ){
  120550. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  120551. }else if( c<65536 ){
  120552. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  120553. int iLo = 0;
  120554. int iRes = -1;
  120555. while( iHi>=iLo ){
  120556. int iTest = (iHi + iLo) / 2;
  120557. int cmp = (c - aEntry[iTest].iCode);
  120558. if( cmp>=0 ){
  120559. iRes = iTest;
  120560. iLo = iTest+1;
  120561. }else{
  120562. iHi = iTest-1;
  120563. }
  120564. }
  120565. assert( iRes<0 || c>=aEntry[iRes].iCode );
  120566. if( iRes>=0 ){
  120567. const struct TableEntry *p = &aEntry[iRes];
  120568. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  120569. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  120570. assert( ret>0 );
  120571. }
  120572. }
  120573. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  120574. }
  120575. else if( c>=66560 && c<66600 ){
  120576. ret = c + 40;
  120577. }
  120578. return ret;
  120579. }
  120580. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  120581. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  120582. /************** End of fts3_unicode2.c ***************************************/
  120583. /************** Begin file rtree.c *******************************************/
  120584. /*
  120585. ** 2001 September 15
  120586. **
  120587. ** The author disclaims copyright to this source code. In place of
  120588. ** a legal notice, here is a blessing:
  120589. **
  120590. ** May you do good and not evil.
  120591. ** May you find forgiveness for yourself and forgive others.
  120592. ** May you share freely, never taking more than you give.
  120593. **
  120594. *************************************************************************
  120595. ** This file contains code for implementations of the r-tree and r*-tree
  120596. ** algorithms packaged as an SQLite virtual table module.
  120597. */
  120598. /*
  120599. ** Database Format of R-Tree Tables
  120600. ** --------------------------------
  120601. **
  120602. ** The data structure for a single virtual r-tree table is stored in three
  120603. ** native SQLite tables declared as follows. In each case, the '%' character
  120604. ** in the table name is replaced with the user-supplied name of the r-tree
  120605. ** table.
  120606. **
  120607. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  120608. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  120609. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  120610. **
  120611. ** The data for each node of the r-tree structure is stored in the %_node
  120612. ** table. For each node that is not the root node of the r-tree, there is
  120613. ** an entry in the %_parent table associating the node with its parent.
  120614. ** And for each row of data in the table, there is an entry in the %_rowid
  120615. ** table that maps from the entries rowid to the id of the node that it
  120616. ** is stored on.
  120617. **
  120618. ** The root node of an r-tree always exists, even if the r-tree table is
  120619. ** empty. The nodeno of the root node is always 1. All other nodes in the
  120620. ** table must be the same size as the root node. The content of each node
  120621. ** is formatted as follows:
  120622. **
  120623. ** 1. If the node is the root node (node 1), then the first 2 bytes
  120624. ** of the node contain the tree depth as a big-endian integer.
  120625. ** For non-root nodes, the first 2 bytes are left unused.
  120626. **
  120627. ** 2. The next 2 bytes contain the number of entries currently
  120628. ** stored in the node.
  120629. **
  120630. ** 3. The remainder of the node contains the node entries. Each entry
  120631. ** consists of a single 8-byte integer followed by an even number
  120632. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  120633. ** of a record. For internal nodes it is the node number of a
  120634. ** child page.
  120635. */
  120636. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  120637. /*
  120638. ** This file contains an implementation of a couple of different variants
  120639. ** of the r-tree algorithm. See the README file for further details. The
  120640. ** same data-structure is used for all, but the algorithms for insert and
  120641. ** delete operations vary. The variants used are selected at compile time
  120642. ** by defining the following symbols:
  120643. */
  120644. /* Either, both or none of the following may be set to activate
  120645. ** r*tree variant algorithms.
  120646. */
  120647. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  120648. #define VARIANT_RSTARTREE_REINSERT 1
  120649. /*
  120650. ** Exactly one of the following must be set to 1.
  120651. */
  120652. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  120653. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  120654. #define VARIANT_RSTARTREE_SPLIT 1
  120655. #define VARIANT_GUTTMAN_SPLIT \
  120656. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  120657. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  120658. #define PickNext QuadraticPickNext
  120659. #define PickSeeds QuadraticPickSeeds
  120660. #define AssignCells splitNodeGuttman
  120661. #endif
  120662. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  120663. #define PickNext LinearPickNext
  120664. #define PickSeeds LinearPickSeeds
  120665. #define AssignCells splitNodeGuttman
  120666. #endif
  120667. #if VARIANT_RSTARTREE_SPLIT
  120668. #define AssignCells splitNodeStartree
  120669. #endif
  120670. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  120671. # define NDEBUG 1
  120672. #endif
  120673. #ifndef SQLITE_CORE
  120674. SQLITE_EXTENSION_INIT1
  120675. #else
  120676. #endif
  120677. /* #include <string.h> */
  120678. /* #include <assert.h> */
  120679. #ifndef SQLITE_AMALGAMATION
  120680. #include "sqlite3rtree.h"
  120681. typedef sqlite3_int64 i64;
  120682. typedef unsigned char u8;
  120683. typedef unsigned int u32;
  120684. #endif
  120685. /* The following macro is used to suppress compiler warnings.
  120686. */
  120687. #ifndef UNUSED_PARAMETER
  120688. # define UNUSED_PARAMETER(x) (void)(x)
  120689. #endif
  120690. typedef struct Rtree Rtree;
  120691. typedef struct RtreeCursor RtreeCursor;
  120692. typedef struct RtreeNode RtreeNode;
  120693. typedef struct RtreeCell RtreeCell;
  120694. typedef struct RtreeConstraint RtreeConstraint;
  120695. typedef struct RtreeMatchArg RtreeMatchArg;
  120696. typedef struct RtreeGeomCallback RtreeGeomCallback;
  120697. typedef union RtreeCoord RtreeCoord;
  120698. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  120699. #define RTREE_MAX_DIMENSIONS 5
  120700. /* Size of hash table Rtree.aHash. This hash table is not expected to
  120701. ** ever contain very many entries, so a fixed number of buckets is
  120702. ** used.
  120703. */
  120704. #define HASHSIZE 128
  120705. /*
  120706. ** An rtree virtual-table object.
  120707. */
  120708. struct Rtree {
  120709. sqlite3_vtab base;
  120710. sqlite3 *db; /* Host database connection */
  120711. int iNodeSize; /* Size in bytes of each node in the node table */
  120712. int nDim; /* Number of dimensions */
  120713. int nBytesPerCell; /* Bytes consumed per cell */
  120714. int iDepth; /* Current depth of the r-tree structure */
  120715. char *zDb; /* Name of database containing r-tree table */
  120716. char *zName; /* Name of r-tree table */
  120717. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  120718. int nBusy; /* Current number of users of this structure */
  120719. /* List of nodes removed during a CondenseTree operation. List is
  120720. ** linked together via the pointer normally used for hash chains -
  120721. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  120722. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  120723. */
  120724. RtreeNode *pDeleted;
  120725. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  120726. /* Statements to read/write/delete a record from xxx_node */
  120727. sqlite3_stmt *pReadNode;
  120728. sqlite3_stmt *pWriteNode;
  120729. sqlite3_stmt *pDeleteNode;
  120730. /* Statements to read/write/delete a record from xxx_rowid */
  120731. sqlite3_stmt *pReadRowid;
  120732. sqlite3_stmt *pWriteRowid;
  120733. sqlite3_stmt *pDeleteRowid;
  120734. /* Statements to read/write/delete a record from xxx_parent */
  120735. sqlite3_stmt *pReadParent;
  120736. sqlite3_stmt *pWriteParent;
  120737. sqlite3_stmt *pDeleteParent;
  120738. int eCoordType;
  120739. };
  120740. /* Possible values for eCoordType: */
  120741. #define RTREE_COORD_REAL32 0
  120742. #define RTREE_COORD_INT32 1
  120743. /*
  120744. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  120745. ** only deal with integer coordinates. No floating point operations
  120746. ** will be done.
  120747. */
  120748. #ifdef SQLITE_RTREE_INT_ONLY
  120749. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  120750. typedef int RtreeValue; /* Low accuracy coordinate */
  120751. #else
  120752. typedef double RtreeDValue; /* High accuracy coordinate */
  120753. typedef float RtreeValue; /* Low accuracy coordinate */
  120754. #endif
  120755. /*
  120756. ** The minimum number of cells allowed for a node is a third of the
  120757. ** maximum. In Gutman's notation:
  120758. **
  120759. ** m = M/3
  120760. **
  120761. ** If an R*-tree "Reinsert" operation is required, the same number of
  120762. ** cells are removed from the overfull node and reinserted into the tree.
  120763. */
  120764. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  120765. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  120766. #define RTREE_MAXCELLS 51
  120767. /*
  120768. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  120769. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  120770. ** Therefore all non-root nodes must contain at least 3 entries. Since
  120771. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  120772. ** 40 or less.
  120773. */
  120774. #define RTREE_MAX_DEPTH 40
  120775. /*
  120776. ** An rtree cursor object.
  120777. */
  120778. struct RtreeCursor {
  120779. sqlite3_vtab_cursor base;
  120780. RtreeNode *pNode; /* Node cursor is currently pointing at */
  120781. int iCell; /* Index of current cell in pNode */
  120782. int iStrategy; /* Copy of idxNum search parameter */
  120783. int nConstraint; /* Number of entries in aConstraint */
  120784. RtreeConstraint *aConstraint; /* Search constraints. */
  120785. };
  120786. union RtreeCoord {
  120787. RtreeValue f;
  120788. int i;
  120789. };
  120790. /*
  120791. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  120792. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  120793. ** variable pRtree points to the Rtree structure associated with the
  120794. ** RtreeCoord.
  120795. */
  120796. #ifdef SQLITE_RTREE_INT_ONLY
  120797. # define DCOORD(coord) ((RtreeDValue)coord.i)
  120798. #else
  120799. # define DCOORD(coord) ( \
  120800. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  120801. ((double)coord.f) : \
  120802. ((double)coord.i) \
  120803. )
  120804. #endif
  120805. /*
  120806. ** A search constraint.
  120807. */
  120808. struct RtreeConstraint {
  120809. int iCoord; /* Index of constrained coordinate */
  120810. int op; /* Constraining operation */
  120811. RtreeDValue rValue; /* Constraint value. */
  120812. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  120813. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  120814. };
  120815. /* Possible values for RtreeConstraint.op */
  120816. #define RTREE_EQ 0x41
  120817. #define RTREE_LE 0x42
  120818. #define RTREE_LT 0x43
  120819. #define RTREE_GE 0x44
  120820. #define RTREE_GT 0x45
  120821. #define RTREE_MATCH 0x46
  120822. /*
  120823. ** An rtree structure node.
  120824. */
  120825. struct RtreeNode {
  120826. RtreeNode *pParent; /* Parent node */
  120827. i64 iNode;
  120828. int nRef;
  120829. int isDirty;
  120830. u8 *zData;
  120831. RtreeNode *pNext; /* Next node in this hash chain */
  120832. };
  120833. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  120834. /*
  120835. ** Structure to store a deserialized rtree record.
  120836. */
  120837. struct RtreeCell {
  120838. i64 iRowid;
  120839. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  120840. };
  120841. /*
  120842. ** Value for the first field of every RtreeMatchArg object. The MATCH
  120843. ** operator tests that the first field of a blob operand matches this
  120844. ** value to avoid operating on invalid blobs (which could cause a segfault).
  120845. */
  120846. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  120847. /*
  120848. ** An instance of this structure must be supplied as a blob argument to
  120849. ** the right-hand-side of an SQL MATCH operator used to constrain an
  120850. ** r-tree query.
  120851. */
  120852. struct RtreeMatchArg {
  120853. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  120854. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  120855. void *pContext;
  120856. int nParam;
  120857. RtreeDValue aParam[1];
  120858. };
  120859. /*
  120860. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  120861. ** a single instance of the following structure is allocated. It is used
  120862. ** as the context for the user-function created by by s_r_g_c(). The object
  120863. ** is eventually deleted by the destructor mechanism provided by
  120864. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  120865. ** the geometry callback function).
  120866. */
  120867. struct RtreeGeomCallback {
  120868. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  120869. void *pContext;
  120870. };
  120871. #ifndef MAX
  120872. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  120873. #endif
  120874. #ifndef MIN
  120875. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  120876. #endif
  120877. /*
  120878. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  120879. ** 64 bit integer. The deserialized value is returned.
  120880. */
  120881. static int readInt16(u8 *p){
  120882. return (p[0]<<8) + p[1];
  120883. }
  120884. static void readCoord(u8 *p, RtreeCoord *pCoord){
  120885. u32 i = (
  120886. (((u32)p[0]) << 24) +
  120887. (((u32)p[1]) << 16) +
  120888. (((u32)p[2]) << 8) +
  120889. (((u32)p[3]) << 0)
  120890. );
  120891. *(u32 *)pCoord = i;
  120892. }
  120893. static i64 readInt64(u8 *p){
  120894. return (
  120895. (((i64)p[0]) << 56) +
  120896. (((i64)p[1]) << 48) +
  120897. (((i64)p[2]) << 40) +
  120898. (((i64)p[3]) << 32) +
  120899. (((i64)p[4]) << 24) +
  120900. (((i64)p[5]) << 16) +
  120901. (((i64)p[6]) << 8) +
  120902. (((i64)p[7]) << 0)
  120903. );
  120904. }
  120905. /*
  120906. ** Functions to serialize a 16 bit integer, 32 bit real number and
  120907. ** 64 bit integer. The value returned is the number of bytes written
  120908. ** to the argument buffer (always 2, 4 and 8 respectively).
  120909. */
  120910. static int writeInt16(u8 *p, int i){
  120911. p[0] = (i>> 8)&0xFF;
  120912. p[1] = (i>> 0)&0xFF;
  120913. return 2;
  120914. }
  120915. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  120916. u32 i;
  120917. assert( sizeof(RtreeCoord)==4 );
  120918. assert( sizeof(u32)==4 );
  120919. i = *(u32 *)pCoord;
  120920. p[0] = (i>>24)&0xFF;
  120921. p[1] = (i>>16)&0xFF;
  120922. p[2] = (i>> 8)&0xFF;
  120923. p[3] = (i>> 0)&0xFF;
  120924. return 4;
  120925. }
  120926. static int writeInt64(u8 *p, i64 i){
  120927. p[0] = (i>>56)&0xFF;
  120928. p[1] = (i>>48)&0xFF;
  120929. p[2] = (i>>40)&0xFF;
  120930. p[3] = (i>>32)&0xFF;
  120931. p[4] = (i>>24)&0xFF;
  120932. p[5] = (i>>16)&0xFF;
  120933. p[6] = (i>> 8)&0xFF;
  120934. p[7] = (i>> 0)&0xFF;
  120935. return 8;
  120936. }
  120937. /*
  120938. ** Increment the reference count of node p.
  120939. */
  120940. static void nodeReference(RtreeNode *p){
  120941. if( p ){
  120942. p->nRef++;
  120943. }
  120944. }
  120945. /*
  120946. ** Clear the content of node p (set all bytes to 0x00).
  120947. */
  120948. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  120949. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  120950. p->isDirty = 1;
  120951. }
  120952. /*
  120953. ** Given a node number iNode, return the corresponding key to use
  120954. ** in the Rtree.aHash table.
  120955. */
  120956. static int nodeHash(i64 iNode){
  120957. return (
  120958. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  120959. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  120960. ) % HASHSIZE;
  120961. }
  120962. /*
  120963. ** Search the node hash table for node iNode. If found, return a pointer
  120964. ** to it. Otherwise, return 0.
  120965. */
  120966. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  120967. RtreeNode *p;
  120968. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  120969. return p;
  120970. }
  120971. /*
  120972. ** Add node pNode to the node hash table.
  120973. */
  120974. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  120975. int iHash;
  120976. assert( pNode->pNext==0 );
  120977. iHash = nodeHash(pNode->iNode);
  120978. pNode->pNext = pRtree->aHash[iHash];
  120979. pRtree->aHash[iHash] = pNode;
  120980. }
  120981. /*
  120982. ** Remove node pNode from the node hash table.
  120983. */
  120984. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  120985. RtreeNode **pp;
  120986. if( pNode->iNode!=0 ){
  120987. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  120988. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  120989. *pp = pNode->pNext;
  120990. pNode->pNext = 0;
  120991. }
  120992. }
  120993. /*
  120994. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  120995. ** indicating that node has not yet been assigned a node number. It is
  120996. ** assigned a node number when nodeWrite() is called to write the
  120997. ** node contents out to the database.
  120998. */
  120999. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  121000. RtreeNode *pNode;
  121001. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  121002. if( pNode ){
  121003. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  121004. pNode->zData = (u8 *)&pNode[1];
  121005. pNode->nRef = 1;
  121006. pNode->pParent = pParent;
  121007. pNode->isDirty = 1;
  121008. nodeReference(pParent);
  121009. }
  121010. return pNode;
  121011. }
  121012. /*
  121013. ** Obtain a reference to an r-tree node.
  121014. */
  121015. static int
  121016. nodeAcquire(
  121017. Rtree *pRtree, /* R-tree structure */
  121018. i64 iNode, /* Node number to load */
  121019. RtreeNode *pParent, /* Either the parent node or NULL */
  121020. RtreeNode **ppNode /* OUT: Acquired node */
  121021. ){
  121022. int rc;
  121023. int rc2 = SQLITE_OK;
  121024. RtreeNode *pNode;
  121025. /* Check if the requested node is already in the hash table. If so,
  121026. ** increase its reference count and return it.
  121027. */
  121028. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  121029. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  121030. if( pParent && !pNode->pParent ){
  121031. nodeReference(pParent);
  121032. pNode->pParent = pParent;
  121033. }
  121034. pNode->nRef++;
  121035. *ppNode = pNode;
  121036. return SQLITE_OK;
  121037. }
  121038. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  121039. rc = sqlite3_step(pRtree->pReadNode);
  121040. if( rc==SQLITE_ROW ){
  121041. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  121042. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  121043. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  121044. if( !pNode ){
  121045. rc2 = SQLITE_NOMEM;
  121046. }else{
  121047. pNode->pParent = pParent;
  121048. pNode->zData = (u8 *)&pNode[1];
  121049. pNode->nRef = 1;
  121050. pNode->iNode = iNode;
  121051. pNode->isDirty = 0;
  121052. pNode->pNext = 0;
  121053. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  121054. nodeReference(pParent);
  121055. }
  121056. }
  121057. }
  121058. rc = sqlite3_reset(pRtree->pReadNode);
  121059. if( rc==SQLITE_OK ) rc = rc2;
  121060. /* If the root node was just loaded, set pRtree->iDepth to the height
  121061. ** of the r-tree structure. A height of zero means all data is stored on
  121062. ** the root node. A height of one means the children of the root node
  121063. ** are the leaves, and so on. If the depth as specified on the root node
  121064. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  121065. */
  121066. if( pNode && iNode==1 ){
  121067. pRtree->iDepth = readInt16(pNode->zData);
  121068. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  121069. rc = SQLITE_CORRUPT_VTAB;
  121070. }
  121071. }
  121072. /* If no error has occurred so far, check if the "number of entries"
  121073. ** field on the node is too large. If so, set the return code to
  121074. ** SQLITE_CORRUPT_VTAB.
  121075. */
  121076. if( pNode && rc==SQLITE_OK ){
  121077. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  121078. rc = SQLITE_CORRUPT_VTAB;
  121079. }
  121080. }
  121081. if( rc==SQLITE_OK ){
  121082. if( pNode!=0 ){
  121083. nodeHashInsert(pRtree, pNode);
  121084. }else{
  121085. rc = SQLITE_CORRUPT_VTAB;
  121086. }
  121087. *ppNode = pNode;
  121088. }else{
  121089. sqlite3_free(pNode);
  121090. *ppNode = 0;
  121091. }
  121092. return rc;
  121093. }
  121094. /*
  121095. ** Overwrite cell iCell of node pNode with the contents of pCell.
  121096. */
  121097. static void nodeOverwriteCell(
  121098. Rtree *pRtree,
  121099. RtreeNode *pNode,
  121100. RtreeCell *pCell,
  121101. int iCell
  121102. ){
  121103. int ii;
  121104. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  121105. p += writeInt64(p, pCell->iRowid);
  121106. for(ii=0; ii<(pRtree->nDim*2); ii++){
  121107. p += writeCoord(p, &pCell->aCoord[ii]);
  121108. }
  121109. pNode->isDirty = 1;
  121110. }
  121111. /*
  121112. ** Remove cell the cell with index iCell from node pNode.
  121113. */
  121114. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  121115. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  121116. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  121117. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  121118. memmove(pDst, pSrc, nByte);
  121119. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  121120. pNode->isDirty = 1;
  121121. }
  121122. /*
  121123. ** Insert the contents of cell pCell into node pNode. If the insert
  121124. ** is successful, return SQLITE_OK.
  121125. **
  121126. ** If there is not enough free space in pNode, return SQLITE_FULL.
  121127. */
  121128. static int
  121129. nodeInsertCell(
  121130. Rtree *pRtree,
  121131. RtreeNode *pNode,
  121132. RtreeCell *pCell
  121133. ){
  121134. int nCell; /* Current number of cells in pNode */
  121135. int nMaxCell; /* Maximum number of cells for pNode */
  121136. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  121137. nCell = NCELL(pNode);
  121138. assert( nCell<=nMaxCell );
  121139. if( nCell<nMaxCell ){
  121140. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  121141. writeInt16(&pNode->zData[2], nCell+1);
  121142. pNode->isDirty = 1;
  121143. }
  121144. return (nCell==nMaxCell);
  121145. }
  121146. /*
  121147. ** If the node is dirty, write it out to the database.
  121148. */
  121149. static int
  121150. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  121151. int rc = SQLITE_OK;
  121152. if( pNode->isDirty ){
  121153. sqlite3_stmt *p = pRtree->pWriteNode;
  121154. if( pNode->iNode ){
  121155. sqlite3_bind_int64(p, 1, pNode->iNode);
  121156. }else{
  121157. sqlite3_bind_null(p, 1);
  121158. }
  121159. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  121160. sqlite3_step(p);
  121161. pNode->isDirty = 0;
  121162. rc = sqlite3_reset(p);
  121163. if( pNode->iNode==0 && rc==SQLITE_OK ){
  121164. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  121165. nodeHashInsert(pRtree, pNode);
  121166. }
  121167. }
  121168. return rc;
  121169. }
  121170. /*
  121171. ** Release a reference to a node. If the node is dirty and the reference
  121172. ** count drops to zero, the node data is written to the database.
  121173. */
  121174. static int
  121175. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  121176. int rc = SQLITE_OK;
  121177. if( pNode ){
  121178. assert( pNode->nRef>0 );
  121179. pNode->nRef--;
  121180. if( pNode->nRef==0 ){
  121181. if( pNode->iNode==1 ){
  121182. pRtree->iDepth = -1;
  121183. }
  121184. if( pNode->pParent ){
  121185. rc = nodeRelease(pRtree, pNode->pParent);
  121186. }
  121187. if( rc==SQLITE_OK ){
  121188. rc = nodeWrite(pRtree, pNode);
  121189. }
  121190. nodeHashDelete(pRtree, pNode);
  121191. sqlite3_free(pNode);
  121192. }
  121193. }
  121194. return rc;
  121195. }
  121196. /*
  121197. ** Return the 64-bit integer value associated with cell iCell of
  121198. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  121199. ** an internal node, then the 64-bit integer is a child page number.
  121200. */
  121201. static i64 nodeGetRowid(
  121202. Rtree *pRtree,
  121203. RtreeNode *pNode,
  121204. int iCell
  121205. ){
  121206. assert( iCell<NCELL(pNode) );
  121207. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  121208. }
  121209. /*
  121210. ** Return coordinate iCoord from cell iCell in node pNode.
  121211. */
  121212. static void nodeGetCoord(
  121213. Rtree *pRtree,
  121214. RtreeNode *pNode,
  121215. int iCell,
  121216. int iCoord,
  121217. RtreeCoord *pCoord /* Space to write result to */
  121218. ){
  121219. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  121220. }
  121221. /*
  121222. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  121223. ** to by pCell with the results.
  121224. */
  121225. static void nodeGetCell(
  121226. Rtree *pRtree,
  121227. RtreeNode *pNode,
  121228. int iCell,
  121229. RtreeCell *pCell
  121230. ){
  121231. int ii;
  121232. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  121233. for(ii=0; ii<pRtree->nDim*2; ii++){
  121234. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  121235. }
  121236. }
  121237. /* Forward declaration for the function that does the work of
  121238. ** the virtual table module xCreate() and xConnect() methods.
  121239. */
  121240. static int rtreeInit(
  121241. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  121242. );
  121243. /*
  121244. ** Rtree virtual table module xCreate method.
  121245. */
  121246. static int rtreeCreate(
  121247. sqlite3 *db,
  121248. void *pAux,
  121249. int argc, const char *const*argv,
  121250. sqlite3_vtab **ppVtab,
  121251. char **pzErr
  121252. ){
  121253. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  121254. }
  121255. /*
  121256. ** Rtree virtual table module xConnect method.
  121257. */
  121258. static int rtreeConnect(
  121259. sqlite3 *db,
  121260. void *pAux,
  121261. int argc, const char *const*argv,
  121262. sqlite3_vtab **ppVtab,
  121263. char **pzErr
  121264. ){
  121265. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  121266. }
  121267. /*
  121268. ** Increment the r-tree reference count.
  121269. */
  121270. static void rtreeReference(Rtree *pRtree){
  121271. pRtree->nBusy++;
  121272. }
  121273. /*
  121274. ** Decrement the r-tree reference count. When the reference count reaches
  121275. ** zero the structure is deleted.
  121276. */
  121277. static void rtreeRelease(Rtree *pRtree){
  121278. pRtree->nBusy--;
  121279. if( pRtree->nBusy==0 ){
  121280. sqlite3_finalize(pRtree->pReadNode);
  121281. sqlite3_finalize(pRtree->pWriteNode);
  121282. sqlite3_finalize(pRtree->pDeleteNode);
  121283. sqlite3_finalize(pRtree->pReadRowid);
  121284. sqlite3_finalize(pRtree->pWriteRowid);
  121285. sqlite3_finalize(pRtree->pDeleteRowid);
  121286. sqlite3_finalize(pRtree->pReadParent);
  121287. sqlite3_finalize(pRtree->pWriteParent);
  121288. sqlite3_finalize(pRtree->pDeleteParent);
  121289. sqlite3_free(pRtree);
  121290. }
  121291. }
  121292. /*
  121293. ** Rtree virtual table module xDisconnect method.
  121294. */
  121295. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  121296. rtreeRelease((Rtree *)pVtab);
  121297. return SQLITE_OK;
  121298. }
  121299. /*
  121300. ** Rtree virtual table module xDestroy method.
  121301. */
  121302. static int rtreeDestroy(sqlite3_vtab *pVtab){
  121303. Rtree *pRtree = (Rtree *)pVtab;
  121304. int rc;
  121305. char *zCreate = sqlite3_mprintf(
  121306. "DROP TABLE '%q'.'%q_node';"
  121307. "DROP TABLE '%q'.'%q_rowid';"
  121308. "DROP TABLE '%q'.'%q_parent';",
  121309. pRtree->zDb, pRtree->zName,
  121310. pRtree->zDb, pRtree->zName,
  121311. pRtree->zDb, pRtree->zName
  121312. );
  121313. if( !zCreate ){
  121314. rc = SQLITE_NOMEM;
  121315. }else{
  121316. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  121317. sqlite3_free(zCreate);
  121318. }
  121319. if( rc==SQLITE_OK ){
  121320. rtreeRelease(pRtree);
  121321. }
  121322. return rc;
  121323. }
  121324. /*
  121325. ** Rtree virtual table module xOpen method.
  121326. */
  121327. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  121328. int rc = SQLITE_NOMEM;
  121329. RtreeCursor *pCsr;
  121330. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  121331. if( pCsr ){
  121332. memset(pCsr, 0, sizeof(RtreeCursor));
  121333. pCsr->base.pVtab = pVTab;
  121334. rc = SQLITE_OK;
  121335. }
  121336. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  121337. return rc;
  121338. }
  121339. /*
  121340. ** Free the RtreeCursor.aConstraint[] array and its contents.
  121341. */
  121342. static void freeCursorConstraints(RtreeCursor *pCsr){
  121343. if( pCsr->aConstraint ){
  121344. int i; /* Used to iterate through constraint array */
  121345. for(i=0; i<pCsr->nConstraint; i++){
  121346. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  121347. if( pGeom ){
  121348. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  121349. sqlite3_free(pGeom);
  121350. }
  121351. }
  121352. sqlite3_free(pCsr->aConstraint);
  121353. pCsr->aConstraint = 0;
  121354. }
  121355. }
  121356. /*
  121357. ** Rtree virtual table module xClose method.
  121358. */
  121359. static int rtreeClose(sqlite3_vtab_cursor *cur){
  121360. Rtree *pRtree = (Rtree *)(cur->pVtab);
  121361. int rc;
  121362. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121363. freeCursorConstraints(pCsr);
  121364. rc = nodeRelease(pRtree, pCsr->pNode);
  121365. sqlite3_free(pCsr);
  121366. return rc;
  121367. }
  121368. /*
  121369. ** Rtree virtual table module xEof method.
  121370. **
  121371. ** Return non-zero if the cursor does not currently point to a valid
  121372. ** record (i.e if the scan has finished), or zero otherwise.
  121373. */
  121374. static int rtreeEof(sqlite3_vtab_cursor *cur){
  121375. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121376. return (pCsr->pNode==0);
  121377. }
  121378. /*
  121379. ** The r-tree constraint passed as the second argument to this function is
  121380. ** guaranteed to be a MATCH constraint.
  121381. */
  121382. static int testRtreeGeom(
  121383. Rtree *pRtree, /* R-Tree object */
  121384. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  121385. RtreeCell *pCell, /* Cell to test */
  121386. int *pbRes /* OUT: Test result */
  121387. ){
  121388. int i;
  121389. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  121390. int nCoord = pRtree->nDim*2;
  121391. assert( pConstraint->op==RTREE_MATCH );
  121392. assert( pConstraint->pGeom );
  121393. for(i=0; i<nCoord; i++){
  121394. aCoord[i] = DCOORD(pCell->aCoord[i]);
  121395. }
  121396. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  121397. }
  121398. /*
  121399. ** Cursor pCursor currently points to a cell in a non-leaf page.
  121400. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  121401. ** (excluded) by the constraints in the pCursor->aConstraint[]
  121402. ** array, or false otherwise.
  121403. **
  121404. ** Return SQLITE_OK if successful or an SQLite error code if an error
  121405. ** occurs within a geometry callback.
  121406. */
  121407. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  121408. RtreeCell cell;
  121409. int ii;
  121410. int bRes = 0;
  121411. int rc = SQLITE_OK;
  121412. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  121413. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  121414. RtreeConstraint *p = &pCursor->aConstraint[ii];
  121415. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  121416. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  121417. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  121418. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  121419. );
  121420. switch( p->op ){
  121421. case RTREE_LE: case RTREE_LT:
  121422. bRes = p->rValue<cell_min;
  121423. break;
  121424. case RTREE_GE: case RTREE_GT:
  121425. bRes = p->rValue>cell_max;
  121426. break;
  121427. case RTREE_EQ:
  121428. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  121429. break;
  121430. default: {
  121431. assert( p->op==RTREE_MATCH );
  121432. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  121433. bRes = !bRes;
  121434. break;
  121435. }
  121436. }
  121437. }
  121438. *pbEof = bRes;
  121439. return rc;
  121440. }
  121441. /*
  121442. ** Test if the cell that cursor pCursor currently points to
  121443. ** would be filtered (excluded) by the constraints in the
  121444. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  121445. ** returning. If the cell is not filtered (excluded) by the constraints,
  121446. ** set pbEof to zero.
  121447. **
  121448. ** Return SQLITE_OK if successful or an SQLite error code if an error
  121449. ** occurs within a geometry callback.
  121450. **
  121451. ** This function assumes that the cell is part of a leaf node.
  121452. */
  121453. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  121454. RtreeCell cell;
  121455. int ii;
  121456. *pbEof = 0;
  121457. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  121458. for(ii=0; ii<pCursor->nConstraint; ii++){
  121459. RtreeConstraint *p = &pCursor->aConstraint[ii];
  121460. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  121461. int res;
  121462. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  121463. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  121464. );
  121465. switch( p->op ){
  121466. case RTREE_LE: res = (coord<=p->rValue); break;
  121467. case RTREE_LT: res = (coord<p->rValue); break;
  121468. case RTREE_GE: res = (coord>=p->rValue); break;
  121469. case RTREE_GT: res = (coord>p->rValue); break;
  121470. case RTREE_EQ: res = (coord==p->rValue); break;
  121471. default: {
  121472. int rc;
  121473. assert( p->op==RTREE_MATCH );
  121474. rc = testRtreeGeom(pRtree, p, &cell, &res);
  121475. if( rc!=SQLITE_OK ){
  121476. return rc;
  121477. }
  121478. break;
  121479. }
  121480. }
  121481. if( !res ){
  121482. *pbEof = 1;
  121483. return SQLITE_OK;
  121484. }
  121485. }
  121486. return SQLITE_OK;
  121487. }
  121488. /*
  121489. ** Cursor pCursor currently points at a node that heads a sub-tree of
  121490. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  121491. ** to point to the left-most cell of the sub-tree that matches the
  121492. ** configured constraints.
  121493. */
  121494. static int descendToCell(
  121495. Rtree *pRtree,
  121496. RtreeCursor *pCursor,
  121497. int iHeight,
  121498. int *pEof /* OUT: Set to true if cannot descend */
  121499. ){
  121500. int isEof;
  121501. int rc;
  121502. int ii;
  121503. RtreeNode *pChild;
  121504. sqlite3_int64 iRowid;
  121505. RtreeNode *pSavedNode = pCursor->pNode;
  121506. int iSavedCell = pCursor->iCell;
  121507. assert( iHeight>=0 );
  121508. if( iHeight==0 ){
  121509. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  121510. }else{
  121511. rc = testRtreeCell(pRtree, pCursor, &isEof);
  121512. }
  121513. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  121514. goto descend_to_cell_out;
  121515. }
  121516. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  121517. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  121518. if( rc!=SQLITE_OK ){
  121519. goto descend_to_cell_out;
  121520. }
  121521. nodeRelease(pRtree, pCursor->pNode);
  121522. pCursor->pNode = pChild;
  121523. isEof = 1;
  121524. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  121525. pCursor->iCell = ii;
  121526. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  121527. if( rc!=SQLITE_OK ){
  121528. goto descend_to_cell_out;
  121529. }
  121530. }
  121531. if( isEof ){
  121532. assert( pCursor->pNode==pChild );
  121533. nodeReference(pSavedNode);
  121534. nodeRelease(pRtree, pChild);
  121535. pCursor->pNode = pSavedNode;
  121536. pCursor->iCell = iSavedCell;
  121537. }
  121538. descend_to_cell_out:
  121539. *pEof = isEof;
  121540. return rc;
  121541. }
  121542. /*
  121543. ** One of the cells in node pNode is guaranteed to have a 64-bit
  121544. ** integer value equal to iRowid. Return the index of this cell.
  121545. */
  121546. static int nodeRowidIndex(
  121547. Rtree *pRtree,
  121548. RtreeNode *pNode,
  121549. i64 iRowid,
  121550. int *piIndex
  121551. ){
  121552. int ii;
  121553. int nCell = NCELL(pNode);
  121554. for(ii=0; ii<nCell; ii++){
  121555. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  121556. *piIndex = ii;
  121557. return SQLITE_OK;
  121558. }
  121559. }
  121560. return SQLITE_CORRUPT_VTAB;
  121561. }
  121562. /*
  121563. ** Return the index of the cell containing a pointer to node pNode
  121564. ** in its parent. If pNode is the root node, return -1.
  121565. */
  121566. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  121567. RtreeNode *pParent = pNode->pParent;
  121568. if( pParent ){
  121569. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  121570. }
  121571. *piIndex = -1;
  121572. return SQLITE_OK;
  121573. }
  121574. /*
  121575. ** Rtree virtual table module xNext method.
  121576. */
  121577. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  121578. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  121579. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121580. int rc = SQLITE_OK;
  121581. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  121582. ** already at EOF. It is against the rules to call the xNext() method of
  121583. ** a cursor that has already reached EOF.
  121584. */
  121585. assert( pCsr->pNode );
  121586. if( pCsr->iStrategy==1 ){
  121587. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  121588. nodeRelease(pRtree, pCsr->pNode);
  121589. pCsr->pNode = 0;
  121590. }else{
  121591. /* Move to the next entry that matches the configured constraints. */
  121592. int iHeight = 0;
  121593. while( pCsr->pNode ){
  121594. RtreeNode *pNode = pCsr->pNode;
  121595. int nCell = NCELL(pNode);
  121596. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  121597. int isEof;
  121598. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  121599. if( rc!=SQLITE_OK || !isEof ){
  121600. return rc;
  121601. }
  121602. }
  121603. pCsr->pNode = pNode->pParent;
  121604. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  121605. if( rc!=SQLITE_OK ){
  121606. return rc;
  121607. }
  121608. nodeReference(pCsr->pNode);
  121609. nodeRelease(pRtree, pNode);
  121610. iHeight++;
  121611. }
  121612. }
  121613. return rc;
  121614. }
  121615. /*
  121616. ** Rtree virtual table module xRowid method.
  121617. */
  121618. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  121619. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  121620. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121621. assert(pCsr->pNode);
  121622. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  121623. return SQLITE_OK;
  121624. }
  121625. /*
  121626. ** Rtree virtual table module xColumn method.
  121627. */
  121628. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  121629. Rtree *pRtree = (Rtree *)cur->pVtab;
  121630. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121631. if( i==0 ){
  121632. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  121633. sqlite3_result_int64(ctx, iRowid);
  121634. }else{
  121635. RtreeCoord c;
  121636. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  121637. #ifndef SQLITE_RTREE_INT_ONLY
  121638. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  121639. sqlite3_result_double(ctx, c.f);
  121640. }else
  121641. #endif
  121642. {
  121643. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  121644. sqlite3_result_int(ctx, c.i);
  121645. }
  121646. }
  121647. return SQLITE_OK;
  121648. }
  121649. /*
  121650. ** Use nodeAcquire() to obtain the leaf node containing the record with
  121651. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  121652. ** return SQLITE_OK. If there is no such record in the table, set
  121653. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  121654. ** to zero and return an SQLite error code.
  121655. */
  121656. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  121657. int rc;
  121658. *ppLeaf = 0;
  121659. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  121660. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  121661. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  121662. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  121663. sqlite3_reset(pRtree->pReadRowid);
  121664. }else{
  121665. rc = sqlite3_reset(pRtree->pReadRowid);
  121666. }
  121667. return rc;
  121668. }
  121669. /*
  121670. ** This function is called to configure the RtreeConstraint object passed
  121671. ** as the second argument for a MATCH constraint. The value passed as the
  121672. ** first argument to this function is the right-hand operand to the MATCH
  121673. ** operator.
  121674. */
  121675. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  121676. RtreeMatchArg *p;
  121677. sqlite3_rtree_geometry *pGeom;
  121678. int nBlob;
  121679. /* Check that value is actually a blob. */
  121680. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  121681. /* Check that the blob is roughly the right size. */
  121682. nBlob = sqlite3_value_bytes(pValue);
  121683. if( nBlob<(int)sizeof(RtreeMatchArg)
  121684. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  121685. ){
  121686. return SQLITE_ERROR;
  121687. }
  121688. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  121689. sizeof(sqlite3_rtree_geometry) + nBlob
  121690. );
  121691. if( !pGeom ) return SQLITE_NOMEM;
  121692. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  121693. p = (RtreeMatchArg *)&pGeom[1];
  121694. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  121695. if( p->magic!=RTREE_GEOMETRY_MAGIC
  121696. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  121697. ){
  121698. sqlite3_free(pGeom);
  121699. return SQLITE_ERROR;
  121700. }
  121701. pGeom->pContext = p->pContext;
  121702. pGeom->nParam = p->nParam;
  121703. pGeom->aParam = p->aParam;
  121704. pCons->xGeom = p->xGeom;
  121705. pCons->pGeom = pGeom;
  121706. return SQLITE_OK;
  121707. }
  121708. /*
  121709. ** Rtree virtual table module xFilter method.
  121710. */
  121711. static int rtreeFilter(
  121712. sqlite3_vtab_cursor *pVtabCursor,
  121713. int idxNum, const char *idxStr,
  121714. int argc, sqlite3_value **argv
  121715. ){
  121716. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  121717. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121718. RtreeNode *pRoot = 0;
  121719. int ii;
  121720. int rc = SQLITE_OK;
  121721. rtreeReference(pRtree);
  121722. freeCursorConstraints(pCsr);
  121723. pCsr->iStrategy = idxNum;
  121724. if( idxNum==1 ){
  121725. /* Special case - lookup by rowid. */
  121726. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  121727. i64 iRowid = sqlite3_value_int64(argv[0]);
  121728. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  121729. pCsr->pNode = pLeaf;
  121730. if( pLeaf ){
  121731. assert( rc==SQLITE_OK );
  121732. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  121733. }
  121734. }else{
  121735. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  121736. ** with the configured constraints.
  121737. */
  121738. if( argc>0 ){
  121739. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  121740. pCsr->nConstraint = argc;
  121741. if( !pCsr->aConstraint ){
  121742. rc = SQLITE_NOMEM;
  121743. }else{
  121744. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  121745. assert( (idxStr==0 && argc==0)
  121746. || (idxStr && (int)strlen(idxStr)==argc*2) );
  121747. for(ii=0; ii<argc; ii++){
  121748. RtreeConstraint *p = &pCsr->aConstraint[ii];
  121749. p->op = idxStr[ii*2];
  121750. p->iCoord = idxStr[ii*2+1]-'a';
  121751. if( p->op==RTREE_MATCH ){
  121752. /* A MATCH operator. The right-hand-side must be a blob that
  121753. ** can be cast into an RtreeMatchArg object. One created using
  121754. ** an sqlite3_rtree_geometry_callback() SQL user function.
  121755. */
  121756. rc = deserializeGeometry(argv[ii], p);
  121757. if( rc!=SQLITE_OK ){
  121758. break;
  121759. }
  121760. }else{
  121761. #ifdef SQLITE_RTREE_INT_ONLY
  121762. p->rValue = sqlite3_value_int64(argv[ii]);
  121763. #else
  121764. p->rValue = sqlite3_value_double(argv[ii]);
  121765. #endif
  121766. }
  121767. }
  121768. }
  121769. }
  121770. if( rc==SQLITE_OK ){
  121771. pCsr->pNode = 0;
  121772. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  121773. }
  121774. if( rc==SQLITE_OK ){
  121775. int isEof = 1;
  121776. int nCell = NCELL(pRoot);
  121777. pCsr->pNode = pRoot;
  121778. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  121779. assert( pCsr->pNode==pRoot );
  121780. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  121781. if( !isEof ){
  121782. break;
  121783. }
  121784. }
  121785. if( rc==SQLITE_OK && isEof ){
  121786. assert( pCsr->pNode==pRoot );
  121787. nodeRelease(pRtree, pRoot);
  121788. pCsr->pNode = 0;
  121789. }
  121790. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  121791. }
  121792. }
  121793. rtreeRelease(pRtree);
  121794. return rc;
  121795. }
  121796. /*
  121797. ** Rtree virtual table module xBestIndex method. There are three
  121798. ** table scan strategies to choose from (in order from most to
  121799. ** least desirable):
  121800. **
  121801. ** idxNum idxStr Strategy
  121802. ** ------------------------------------------------
  121803. ** 1 Unused Direct lookup by rowid.
  121804. ** 2 See below R-tree query or full-table scan.
  121805. ** ------------------------------------------------
  121806. **
  121807. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  121808. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  121809. ** constraint used. The first two bytes of idxStr correspond to
  121810. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  121811. ** (argvIndex==1) etc.
  121812. **
  121813. ** The first of each pair of bytes in idxStr identifies the constraint
  121814. ** operator as follows:
  121815. **
  121816. ** Operator Byte Value
  121817. ** ----------------------
  121818. ** = 0x41 ('A')
  121819. ** <= 0x42 ('B')
  121820. ** < 0x43 ('C')
  121821. ** >= 0x44 ('D')
  121822. ** > 0x45 ('E')
  121823. ** MATCH 0x46 ('F')
  121824. ** ----------------------
  121825. **
  121826. ** The second of each pair of bytes identifies the coordinate column
  121827. ** to which the constraint applies. The leftmost coordinate column
  121828. ** is 'a', the second from the left 'b' etc.
  121829. */
  121830. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  121831. int rc = SQLITE_OK;
  121832. int ii;
  121833. int iIdx = 0;
  121834. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  121835. memset(zIdxStr, 0, sizeof(zIdxStr));
  121836. UNUSED_PARAMETER(tab);
  121837. assert( pIdxInfo->idxStr==0 );
  121838. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  121839. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  121840. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  121841. /* We have an equality constraint on the rowid. Use strategy 1. */
  121842. int jj;
  121843. for(jj=0; jj<ii; jj++){
  121844. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  121845. pIdxInfo->aConstraintUsage[jj].omit = 0;
  121846. }
  121847. pIdxInfo->idxNum = 1;
  121848. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  121849. pIdxInfo->aConstraintUsage[jj].omit = 1;
  121850. /* This strategy involves a two rowid lookups on an B-Tree structures
  121851. ** and then a linear search of an R-Tree node. This should be
  121852. ** considered almost as quick as a direct rowid lookup (for which
  121853. ** sqlite uses an internal cost of 0.0).
  121854. */
  121855. pIdxInfo->estimatedCost = 10.0;
  121856. return SQLITE_OK;
  121857. }
  121858. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  121859. u8 op;
  121860. switch( p->op ){
  121861. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  121862. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  121863. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  121864. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  121865. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  121866. default:
  121867. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  121868. op = RTREE_MATCH;
  121869. break;
  121870. }
  121871. zIdxStr[iIdx++] = op;
  121872. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  121873. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  121874. pIdxInfo->aConstraintUsage[ii].omit = 1;
  121875. }
  121876. }
  121877. pIdxInfo->idxNum = 2;
  121878. pIdxInfo->needToFreeIdxStr = 1;
  121879. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  121880. return SQLITE_NOMEM;
  121881. }
  121882. assert( iIdx>=0 );
  121883. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  121884. return rc;
  121885. }
  121886. /*
  121887. ** Return the N-dimensional volumn of the cell stored in *p.
  121888. */
  121889. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  121890. RtreeDValue area = (RtreeDValue)1;
  121891. int ii;
  121892. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121893. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  121894. }
  121895. return area;
  121896. }
  121897. /*
  121898. ** Return the margin length of cell p. The margin length is the sum
  121899. ** of the objects size in each dimension.
  121900. */
  121901. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  121902. RtreeDValue margin = (RtreeDValue)0;
  121903. int ii;
  121904. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121905. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  121906. }
  121907. return margin;
  121908. }
  121909. /*
  121910. ** Store the union of cells p1 and p2 in p1.
  121911. */
  121912. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  121913. int ii;
  121914. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  121915. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121916. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  121917. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  121918. }
  121919. }else{
  121920. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121921. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  121922. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  121923. }
  121924. }
  121925. }
  121926. /*
  121927. ** Return true if the area covered by p2 is a subset of the area covered
  121928. ** by p1. False otherwise.
  121929. */
  121930. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  121931. int ii;
  121932. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  121933. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121934. RtreeCoord *a1 = &p1->aCoord[ii];
  121935. RtreeCoord *a2 = &p2->aCoord[ii];
  121936. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  121937. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  121938. ){
  121939. return 0;
  121940. }
  121941. }
  121942. return 1;
  121943. }
  121944. /*
  121945. ** Return the amount cell p would grow by if it were unioned with pCell.
  121946. */
  121947. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  121948. RtreeDValue area;
  121949. RtreeCell cell;
  121950. memcpy(&cell, p, sizeof(RtreeCell));
  121951. area = cellArea(pRtree, &cell);
  121952. cellUnion(pRtree, &cell, pCell);
  121953. return (cellArea(pRtree, &cell)-area);
  121954. }
  121955. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  121956. static RtreeDValue cellOverlap(
  121957. Rtree *pRtree,
  121958. RtreeCell *p,
  121959. RtreeCell *aCell,
  121960. int nCell,
  121961. int iExclude
  121962. ){
  121963. int ii;
  121964. RtreeDValue overlap = 0.0;
  121965. for(ii=0; ii<nCell; ii++){
  121966. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  121967. if( ii!=iExclude )
  121968. #else
  121969. assert( iExclude==-1 );
  121970. UNUSED_PARAMETER(iExclude);
  121971. #endif
  121972. {
  121973. int jj;
  121974. RtreeDValue o = (RtreeDValue)1;
  121975. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  121976. RtreeDValue x1, x2;
  121977. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  121978. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  121979. if( x2<x1 ){
  121980. o = 0.0;
  121981. break;
  121982. }else{
  121983. o = o * (x2-x1);
  121984. }
  121985. }
  121986. overlap += o;
  121987. }
  121988. }
  121989. return overlap;
  121990. }
  121991. #endif
  121992. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  121993. static RtreeDValue cellOverlapEnlargement(
  121994. Rtree *pRtree,
  121995. RtreeCell *p,
  121996. RtreeCell *pInsert,
  121997. RtreeCell *aCell,
  121998. int nCell,
  121999. int iExclude
  122000. ){
  122001. RtreeDValue before, after;
  122002. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  122003. cellUnion(pRtree, p, pInsert);
  122004. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  122005. return (after-before);
  122006. }
  122007. #endif
  122008. /*
  122009. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  122010. ** ChooseSubTree in r*tree terminology.
  122011. */
  122012. static int ChooseLeaf(
  122013. Rtree *pRtree, /* Rtree table */
  122014. RtreeCell *pCell, /* Cell to insert into rtree */
  122015. int iHeight, /* Height of sub-tree rooted at pCell */
  122016. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  122017. ){
  122018. int rc;
  122019. int ii;
  122020. RtreeNode *pNode;
  122021. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  122022. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  122023. int iCell;
  122024. sqlite3_int64 iBest = 0;
  122025. RtreeDValue fMinGrowth = 0.0;
  122026. RtreeDValue fMinArea = 0.0;
  122027. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122028. RtreeDValue fMinOverlap = 0.0;
  122029. RtreeDValue overlap;
  122030. #endif
  122031. int nCell = NCELL(pNode);
  122032. RtreeCell cell;
  122033. RtreeNode *pChild;
  122034. RtreeCell *aCell = 0;
  122035. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122036. if( ii==(pRtree->iDepth-1) ){
  122037. int jj;
  122038. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  122039. if( !aCell ){
  122040. rc = SQLITE_NOMEM;
  122041. nodeRelease(pRtree, pNode);
  122042. pNode = 0;
  122043. continue;
  122044. }
  122045. for(jj=0; jj<nCell; jj++){
  122046. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  122047. }
  122048. }
  122049. #endif
  122050. /* Select the child node which will be enlarged the least if pCell
  122051. ** is inserted into it. Resolve ties by choosing the entry with
  122052. ** the smallest area.
  122053. */
  122054. for(iCell=0; iCell<nCell; iCell++){
  122055. int bBest = 0;
  122056. RtreeDValue growth;
  122057. RtreeDValue area;
  122058. nodeGetCell(pRtree, pNode, iCell, &cell);
  122059. growth = cellGrowth(pRtree, &cell, pCell);
  122060. area = cellArea(pRtree, &cell);
  122061. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122062. if( ii==(pRtree->iDepth-1) ){
  122063. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  122064. }else{
  122065. overlap = 0.0;
  122066. }
  122067. if( (iCell==0)
  122068. || (overlap<fMinOverlap)
  122069. || (overlap==fMinOverlap && growth<fMinGrowth)
  122070. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  122071. ){
  122072. bBest = 1;
  122073. fMinOverlap = overlap;
  122074. }
  122075. #else
  122076. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  122077. bBest = 1;
  122078. }
  122079. #endif
  122080. if( bBest ){
  122081. fMinGrowth = growth;
  122082. fMinArea = area;
  122083. iBest = cell.iRowid;
  122084. }
  122085. }
  122086. sqlite3_free(aCell);
  122087. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  122088. nodeRelease(pRtree, pNode);
  122089. pNode = pChild;
  122090. }
  122091. *ppLeaf = pNode;
  122092. return rc;
  122093. }
  122094. /*
  122095. ** A cell with the same content as pCell has just been inserted into
  122096. ** the node pNode. This function updates the bounding box cells in
  122097. ** all ancestor elements.
  122098. */
  122099. static int AdjustTree(
  122100. Rtree *pRtree, /* Rtree table */
  122101. RtreeNode *pNode, /* Adjust ancestry of this node. */
  122102. RtreeCell *pCell /* This cell was just inserted */
  122103. ){
  122104. RtreeNode *p = pNode;
  122105. while( p->pParent ){
  122106. RtreeNode *pParent = p->pParent;
  122107. RtreeCell cell;
  122108. int iCell;
  122109. if( nodeParentIndex(pRtree, p, &iCell) ){
  122110. return SQLITE_CORRUPT_VTAB;
  122111. }
  122112. nodeGetCell(pRtree, pParent, iCell, &cell);
  122113. if( !cellContains(pRtree, &cell, pCell) ){
  122114. cellUnion(pRtree, &cell, pCell);
  122115. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  122116. }
  122117. p = pParent;
  122118. }
  122119. return SQLITE_OK;
  122120. }
  122121. /*
  122122. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  122123. */
  122124. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  122125. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  122126. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  122127. sqlite3_step(pRtree->pWriteRowid);
  122128. return sqlite3_reset(pRtree->pWriteRowid);
  122129. }
  122130. /*
  122131. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  122132. */
  122133. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  122134. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  122135. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  122136. sqlite3_step(pRtree->pWriteParent);
  122137. return sqlite3_reset(pRtree->pWriteParent);
  122138. }
  122139. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  122140. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  122141. /*
  122142. ** Implementation of the linear variant of the PickNext() function from
  122143. ** Guttman[84].
  122144. */
  122145. static RtreeCell *LinearPickNext(
  122146. Rtree *pRtree,
  122147. RtreeCell *aCell,
  122148. int nCell,
  122149. RtreeCell *pLeftBox,
  122150. RtreeCell *pRightBox,
  122151. int *aiUsed
  122152. ){
  122153. int ii;
  122154. for(ii=0; aiUsed[ii]; ii++);
  122155. aiUsed[ii] = 1;
  122156. return &aCell[ii];
  122157. }
  122158. /*
  122159. ** Implementation of the linear variant of the PickSeeds() function from
  122160. ** Guttman[84].
  122161. */
  122162. static void LinearPickSeeds(
  122163. Rtree *pRtree,
  122164. RtreeCell *aCell,
  122165. int nCell,
  122166. int *piLeftSeed,
  122167. int *piRightSeed
  122168. ){
  122169. int i;
  122170. int iLeftSeed = 0;
  122171. int iRightSeed = 1;
  122172. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  122173. /* Pick two "seed" cells from the array of cells. The algorithm used
  122174. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  122175. ** indices of the two seed cells in the array are stored in local
  122176. ** variables iLeftSeek and iRightSeed.
  122177. */
  122178. for(i=0; i<pRtree->nDim; i++){
  122179. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  122180. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  122181. RtreeDValue x3 = x1;
  122182. RtreeDValue x4 = x2;
  122183. int jj;
  122184. int iCellLeft = 0;
  122185. int iCellRight = 0;
  122186. for(jj=1; jj<nCell; jj++){
  122187. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  122188. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  122189. if( left<x1 ) x1 = left;
  122190. if( right>x4 ) x4 = right;
  122191. if( left>x3 ){
  122192. x3 = left;
  122193. iCellRight = jj;
  122194. }
  122195. if( right<x2 ){
  122196. x2 = right;
  122197. iCellLeft = jj;
  122198. }
  122199. }
  122200. if( x4!=x1 ){
  122201. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  122202. if( normalwidth>maxNormalInnerWidth ){
  122203. iLeftSeed = iCellLeft;
  122204. iRightSeed = iCellRight;
  122205. }
  122206. }
  122207. }
  122208. *piLeftSeed = iLeftSeed;
  122209. *piRightSeed = iRightSeed;
  122210. }
  122211. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  122212. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  122213. /*
  122214. ** Implementation of the quadratic variant of the PickNext() function from
  122215. ** Guttman[84].
  122216. */
  122217. static RtreeCell *QuadraticPickNext(
  122218. Rtree *pRtree,
  122219. RtreeCell *aCell,
  122220. int nCell,
  122221. RtreeCell *pLeftBox,
  122222. RtreeCell *pRightBox,
  122223. int *aiUsed
  122224. ){
  122225. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  122226. int iSelect = -1;
  122227. RtreeDValue fDiff;
  122228. int ii;
  122229. for(ii=0; ii<nCell; ii++){
  122230. if( aiUsed[ii]==0 ){
  122231. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  122232. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  122233. RtreeDValue diff = FABS(right-left);
  122234. if( iSelect<0 || diff>fDiff ){
  122235. fDiff = diff;
  122236. iSelect = ii;
  122237. }
  122238. }
  122239. }
  122240. aiUsed[iSelect] = 1;
  122241. return &aCell[iSelect];
  122242. }
  122243. /*
  122244. ** Implementation of the quadratic variant of the PickSeeds() function from
  122245. ** Guttman[84].
  122246. */
  122247. static void QuadraticPickSeeds(
  122248. Rtree *pRtree,
  122249. RtreeCell *aCell,
  122250. int nCell,
  122251. int *piLeftSeed,
  122252. int *piRightSeed
  122253. ){
  122254. int ii;
  122255. int jj;
  122256. int iLeftSeed = 0;
  122257. int iRightSeed = 1;
  122258. RtreeDValue fWaste = 0.0;
  122259. for(ii=0; ii<nCell; ii++){
  122260. for(jj=ii+1; jj<nCell; jj++){
  122261. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  122262. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  122263. RtreeDValue waste = growth - right;
  122264. if( waste>fWaste ){
  122265. iLeftSeed = ii;
  122266. iRightSeed = jj;
  122267. fWaste = waste;
  122268. }
  122269. }
  122270. }
  122271. *piLeftSeed = iLeftSeed;
  122272. *piRightSeed = iRightSeed;
  122273. }
  122274. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  122275. /*
  122276. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  122277. ** nIdx. The aIdx array contains the set of integers from 0 to
  122278. ** (nIdx-1) in no particular order. This function sorts the values
  122279. ** in aIdx according to the indexed values in aDistance. For
  122280. ** example, assuming the inputs:
  122281. **
  122282. ** aIdx = { 0, 1, 2, 3 }
  122283. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  122284. **
  122285. ** this function sets the aIdx array to contain:
  122286. **
  122287. ** aIdx = { 0, 1, 2, 3 }
  122288. **
  122289. ** The aSpare array is used as temporary working space by the
  122290. ** sorting algorithm.
  122291. */
  122292. static void SortByDistance(
  122293. int *aIdx,
  122294. int nIdx,
  122295. RtreeDValue *aDistance,
  122296. int *aSpare
  122297. ){
  122298. if( nIdx>1 ){
  122299. int iLeft = 0;
  122300. int iRight = 0;
  122301. int nLeft = nIdx/2;
  122302. int nRight = nIdx-nLeft;
  122303. int *aLeft = aIdx;
  122304. int *aRight = &aIdx[nLeft];
  122305. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  122306. SortByDistance(aRight, nRight, aDistance, aSpare);
  122307. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  122308. aLeft = aSpare;
  122309. while( iLeft<nLeft || iRight<nRight ){
  122310. if( iLeft==nLeft ){
  122311. aIdx[iLeft+iRight] = aRight[iRight];
  122312. iRight++;
  122313. }else if( iRight==nRight ){
  122314. aIdx[iLeft+iRight] = aLeft[iLeft];
  122315. iLeft++;
  122316. }else{
  122317. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  122318. RtreeDValue fRight = aDistance[aRight[iRight]];
  122319. if( fLeft<fRight ){
  122320. aIdx[iLeft+iRight] = aLeft[iLeft];
  122321. iLeft++;
  122322. }else{
  122323. aIdx[iLeft+iRight] = aRight[iRight];
  122324. iRight++;
  122325. }
  122326. }
  122327. }
  122328. #if 0
  122329. /* Check that the sort worked */
  122330. {
  122331. int jj;
  122332. for(jj=1; jj<nIdx; jj++){
  122333. RtreeDValue left = aDistance[aIdx[jj-1]];
  122334. RtreeDValue right = aDistance[aIdx[jj]];
  122335. assert( left<=right );
  122336. }
  122337. }
  122338. #endif
  122339. }
  122340. }
  122341. /*
  122342. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  122343. ** nIdx. The aIdx array contains the set of integers from 0 to
  122344. ** (nIdx-1) in no particular order. This function sorts the values
  122345. ** in aIdx according to dimension iDim of the cells in aCell. The
  122346. ** minimum value of dimension iDim is considered first, the
  122347. ** maximum used to break ties.
  122348. **
  122349. ** The aSpare array is used as temporary working space by the
  122350. ** sorting algorithm.
  122351. */
  122352. static void SortByDimension(
  122353. Rtree *pRtree,
  122354. int *aIdx,
  122355. int nIdx,
  122356. int iDim,
  122357. RtreeCell *aCell,
  122358. int *aSpare
  122359. ){
  122360. if( nIdx>1 ){
  122361. int iLeft = 0;
  122362. int iRight = 0;
  122363. int nLeft = nIdx/2;
  122364. int nRight = nIdx-nLeft;
  122365. int *aLeft = aIdx;
  122366. int *aRight = &aIdx[nLeft];
  122367. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  122368. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  122369. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  122370. aLeft = aSpare;
  122371. while( iLeft<nLeft || iRight<nRight ){
  122372. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  122373. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  122374. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  122375. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  122376. if( (iLeft!=nLeft) && ((iRight==nRight)
  122377. || (xleft1<xright1)
  122378. || (xleft1==xright1 && xleft2<xright2)
  122379. )){
  122380. aIdx[iLeft+iRight] = aLeft[iLeft];
  122381. iLeft++;
  122382. }else{
  122383. aIdx[iLeft+iRight] = aRight[iRight];
  122384. iRight++;
  122385. }
  122386. }
  122387. #if 0
  122388. /* Check that the sort worked */
  122389. {
  122390. int jj;
  122391. for(jj=1; jj<nIdx; jj++){
  122392. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  122393. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  122394. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  122395. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  122396. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  122397. }
  122398. }
  122399. #endif
  122400. }
  122401. }
  122402. #if VARIANT_RSTARTREE_SPLIT
  122403. /*
  122404. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  122405. */
  122406. static int splitNodeStartree(
  122407. Rtree *pRtree,
  122408. RtreeCell *aCell,
  122409. int nCell,
  122410. RtreeNode *pLeft,
  122411. RtreeNode *pRight,
  122412. RtreeCell *pBboxLeft,
  122413. RtreeCell *pBboxRight
  122414. ){
  122415. int **aaSorted;
  122416. int *aSpare;
  122417. int ii;
  122418. int iBestDim = 0;
  122419. int iBestSplit = 0;
  122420. RtreeDValue fBestMargin = 0.0;
  122421. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  122422. aaSorted = (int **)sqlite3_malloc(nByte);
  122423. if( !aaSorted ){
  122424. return SQLITE_NOMEM;
  122425. }
  122426. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  122427. memset(aaSorted, 0, nByte);
  122428. for(ii=0; ii<pRtree->nDim; ii++){
  122429. int jj;
  122430. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  122431. for(jj=0; jj<nCell; jj++){
  122432. aaSorted[ii][jj] = jj;
  122433. }
  122434. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  122435. }
  122436. for(ii=0; ii<pRtree->nDim; ii++){
  122437. RtreeDValue margin = 0.0;
  122438. RtreeDValue fBestOverlap = 0.0;
  122439. RtreeDValue fBestArea = 0.0;
  122440. int iBestLeft = 0;
  122441. int nLeft;
  122442. for(
  122443. nLeft=RTREE_MINCELLS(pRtree);
  122444. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  122445. nLeft++
  122446. ){
  122447. RtreeCell left;
  122448. RtreeCell right;
  122449. int kk;
  122450. RtreeDValue overlap;
  122451. RtreeDValue area;
  122452. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  122453. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  122454. for(kk=1; kk<(nCell-1); kk++){
  122455. if( kk<nLeft ){
  122456. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  122457. }else{
  122458. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  122459. }
  122460. }
  122461. margin += cellMargin(pRtree, &left);
  122462. margin += cellMargin(pRtree, &right);
  122463. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  122464. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  122465. if( (nLeft==RTREE_MINCELLS(pRtree))
  122466. || (overlap<fBestOverlap)
  122467. || (overlap==fBestOverlap && area<fBestArea)
  122468. ){
  122469. iBestLeft = nLeft;
  122470. fBestOverlap = overlap;
  122471. fBestArea = area;
  122472. }
  122473. }
  122474. if( ii==0 || margin<fBestMargin ){
  122475. iBestDim = ii;
  122476. fBestMargin = margin;
  122477. iBestSplit = iBestLeft;
  122478. }
  122479. }
  122480. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  122481. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  122482. for(ii=0; ii<nCell; ii++){
  122483. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  122484. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  122485. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  122486. nodeInsertCell(pRtree, pTarget, pCell);
  122487. cellUnion(pRtree, pBbox, pCell);
  122488. }
  122489. sqlite3_free(aaSorted);
  122490. return SQLITE_OK;
  122491. }
  122492. #endif
  122493. #if VARIANT_GUTTMAN_SPLIT
  122494. /*
  122495. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  122496. */
  122497. static int splitNodeGuttman(
  122498. Rtree *pRtree,
  122499. RtreeCell *aCell,
  122500. int nCell,
  122501. RtreeNode *pLeft,
  122502. RtreeNode *pRight,
  122503. RtreeCell *pBboxLeft,
  122504. RtreeCell *pBboxRight
  122505. ){
  122506. int iLeftSeed = 0;
  122507. int iRightSeed = 1;
  122508. int *aiUsed;
  122509. int i;
  122510. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  122511. if( !aiUsed ){
  122512. return SQLITE_NOMEM;
  122513. }
  122514. memset(aiUsed, 0, sizeof(int)*nCell);
  122515. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  122516. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  122517. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  122518. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  122519. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  122520. aiUsed[iLeftSeed] = 1;
  122521. aiUsed[iRightSeed] = 1;
  122522. for(i=nCell-2; i>0; i--){
  122523. RtreeCell *pNext;
  122524. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  122525. RtreeDValue diff =
  122526. cellGrowth(pRtree, pBboxLeft, pNext) -
  122527. cellGrowth(pRtree, pBboxRight, pNext)
  122528. ;
  122529. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  122530. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  122531. ){
  122532. nodeInsertCell(pRtree, pRight, pNext);
  122533. cellUnion(pRtree, pBboxRight, pNext);
  122534. }else{
  122535. nodeInsertCell(pRtree, pLeft, pNext);
  122536. cellUnion(pRtree, pBboxLeft, pNext);
  122537. }
  122538. }
  122539. sqlite3_free(aiUsed);
  122540. return SQLITE_OK;
  122541. }
  122542. #endif
  122543. static int updateMapping(
  122544. Rtree *pRtree,
  122545. i64 iRowid,
  122546. RtreeNode *pNode,
  122547. int iHeight
  122548. ){
  122549. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  122550. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  122551. if( iHeight>0 ){
  122552. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  122553. if( pChild ){
  122554. nodeRelease(pRtree, pChild->pParent);
  122555. nodeReference(pNode);
  122556. pChild->pParent = pNode;
  122557. }
  122558. }
  122559. return xSetMapping(pRtree, iRowid, pNode->iNode);
  122560. }
  122561. static int SplitNode(
  122562. Rtree *pRtree,
  122563. RtreeNode *pNode,
  122564. RtreeCell *pCell,
  122565. int iHeight
  122566. ){
  122567. int i;
  122568. int newCellIsRight = 0;
  122569. int rc = SQLITE_OK;
  122570. int nCell = NCELL(pNode);
  122571. RtreeCell *aCell;
  122572. int *aiUsed;
  122573. RtreeNode *pLeft = 0;
  122574. RtreeNode *pRight = 0;
  122575. RtreeCell leftbbox;
  122576. RtreeCell rightbbox;
  122577. /* Allocate an array and populate it with a copy of pCell and
  122578. ** all cells from node pLeft. Then zero the original node.
  122579. */
  122580. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  122581. if( !aCell ){
  122582. rc = SQLITE_NOMEM;
  122583. goto splitnode_out;
  122584. }
  122585. aiUsed = (int *)&aCell[nCell+1];
  122586. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  122587. for(i=0; i<nCell; i++){
  122588. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  122589. }
  122590. nodeZero(pRtree, pNode);
  122591. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  122592. nCell++;
  122593. if( pNode->iNode==1 ){
  122594. pRight = nodeNew(pRtree, pNode);
  122595. pLeft = nodeNew(pRtree, pNode);
  122596. pRtree->iDepth++;
  122597. pNode->isDirty = 1;
  122598. writeInt16(pNode->zData, pRtree->iDepth);
  122599. }else{
  122600. pLeft = pNode;
  122601. pRight = nodeNew(pRtree, pLeft->pParent);
  122602. nodeReference(pLeft);
  122603. }
  122604. if( !pLeft || !pRight ){
  122605. rc = SQLITE_NOMEM;
  122606. goto splitnode_out;
  122607. }
  122608. memset(pLeft->zData, 0, pRtree->iNodeSize);
  122609. memset(pRight->zData, 0, pRtree->iNodeSize);
  122610. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  122611. if( rc!=SQLITE_OK ){
  122612. goto splitnode_out;
  122613. }
  122614. /* Ensure both child nodes have node numbers assigned to them by calling
  122615. ** nodeWrite(). Node pRight always needs a node number, as it was created
  122616. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  122617. ** In this case avoid the all to nodeWrite().
  122618. */
  122619. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  122620. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  122621. ){
  122622. goto splitnode_out;
  122623. }
  122624. rightbbox.iRowid = pRight->iNode;
  122625. leftbbox.iRowid = pLeft->iNode;
  122626. if( pNode->iNode==1 ){
  122627. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  122628. if( rc!=SQLITE_OK ){
  122629. goto splitnode_out;
  122630. }
  122631. }else{
  122632. RtreeNode *pParent = pLeft->pParent;
  122633. int iCell;
  122634. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  122635. if( rc==SQLITE_OK ){
  122636. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  122637. rc = AdjustTree(pRtree, pParent, &leftbbox);
  122638. }
  122639. if( rc!=SQLITE_OK ){
  122640. goto splitnode_out;
  122641. }
  122642. }
  122643. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  122644. goto splitnode_out;
  122645. }
  122646. for(i=0; i<NCELL(pRight); i++){
  122647. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  122648. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  122649. if( iRowid==pCell->iRowid ){
  122650. newCellIsRight = 1;
  122651. }
  122652. if( rc!=SQLITE_OK ){
  122653. goto splitnode_out;
  122654. }
  122655. }
  122656. if( pNode->iNode==1 ){
  122657. for(i=0; i<NCELL(pLeft); i++){
  122658. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  122659. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  122660. if( rc!=SQLITE_OK ){
  122661. goto splitnode_out;
  122662. }
  122663. }
  122664. }else if( newCellIsRight==0 ){
  122665. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  122666. }
  122667. if( rc==SQLITE_OK ){
  122668. rc = nodeRelease(pRtree, pRight);
  122669. pRight = 0;
  122670. }
  122671. if( rc==SQLITE_OK ){
  122672. rc = nodeRelease(pRtree, pLeft);
  122673. pLeft = 0;
  122674. }
  122675. splitnode_out:
  122676. nodeRelease(pRtree, pRight);
  122677. nodeRelease(pRtree, pLeft);
  122678. sqlite3_free(aCell);
  122679. return rc;
  122680. }
  122681. /*
  122682. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  122683. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  122684. ** the pLeaf->pParent chain all the way up to the root node.
  122685. **
  122686. ** This operation is required when a row is deleted (or updated - an update
  122687. ** is implemented as a delete followed by an insert). SQLite provides the
  122688. ** rowid of the row to delete, which can be used to find the leaf on which
  122689. ** the entry resides (argument pLeaf). Once the leaf is located, this
  122690. ** function is called to determine its ancestry.
  122691. */
  122692. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  122693. int rc = SQLITE_OK;
  122694. RtreeNode *pChild = pLeaf;
  122695. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  122696. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  122697. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  122698. rc = sqlite3_step(pRtree->pReadParent);
  122699. if( rc==SQLITE_ROW ){
  122700. RtreeNode *pTest; /* Used to test for reference loops */
  122701. i64 iNode; /* Node number of parent node */
  122702. /* Before setting pChild->pParent, test that we are not creating a
  122703. ** loop of references (as we would if, say, pChild==pParent). We don't
  122704. ** want to do this as it leads to a memory leak when trying to delete
  122705. ** the referenced counted node structures.
  122706. */
  122707. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  122708. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  122709. if( !pTest ){
  122710. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  122711. }
  122712. }
  122713. rc = sqlite3_reset(pRtree->pReadParent);
  122714. if( rc==SQLITE_OK ) rc = rc2;
  122715. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  122716. pChild = pChild->pParent;
  122717. }
  122718. return rc;
  122719. }
  122720. static int deleteCell(Rtree *, RtreeNode *, int, int);
  122721. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  122722. int rc;
  122723. int rc2;
  122724. RtreeNode *pParent = 0;
  122725. int iCell;
  122726. assert( pNode->nRef==1 );
  122727. /* Remove the entry in the parent cell. */
  122728. rc = nodeParentIndex(pRtree, pNode, &iCell);
  122729. if( rc==SQLITE_OK ){
  122730. pParent = pNode->pParent;
  122731. pNode->pParent = 0;
  122732. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  122733. }
  122734. rc2 = nodeRelease(pRtree, pParent);
  122735. if( rc==SQLITE_OK ){
  122736. rc = rc2;
  122737. }
  122738. if( rc!=SQLITE_OK ){
  122739. return rc;
  122740. }
  122741. /* Remove the xxx_node entry. */
  122742. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  122743. sqlite3_step(pRtree->pDeleteNode);
  122744. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  122745. return rc;
  122746. }
  122747. /* Remove the xxx_parent entry. */
  122748. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  122749. sqlite3_step(pRtree->pDeleteParent);
  122750. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  122751. return rc;
  122752. }
  122753. /* Remove the node from the in-memory hash table and link it into
  122754. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  122755. */
  122756. nodeHashDelete(pRtree, pNode);
  122757. pNode->iNode = iHeight;
  122758. pNode->pNext = pRtree->pDeleted;
  122759. pNode->nRef++;
  122760. pRtree->pDeleted = pNode;
  122761. return SQLITE_OK;
  122762. }
  122763. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  122764. RtreeNode *pParent = pNode->pParent;
  122765. int rc = SQLITE_OK;
  122766. if( pParent ){
  122767. int ii;
  122768. int nCell = NCELL(pNode);
  122769. RtreeCell box; /* Bounding box for pNode */
  122770. nodeGetCell(pRtree, pNode, 0, &box);
  122771. for(ii=1; ii<nCell; ii++){
  122772. RtreeCell cell;
  122773. nodeGetCell(pRtree, pNode, ii, &cell);
  122774. cellUnion(pRtree, &box, &cell);
  122775. }
  122776. box.iRowid = pNode->iNode;
  122777. rc = nodeParentIndex(pRtree, pNode, &ii);
  122778. if( rc==SQLITE_OK ){
  122779. nodeOverwriteCell(pRtree, pParent, &box, ii);
  122780. rc = fixBoundingBox(pRtree, pParent);
  122781. }
  122782. }
  122783. return rc;
  122784. }
  122785. /*
  122786. ** Delete the cell at index iCell of node pNode. After removing the
  122787. ** cell, adjust the r-tree data structure if required.
  122788. */
  122789. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  122790. RtreeNode *pParent;
  122791. int rc;
  122792. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  122793. return rc;
  122794. }
  122795. /* Remove the cell from the node. This call just moves bytes around
  122796. ** the in-memory node image, so it cannot fail.
  122797. */
  122798. nodeDeleteCell(pRtree, pNode, iCell);
  122799. /* If the node is not the tree root and now has less than the minimum
  122800. ** number of cells, remove it from the tree. Otherwise, update the
  122801. ** cell in the parent node so that it tightly contains the updated
  122802. ** node.
  122803. */
  122804. pParent = pNode->pParent;
  122805. assert( pParent || pNode->iNode==1 );
  122806. if( pParent ){
  122807. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  122808. rc = removeNode(pRtree, pNode, iHeight);
  122809. }else{
  122810. rc = fixBoundingBox(pRtree, pNode);
  122811. }
  122812. }
  122813. return rc;
  122814. }
  122815. static int Reinsert(
  122816. Rtree *pRtree,
  122817. RtreeNode *pNode,
  122818. RtreeCell *pCell,
  122819. int iHeight
  122820. ){
  122821. int *aOrder;
  122822. int *aSpare;
  122823. RtreeCell *aCell;
  122824. RtreeDValue *aDistance;
  122825. int nCell;
  122826. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  122827. int iDim;
  122828. int ii;
  122829. int rc = SQLITE_OK;
  122830. int n;
  122831. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  122832. nCell = NCELL(pNode)+1;
  122833. n = (nCell+1)&(~1);
  122834. /* Allocate the buffers used by this operation. The allocation is
  122835. ** relinquished before this function returns.
  122836. */
  122837. aCell = (RtreeCell *)sqlite3_malloc(n * (
  122838. sizeof(RtreeCell) + /* aCell array */
  122839. sizeof(int) + /* aOrder array */
  122840. sizeof(int) + /* aSpare array */
  122841. sizeof(RtreeDValue) /* aDistance array */
  122842. ));
  122843. if( !aCell ){
  122844. return SQLITE_NOMEM;
  122845. }
  122846. aOrder = (int *)&aCell[n];
  122847. aSpare = (int *)&aOrder[n];
  122848. aDistance = (RtreeDValue *)&aSpare[n];
  122849. for(ii=0; ii<nCell; ii++){
  122850. if( ii==(nCell-1) ){
  122851. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  122852. }else{
  122853. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  122854. }
  122855. aOrder[ii] = ii;
  122856. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122857. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  122858. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  122859. }
  122860. }
  122861. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122862. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  122863. }
  122864. for(ii=0; ii<nCell; ii++){
  122865. aDistance[ii] = 0.0;
  122866. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122867. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  122868. DCOORD(aCell[ii].aCoord[iDim*2]));
  122869. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  122870. }
  122871. }
  122872. SortByDistance(aOrder, nCell, aDistance, aSpare);
  122873. nodeZero(pRtree, pNode);
  122874. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  122875. RtreeCell *p = &aCell[aOrder[ii]];
  122876. nodeInsertCell(pRtree, pNode, p);
  122877. if( p->iRowid==pCell->iRowid ){
  122878. if( iHeight==0 ){
  122879. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  122880. }else{
  122881. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  122882. }
  122883. }
  122884. }
  122885. if( rc==SQLITE_OK ){
  122886. rc = fixBoundingBox(pRtree, pNode);
  122887. }
  122888. for(; rc==SQLITE_OK && ii<nCell; ii++){
  122889. /* Find a node to store this cell in. pNode->iNode currently contains
  122890. ** the height of the sub-tree headed by the cell.
  122891. */
  122892. RtreeNode *pInsert;
  122893. RtreeCell *p = &aCell[aOrder[ii]];
  122894. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  122895. if( rc==SQLITE_OK ){
  122896. int rc2;
  122897. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  122898. rc2 = nodeRelease(pRtree, pInsert);
  122899. if( rc==SQLITE_OK ){
  122900. rc = rc2;
  122901. }
  122902. }
  122903. }
  122904. sqlite3_free(aCell);
  122905. return rc;
  122906. }
  122907. /*
  122908. ** Insert cell pCell into node pNode. Node pNode is the head of a
  122909. ** subtree iHeight high (leaf nodes have iHeight==0).
  122910. */
  122911. static int rtreeInsertCell(
  122912. Rtree *pRtree,
  122913. RtreeNode *pNode,
  122914. RtreeCell *pCell,
  122915. int iHeight
  122916. ){
  122917. int rc = SQLITE_OK;
  122918. if( iHeight>0 ){
  122919. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  122920. if( pChild ){
  122921. nodeRelease(pRtree, pChild->pParent);
  122922. nodeReference(pNode);
  122923. pChild->pParent = pNode;
  122924. }
  122925. }
  122926. if( nodeInsertCell(pRtree, pNode, pCell) ){
  122927. #if VARIANT_RSTARTREE_REINSERT
  122928. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  122929. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  122930. }else{
  122931. pRtree->iReinsertHeight = iHeight;
  122932. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  122933. }
  122934. #else
  122935. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  122936. #endif
  122937. }else{
  122938. rc = AdjustTree(pRtree, pNode, pCell);
  122939. if( rc==SQLITE_OK ){
  122940. if( iHeight==0 ){
  122941. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  122942. }else{
  122943. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  122944. }
  122945. }
  122946. }
  122947. return rc;
  122948. }
  122949. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  122950. int ii;
  122951. int rc = SQLITE_OK;
  122952. int nCell = NCELL(pNode);
  122953. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  122954. RtreeNode *pInsert;
  122955. RtreeCell cell;
  122956. nodeGetCell(pRtree, pNode, ii, &cell);
  122957. /* Find a node to store this cell in. pNode->iNode currently contains
  122958. ** the height of the sub-tree headed by the cell.
  122959. */
  122960. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  122961. if( rc==SQLITE_OK ){
  122962. int rc2;
  122963. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  122964. rc2 = nodeRelease(pRtree, pInsert);
  122965. if( rc==SQLITE_OK ){
  122966. rc = rc2;
  122967. }
  122968. }
  122969. }
  122970. return rc;
  122971. }
  122972. /*
  122973. ** Select a currently unused rowid for a new r-tree record.
  122974. */
  122975. static int newRowid(Rtree *pRtree, i64 *piRowid){
  122976. int rc;
  122977. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  122978. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  122979. sqlite3_step(pRtree->pWriteRowid);
  122980. rc = sqlite3_reset(pRtree->pWriteRowid);
  122981. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  122982. return rc;
  122983. }
  122984. /*
  122985. ** Remove the entry with rowid=iDelete from the r-tree structure.
  122986. */
  122987. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  122988. int rc; /* Return code */
  122989. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  122990. int iCell; /* Index of iDelete cell in pLeaf */
  122991. RtreeNode *pRoot; /* Root node of rtree structure */
  122992. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  122993. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  122994. /* Obtain a reference to the leaf node that contains the entry
  122995. ** about to be deleted.
  122996. */
  122997. if( rc==SQLITE_OK ){
  122998. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  122999. }
  123000. /* Delete the cell in question from the leaf node. */
  123001. if( rc==SQLITE_OK ){
  123002. int rc2;
  123003. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  123004. if( rc==SQLITE_OK ){
  123005. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  123006. }
  123007. rc2 = nodeRelease(pRtree, pLeaf);
  123008. if( rc==SQLITE_OK ){
  123009. rc = rc2;
  123010. }
  123011. }
  123012. /* Delete the corresponding entry in the <rtree>_rowid table. */
  123013. if( rc==SQLITE_OK ){
  123014. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  123015. sqlite3_step(pRtree->pDeleteRowid);
  123016. rc = sqlite3_reset(pRtree->pDeleteRowid);
  123017. }
  123018. /* Check if the root node now has exactly one child. If so, remove
  123019. ** it, schedule the contents of the child for reinsertion and
  123020. ** reduce the tree height by one.
  123021. **
  123022. ** This is equivalent to copying the contents of the child into
  123023. ** the root node (the operation that Gutman's paper says to perform
  123024. ** in this scenario).
  123025. */
  123026. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  123027. int rc2;
  123028. RtreeNode *pChild;
  123029. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  123030. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  123031. if( rc==SQLITE_OK ){
  123032. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  123033. }
  123034. rc2 = nodeRelease(pRtree, pChild);
  123035. if( rc==SQLITE_OK ) rc = rc2;
  123036. if( rc==SQLITE_OK ){
  123037. pRtree->iDepth--;
  123038. writeInt16(pRoot->zData, pRtree->iDepth);
  123039. pRoot->isDirty = 1;
  123040. }
  123041. }
  123042. /* Re-insert the contents of any underfull nodes removed from the tree. */
  123043. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  123044. if( rc==SQLITE_OK ){
  123045. rc = reinsertNodeContent(pRtree, pLeaf);
  123046. }
  123047. pRtree->pDeleted = pLeaf->pNext;
  123048. sqlite3_free(pLeaf);
  123049. }
  123050. /* Release the reference to the root node. */
  123051. if( rc==SQLITE_OK ){
  123052. rc = nodeRelease(pRtree, pRoot);
  123053. }else{
  123054. nodeRelease(pRtree, pRoot);
  123055. }
  123056. return rc;
  123057. }
  123058. /*
  123059. ** Rounding constants for float->double conversion.
  123060. */
  123061. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  123062. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  123063. #if !defined(SQLITE_RTREE_INT_ONLY)
  123064. /*
  123065. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  123066. ** while taking care to round toward negative or positive, respectively.
  123067. */
  123068. static RtreeValue rtreeValueDown(sqlite3_value *v){
  123069. double d = sqlite3_value_double(v);
  123070. float f = (float)d;
  123071. if( f>d ){
  123072. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  123073. }
  123074. return f;
  123075. }
  123076. static RtreeValue rtreeValueUp(sqlite3_value *v){
  123077. double d = sqlite3_value_double(v);
  123078. float f = (float)d;
  123079. if( f<d ){
  123080. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  123081. }
  123082. return f;
  123083. }
  123084. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  123085. /*
  123086. ** The xUpdate method for rtree module virtual tables.
  123087. */
  123088. static int rtreeUpdate(
  123089. sqlite3_vtab *pVtab,
  123090. int nData,
  123091. sqlite3_value **azData,
  123092. sqlite_int64 *pRowid
  123093. ){
  123094. Rtree *pRtree = (Rtree *)pVtab;
  123095. int rc = SQLITE_OK;
  123096. RtreeCell cell; /* New cell to insert if nData>1 */
  123097. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  123098. rtreeReference(pRtree);
  123099. assert(nData>=1);
  123100. /* Constraint handling. A write operation on an r-tree table may return
  123101. ** SQLITE_CONSTRAINT for two reasons:
  123102. **
  123103. ** 1. A duplicate rowid value, or
  123104. ** 2. The supplied data violates the "x2>=x1" constraint.
  123105. **
  123106. ** In the first case, if the conflict-handling mode is REPLACE, then
  123107. ** the conflicting row can be removed before proceeding. In the second
  123108. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  123109. ** conflict-handling mode specified by the user.
  123110. */
  123111. if( nData>1 ){
  123112. int ii;
  123113. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  123114. assert( nData==(pRtree->nDim*2 + 3) );
  123115. #ifndef SQLITE_RTREE_INT_ONLY
  123116. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  123117. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  123118. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  123119. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  123120. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  123121. rc = SQLITE_CONSTRAINT;
  123122. goto constraint;
  123123. }
  123124. }
  123125. }else
  123126. #endif
  123127. {
  123128. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  123129. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  123130. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  123131. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  123132. rc = SQLITE_CONSTRAINT;
  123133. goto constraint;
  123134. }
  123135. }
  123136. }
  123137. /* If a rowid value was supplied, check if it is already present in
  123138. ** the table. If so, the constraint has failed. */
  123139. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  123140. cell.iRowid = sqlite3_value_int64(azData[2]);
  123141. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  123142. || sqlite3_value_int64(azData[0])!=cell.iRowid
  123143. ){
  123144. int steprc;
  123145. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  123146. steprc = sqlite3_step(pRtree->pReadRowid);
  123147. rc = sqlite3_reset(pRtree->pReadRowid);
  123148. if( SQLITE_ROW==steprc ){
  123149. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  123150. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  123151. }else{
  123152. rc = SQLITE_CONSTRAINT;
  123153. goto constraint;
  123154. }
  123155. }
  123156. }
  123157. bHaveRowid = 1;
  123158. }
  123159. }
  123160. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  123161. ** record to delete from the r-tree table. The following block does
  123162. ** just that.
  123163. */
  123164. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  123165. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  123166. }
  123167. /* If the azData[] array contains more than one element, elements
  123168. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  123169. ** the r-tree structure.
  123170. */
  123171. if( rc==SQLITE_OK && nData>1 ){
  123172. /* Insert the new record into the r-tree */
  123173. RtreeNode *pLeaf = 0;
  123174. /* Figure out the rowid of the new row. */
  123175. if( bHaveRowid==0 ){
  123176. rc = newRowid(pRtree, &cell.iRowid);
  123177. }
  123178. *pRowid = cell.iRowid;
  123179. if( rc==SQLITE_OK ){
  123180. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  123181. }
  123182. if( rc==SQLITE_OK ){
  123183. int rc2;
  123184. pRtree->iReinsertHeight = -1;
  123185. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  123186. rc2 = nodeRelease(pRtree, pLeaf);
  123187. if( rc==SQLITE_OK ){
  123188. rc = rc2;
  123189. }
  123190. }
  123191. }
  123192. constraint:
  123193. rtreeRelease(pRtree);
  123194. return rc;
  123195. }
  123196. /*
  123197. ** The xRename method for rtree module virtual tables.
  123198. */
  123199. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  123200. Rtree *pRtree = (Rtree *)pVtab;
  123201. int rc = SQLITE_NOMEM;
  123202. char *zSql = sqlite3_mprintf(
  123203. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  123204. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  123205. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  123206. , pRtree->zDb, pRtree->zName, zNewName
  123207. , pRtree->zDb, pRtree->zName, zNewName
  123208. , pRtree->zDb, pRtree->zName, zNewName
  123209. );
  123210. if( zSql ){
  123211. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  123212. sqlite3_free(zSql);
  123213. }
  123214. return rc;
  123215. }
  123216. static sqlite3_module rtreeModule = {
  123217. 0, /* iVersion */
  123218. rtreeCreate, /* xCreate - create a table */
  123219. rtreeConnect, /* xConnect - connect to an existing table */
  123220. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  123221. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  123222. rtreeDestroy, /* xDestroy - Drop a table */
  123223. rtreeOpen, /* xOpen - open a cursor */
  123224. rtreeClose, /* xClose - close a cursor */
  123225. rtreeFilter, /* xFilter - configure scan constraints */
  123226. rtreeNext, /* xNext - advance a cursor */
  123227. rtreeEof, /* xEof */
  123228. rtreeColumn, /* xColumn - read data */
  123229. rtreeRowid, /* xRowid - read data */
  123230. rtreeUpdate, /* xUpdate - write data */
  123231. 0, /* xBegin - begin transaction */
  123232. 0, /* xSync - sync transaction */
  123233. 0, /* xCommit - commit transaction */
  123234. 0, /* xRollback - rollback transaction */
  123235. 0, /* xFindFunction - function overloading */
  123236. rtreeRename, /* xRename - rename the table */
  123237. 0, /* xSavepoint */
  123238. 0, /* xRelease */
  123239. 0 /* xRollbackTo */
  123240. };
  123241. static int rtreeSqlInit(
  123242. Rtree *pRtree,
  123243. sqlite3 *db,
  123244. const char *zDb,
  123245. const char *zPrefix,
  123246. int isCreate
  123247. ){
  123248. int rc = SQLITE_OK;
  123249. #define N_STATEMENT 9
  123250. static const char *azSql[N_STATEMENT] = {
  123251. /* Read and write the xxx_node table */
  123252. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  123253. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  123254. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  123255. /* Read and write the xxx_rowid table */
  123256. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  123257. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  123258. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  123259. /* Read and write the xxx_parent table */
  123260. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  123261. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  123262. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  123263. };
  123264. sqlite3_stmt **appStmt[N_STATEMENT];
  123265. int i;
  123266. pRtree->db = db;
  123267. if( isCreate ){
  123268. char *zCreate = sqlite3_mprintf(
  123269. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  123270. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  123271. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  123272. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  123273. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  123274. );
  123275. if( !zCreate ){
  123276. return SQLITE_NOMEM;
  123277. }
  123278. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  123279. sqlite3_free(zCreate);
  123280. if( rc!=SQLITE_OK ){
  123281. return rc;
  123282. }
  123283. }
  123284. appStmt[0] = &pRtree->pReadNode;
  123285. appStmt[1] = &pRtree->pWriteNode;
  123286. appStmt[2] = &pRtree->pDeleteNode;
  123287. appStmt[3] = &pRtree->pReadRowid;
  123288. appStmt[4] = &pRtree->pWriteRowid;
  123289. appStmt[5] = &pRtree->pDeleteRowid;
  123290. appStmt[6] = &pRtree->pReadParent;
  123291. appStmt[7] = &pRtree->pWriteParent;
  123292. appStmt[8] = &pRtree->pDeleteParent;
  123293. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  123294. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  123295. if( zSql ){
  123296. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  123297. }else{
  123298. rc = SQLITE_NOMEM;
  123299. }
  123300. sqlite3_free(zSql);
  123301. }
  123302. return rc;
  123303. }
  123304. /*
  123305. ** The second argument to this function contains the text of an SQL statement
  123306. ** that returns a single integer value. The statement is compiled and executed
  123307. ** using database connection db. If successful, the integer value returned
  123308. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  123309. ** code is returned and the value of *piVal after returning is not defined.
  123310. */
  123311. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  123312. int rc = SQLITE_NOMEM;
  123313. if( zSql ){
  123314. sqlite3_stmt *pStmt = 0;
  123315. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  123316. if( rc==SQLITE_OK ){
  123317. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  123318. *piVal = sqlite3_column_int(pStmt, 0);
  123319. }
  123320. rc = sqlite3_finalize(pStmt);
  123321. }
  123322. }
  123323. return rc;
  123324. }
  123325. /*
  123326. ** This function is called from within the xConnect() or xCreate() method to
  123327. ** determine the node-size used by the rtree table being created or connected
  123328. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  123329. ** Otherwise, an SQLite error code is returned.
  123330. **
  123331. ** If this function is being called as part of an xConnect(), then the rtree
  123332. ** table already exists. In this case the node-size is determined by inspecting
  123333. ** the root node of the tree.
  123334. **
  123335. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  123336. ** This ensures that each node is stored on a single database page. If the
  123337. ** database page-size is so large that more than RTREE_MAXCELLS entries
  123338. ** would fit in a single node, use a smaller node-size.
  123339. */
  123340. static int getNodeSize(
  123341. sqlite3 *db, /* Database handle */
  123342. Rtree *pRtree, /* Rtree handle */
  123343. int isCreate, /* True for xCreate, false for xConnect */
  123344. char **pzErr /* OUT: Error message, if any */
  123345. ){
  123346. int rc;
  123347. char *zSql;
  123348. if( isCreate ){
  123349. int iPageSize = 0;
  123350. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  123351. rc = getIntFromStmt(db, zSql, &iPageSize);
  123352. if( rc==SQLITE_OK ){
  123353. pRtree->iNodeSize = iPageSize-64;
  123354. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  123355. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  123356. }
  123357. }else{
  123358. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123359. }
  123360. }else{
  123361. zSql = sqlite3_mprintf(
  123362. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  123363. pRtree->zDb, pRtree->zName
  123364. );
  123365. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  123366. if( rc!=SQLITE_OK ){
  123367. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123368. }
  123369. }
  123370. sqlite3_free(zSql);
  123371. return rc;
  123372. }
  123373. /*
  123374. ** This function is the implementation of both the xConnect and xCreate
  123375. ** methods of the r-tree virtual table.
  123376. **
  123377. ** argv[0] -> module name
  123378. ** argv[1] -> database name
  123379. ** argv[2] -> table name
  123380. ** argv[...] -> column names...
  123381. */
  123382. static int rtreeInit(
  123383. sqlite3 *db, /* Database connection */
  123384. void *pAux, /* One of the RTREE_COORD_* constants */
  123385. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  123386. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  123387. char **pzErr, /* OUT: Error message, if any */
  123388. int isCreate /* True for xCreate, false for xConnect */
  123389. ){
  123390. int rc = SQLITE_OK;
  123391. Rtree *pRtree;
  123392. int nDb; /* Length of string argv[1] */
  123393. int nName; /* Length of string argv[2] */
  123394. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  123395. const char *aErrMsg[] = {
  123396. 0, /* 0 */
  123397. "Wrong number of columns for an rtree table", /* 1 */
  123398. "Too few columns for an rtree table", /* 2 */
  123399. "Too many columns for an rtree table" /* 3 */
  123400. };
  123401. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  123402. if( aErrMsg[iErr] ){
  123403. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  123404. return SQLITE_ERROR;
  123405. }
  123406. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  123407. /* Allocate the sqlite3_vtab structure */
  123408. nDb = (int)strlen(argv[1]);
  123409. nName = (int)strlen(argv[2]);
  123410. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  123411. if( !pRtree ){
  123412. return SQLITE_NOMEM;
  123413. }
  123414. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  123415. pRtree->nBusy = 1;
  123416. pRtree->base.pModule = &rtreeModule;
  123417. pRtree->zDb = (char *)&pRtree[1];
  123418. pRtree->zName = &pRtree->zDb[nDb+1];
  123419. pRtree->nDim = (argc-4)/2;
  123420. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  123421. pRtree->eCoordType = eCoordType;
  123422. memcpy(pRtree->zDb, argv[1], nDb);
  123423. memcpy(pRtree->zName, argv[2], nName);
  123424. /* Figure out the node size to use. */
  123425. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  123426. /* Create/Connect to the underlying relational database schema. If
  123427. ** that is successful, call sqlite3_declare_vtab() to configure
  123428. ** the r-tree table schema.
  123429. */
  123430. if( rc==SQLITE_OK ){
  123431. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  123432. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123433. }else{
  123434. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  123435. char *zTmp;
  123436. int ii;
  123437. for(ii=4; zSql && ii<argc; ii++){
  123438. zTmp = zSql;
  123439. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  123440. sqlite3_free(zTmp);
  123441. }
  123442. if( zSql ){
  123443. zTmp = zSql;
  123444. zSql = sqlite3_mprintf("%s);", zTmp);
  123445. sqlite3_free(zTmp);
  123446. }
  123447. if( !zSql ){
  123448. rc = SQLITE_NOMEM;
  123449. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  123450. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123451. }
  123452. sqlite3_free(zSql);
  123453. }
  123454. }
  123455. if( rc==SQLITE_OK ){
  123456. *ppVtab = (sqlite3_vtab *)pRtree;
  123457. }else{
  123458. rtreeRelease(pRtree);
  123459. }
  123460. return rc;
  123461. }
  123462. /*
  123463. ** Implementation of a scalar function that decodes r-tree nodes to
  123464. ** human readable strings. This can be used for debugging and analysis.
  123465. **
  123466. ** The scalar function takes two arguments, a blob of data containing
  123467. ** an r-tree node, and the number of dimensions the r-tree indexes.
  123468. ** For a two-dimensional r-tree structure called "rt", to deserialize
  123469. ** all nodes, a statement like:
  123470. **
  123471. ** SELECT rtreenode(2, data) FROM rt_node;
  123472. **
  123473. ** The human readable string takes the form of a Tcl list with one
  123474. ** entry for each cell in the r-tree node. Each entry is itself a
  123475. ** list, containing the 8-byte rowid/pageno followed by the
  123476. ** <num-dimension>*2 coordinates.
  123477. */
  123478. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  123479. char *zText = 0;
  123480. RtreeNode node;
  123481. Rtree tree;
  123482. int ii;
  123483. UNUSED_PARAMETER(nArg);
  123484. memset(&node, 0, sizeof(RtreeNode));
  123485. memset(&tree, 0, sizeof(Rtree));
  123486. tree.nDim = sqlite3_value_int(apArg[0]);
  123487. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  123488. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  123489. for(ii=0; ii<NCELL(&node); ii++){
  123490. char zCell[512];
  123491. int nCell = 0;
  123492. RtreeCell cell;
  123493. int jj;
  123494. nodeGetCell(&tree, &node, ii, &cell);
  123495. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  123496. nCell = (int)strlen(zCell);
  123497. for(jj=0; jj<tree.nDim*2; jj++){
  123498. #ifndef SQLITE_RTREE_INT_ONLY
  123499. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  123500. (double)cell.aCoord[jj].f);
  123501. #else
  123502. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  123503. cell.aCoord[jj].i);
  123504. #endif
  123505. nCell = (int)strlen(zCell);
  123506. }
  123507. if( zText ){
  123508. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  123509. sqlite3_free(zText);
  123510. zText = zTextNew;
  123511. }else{
  123512. zText = sqlite3_mprintf("{%s}", zCell);
  123513. }
  123514. }
  123515. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  123516. }
  123517. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  123518. UNUSED_PARAMETER(nArg);
  123519. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  123520. || sqlite3_value_bytes(apArg[0])<2
  123521. ){
  123522. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  123523. }else{
  123524. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  123525. sqlite3_result_int(ctx, readInt16(zBlob));
  123526. }
  123527. }
  123528. /*
  123529. ** Register the r-tree module with database handle db. This creates the
  123530. ** virtual table module "rtree" and the debugging/analysis scalar
  123531. ** function "rtreenode".
  123532. */
  123533. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  123534. const int utf8 = SQLITE_UTF8;
  123535. int rc;
  123536. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  123537. if( rc==SQLITE_OK ){
  123538. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  123539. }
  123540. if( rc==SQLITE_OK ){
  123541. #ifdef SQLITE_RTREE_INT_ONLY
  123542. void *c = (void *)RTREE_COORD_INT32;
  123543. #else
  123544. void *c = (void *)RTREE_COORD_REAL32;
  123545. #endif
  123546. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  123547. }
  123548. if( rc==SQLITE_OK ){
  123549. void *c = (void *)RTREE_COORD_INT32;
  123550. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  123551. }
  123552. return rc;
  123553. }
  123554. /*
  123555. ** A version of sqlite3_free() that can be used as a callback. This is used
  123556. ** in two places - as the destructor for the blob value returned by the
  123557. ** invocation of a geometry function, and as the destructor for the geometry
  123558. ** functions themselves.
  123559. */
  123560. static void doSqlite3Free(void *p){
  123561. sqlite3_free(p);
  123562. }
  123563. /*
  123564. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  123565. ** scalar user function. This C function is the callback used for all such
  123566. ** registered SQL functions.
  123567. **
  123568. ** The scalar user functions return a blob that is interpreted by r-tree
  123569. ** table MATCH operators.
  123570. */
  123571. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  123572. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  123573. RtreeMatchArg *pBlob;
  123574. int nBlob;
  123575. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  123576. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  123577. if( !pBlob ){
  123578. sqlite3_result_error_nomem(ctx);
  123579. }else{
  123580. int i;
  123581. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  123582. pBlob->xGeom = pGeomCtx->xGeom;
  123583. pBlob->pContext = pGeomCtx->pContext;
  123584. pBlob->nParam = nArg;
  123585. for(i=0; i<nArg; i++){
  123586. #ifdef SQLITE_RTREE_INT_ONLY
  123587. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  123588. #else
  123589. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  123590. #endif
  123591. }
  123592. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  123593. }
  123594. }
  123595. /*
  123596. ** Register a new geometry function for use with the r-tree MATCH operator.
  123597. */
  123598. SQLITE_API int sqlite3_rtree_geometry_callback(
  123599. sqlite3 *db,
  123600. const char *zGeom,
  123601. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  123602. void *pContext
  123603. ){
  123604. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  123605. /* Allocate and populate the context object. */
  123606. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  123607. if( !pGeomCtx ) return SQLITE_NOMEM;
  123608. pGeomCtx->xGeom = xGeom;
  123609. pGeomCtx->pContext = pContext;
  123610. /* Create the new user-function. Register a destructor function to delete
  123611. ** the context object when it is no longer required. */
  123612. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  123613. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  123614. );
  123615. }
  123616. #if !SQLITE_CORE
  123617. #ifdef _WIN32
  123618. __declspec(dllexport)
  123619. #endif
  123620. SQLITE_API int sqlite3_rtree_init(
  123621. sqlite3 *db,
  123622. char **pzErrMsg,
  123623. const sqlite3_api_routines *pApi
  123624. ){
  123625. SQLITE_EXTENSION_INIT2(pApi)
  123626. return sqlite3RtreeInit(db);
  123627. }
  123628. #endif
  123629. #endif
  123630. /************** End of rtree.c ***********************************************/
  123631. /************** Begin file icu.c *********************************************/
  123632. /*
  123633. ** 2007 May 6
  123634. **
  123635. ** The author disclaims copyright to this source code. In place of
  123636. ** a legal notice, here is a blessing:
  123637. **
  123638. ** May you do good and not evil.
  123639. ** May you find forgiveness for yourself and forgive others.
  123640. ** May you share freely, never taking more than you give.
  123641. **
  123642. *************************************************************************
  123643. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  123644. **
  123645. ** This file implements an integration between the ICU library
  123646. ** ("International Components for Unicode", an open-source library
  123647. ** for handling unicode data) and SQLite. The integration uses
  123648. ** ICU to provide the following to SQLite:
  123649. **
  123650. ** * An implementation of the SQL regexp() function (and hence REGEXP
  123651. ** operator) using the ICU uregex_XX() APIs.
  123652. **
  123653. ** * Implementations of the SQL scalar upper() and lower() functions
  123654. ** for case mapping.
  123655. **
  123656. ** * Integration of ICU and SQLite collation sequences.
  123657. **
  123658. ** * An implementation of the LIKE operator that uses ICU to
  123659. ** provide case-independent matching.
  123660. */
  123661. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  123662. /* Include ICU headers */
  123663. #include <unicode/utypes.h>
  123664. #include <unicode/uregex.h>
  123665. #include <unicode/ustring.h>
  123666. #include <unicode/ucol.h>
  123667. /* #include <assert.h> */
  123668. #ifndef SQLITE_CORE
  123669. SQLITE_EXTENSION_INIT1
  123670. #else
  123671. #endif
  123672. /*
  123673. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  123674. ** operator.
  123675. */
  123676. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  123677. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  123678. #endif
  123679. /*
  123680. ** Version of sqlite3_free() that is always a function, never a macro.
  123681. */
  123682. static void xFree(void *p){
  123683. sqlite3_free(p);
  123684. }
  123685. /*
  123686. ** Compare two UTF-8 strings for equality where the first string is
  123687. ** a "LIKE" expression. Return true (1) if they are the same and
  123688. ** false (0) if they are different.
  123689. */
  123690. static int icuLikeCompare(
  123691. const uint8_t *zPattern, /* LIKE pattern */
  123692. const uint8_t *zString, /* The UTF-8 string to compare against */
  123693. const UChar32 uEsc /* The escape character */
  123694. ){
  123695. static const int MATCH_ONE = (UChar32)'_';
  123696. static const int MATCH_ALL = (UChar32)'%';
  123697. int iPattern = 0; /* Current byte index in zPattern */
  123698. int iString = 0; /* Current byte index in zString */
  123699. int prevEscape = 0; /* True if the previous character was uEsc */
  123700. while( zPattern[iPattern]!=0 ){
  123701. /* Read (and consume) the next character from the input pattern. */
  123702. UChar32 uPattern;
  123703. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  123704. assert(uPattern!=0);
  123705. /* There are now 4 possibilities:
  123706. **
  123707. ** 1. uPattern is an unescaped match-all character "%",
  123708. ** 2. uPattern is an unescaped match-one character "_",
  123709. ** 3. uPattern is an unescaped escape character, or
  123710. ** 4. uPattern is to be handled as an ordinary character
  123711. */
  123712. if( !prevEscape && uPattern==MATCH_ALL ){
  123713. /* Case 1. */
  123714. uint8_t c;
  123715. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  123716. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  123717. ** test string.
  123718. */
  123719. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  123720. if( c==MATCH_ONE ){
  123721. if( zString[iString]==0 ) return 0;
  123722. U8_FWD_1_UNSAFE(zString, iString);
  123723. }
  123724. iPattern++;
  123725. }
  123726. if( zPattern[iPattern]==0 ) return 1;
  123727. while( zString[iString] ){
  123728. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  123729. return 1;
  123730. }
  123731. U8_FWD_1_UNSAFE(zString, iString);
  123732. }
  123733. return 0;
  123734. }else if( !prevEscape && uPattern==MATCH_ONE ){
  123735. /* Case 2. */
  123736. if( zString[iString]==0 ) return 0;
  123737. U8_FWD_1_UNSAFE(zString, iString);
  123738. }else if( !prevEscape && uPattern==uEsc){
  123739. /* Case 3. */
  123740. prevEscape = 1;
  123741. }else{
  123742. /* Case 4. */
  123743. UChar32 uString;
  123744. U8_NEXT_UNSAFE(zString, iString, uString);
  123745. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  123746. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  123747. if( uString!=uPattern ){
  123748. return 0;
  123749. }
  123750. prevEscape = 0;
  123751. }
  123752. }
  123753. return zString[iString]==0;
  123754. }
  123755. /*
  123756. ** Implementation of the like() SQL function. This function implements
  123757. ** the build-in LIKE operator. The first argument to the function is the
  123758. ** pattern and the second argument is the string. So, the SQL statements:
  123759. **
  123760. ** A LIKE B
  123761. **
  123762. ** is implemented as like(B, A). If there is an escape character E,
  123763. **
  123764. ** A LIKE B ESCAPE E
  123765. **
  123766. ** is mapped to like(B, A, E).
  123767. */
  123768. static void icuLikeFunc(
  123769. sqlite3_context *context,
  123770. int argc,
  123771. sqlite3_value **argv
  123772. ){
  123773. const unsigned char *zA = sqlite3_value_text(argv[0]);
  123774. const unsigned char *zB = sqlite3_value_text(argv[1]);
  123775. UChar32 uEsc = 0;
  123776. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  123777. ** of deep recursion and N*N behavior in patternCompare().
  123778. */
  123779. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  123780. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  123781. return;
  123782. }
  123783. if( argc==3 ){
  123784. /* The escape character string must consist of a single UTF-8 character.
  123785. ** Otherwise, return an error.
  123786. */
  123787. int nE= sqlite3_value_bytes(argv[2]);
  123788. const unsigned char *zE = sqlite3_value_text(argv[2]);
  123789. int i = 0;
  123790. if( zE==0 ) return;
  123791. U8_NEXT(zE, i, nE, uEsc);
  123792. if( i!=nE){
  123793. sqlite3_result_error(context,
  123794. "ESCAPE expression must be a single character", -1);
  123795. return;
  123796. }
  123797. }
  123798. if( zA && zB ){
  123799. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  123800. }
  123801. }
  123802. /*
  123803. ** This function is called when an ICU function called from within
  123804. ** the implementation of an SQL scalar function returns an error.
  123805. **
  123806. ** The scalar function context passed as the first argument is
  123807. ** loaded with an error message based on the following two args.
  123808. */
  123809. static void icuFunctionError(
  123810. sqlite3_context *pCtx, /* SQLite scalar function context */
  123811. const char *zName, /* Name of ICU function that failed */
  123812. UErrorCode e /* Error code returned by ICU function */
  123813. ){
  123814. char zBuf[128];
  123815. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  123816. zBuf[127] = '\0';
  123817. sqlite3_result_error(pCtx, zBuf, -1);
  123818. }
  123819. /*
  123820. ** Function to delete compiled regexp objects. Registered as
  123821. ** a destructor function with sqlite3_set_auxdata().
  123822. */
  123823. static void icuRegexpDelete(void *p){
  123824. URegularExpression *pExpr = (URegularExpression *)p;
  123825. uregex_close(pExpr);
  123826. }
  123827. /*
  123828. ** Implementation of SQLite REGEXP operator. This scalar function takes
  123829. ** two arguments. The first is a regular expression pattern to compile
  123830. ** the second is a string to match against that pattern. If either
  123831. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  123832. ** is 1 if the string matches the pattern, or 0 otherwise.
  123833. **
  123834. ** SQLite maps the regexp() function to the regexp() operator such
  123835. ** that the following two are equivalent:
  123836. **
  123837. ** zString REGEXP zPattern
  123838. ** regexp(zPattern, zString)
  123839. **
  123840. ** Uses the following ICU regexp APIs:
  123841. **
  123842. ** uregex_open()
  123843. ** uregex_matches()
  123844. ** uregex_close()
  123845. */
  123846. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  123847. UErrorCode status = U_ZERO_ERROR;
  123848. URegularExpression *pExpr;
  123849. UBool res;
  123850. const UChar *zString = sqlite3_value_text16(apArg[1]);
  123851. (void)nArg; /* Unused parameter */
  123852. /* If the left hand side of the regexp operator is NULL,
  123853. ** then the result is also NULL.
  123854. */
  123855. if( !zString ){
  123856. return;
  123857. }
  123858. pExpr = sqlite3_get_auxdata(p, 0);
  123859. if( !pExpr ){
  123860. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  123861. if( !zPattern ){
  123862. return;
  123863. }
  123864. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  123865. if( U_SUCCESS(status) ){
  123866. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  123867. }else{
  123868. assert(!pExpr);
  123869. icuFunctionError(p, "uregex_open", status);
  123870. return;
  123871. }
  123872. }
  123873. /* Configure the text that the regular expression operates on. */
  123874. uregex_setText(pExpr, zString, -1, &status);
  123875. if( !U_SUCCESS(status) ){
  123876. icuFunctionError(p, "uregex_setText", status);
  123877. return;
  123878. }
  123879. /* Attempt the match */
  123880. res = uregex_matches(pExpr, 0, &status);
  123881. if( !U_SUCCESS(status) ){
  123882. icuFunctionError(p, "uregex_matches", status);
  123883. return;
  123884. }
  123885. /* Set the text that the regular expression operates on to a NULL
  123886. ** pointer. This is not really necessary, but it is tidier than
  123887. ** leaving the regular expression object configured with an invalid
  123888. ** pointer after this function returns.
  123889. */
  123890. uregex_setText(pExpr, 0, 0, &status);
  123891. /* Return 1 or 0. */
  123892. sqlite3_result_int(p, res ? 1 : 0);
  123893. }
  123894. /*
  123895. ** Implementations of scalar functions for case mapping - upper() and
  123896. ** lower(). Function upper() converts its input to upper-case (ABC).
  123897. ** Function lower() converts to lower-case (abc).
  123898. **
  123899. ** ICU provides two types of case mapping, "general" case mapping and
  123900. ** "language specific". Refer to ICU documentation for the differences
  123901. ** between the two.
  123902. **
  123903. ** To utilise "general" case mapping, the upper() or lower() scalar
  123904. ** functions are invoked with one argument:
  123905. **
  123906. ** upper('ABC') -> 'abc'
  123907. ** lower('abc') -> 'ABC'
  123908. **
  123909. ** To access ICU "language specific" case mapping, upper() or lower()
  123910. ** should be invoked with two arguments. The second argument is the name
  123911. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  123912. ** as the second argument is the same as invoking the 1 argument version
  123913. ** of upper() or lower().
  123914. **
  123915. ** lower('I', 'en_us') -> 'i'
  123916. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  123917. **
  123918. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  123919. */
  123920. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  123921. const UChar *zInput;
  123922. UChar *zOutput;
  123923. int nInput;
  123924. int nOutput;
  123925. UErrorCode status = U_ZERO_ERROR;
  123926. const char *zLocale = 0;
  123927. assert(nArg==1 || nArg==2);
  123928. if( nArg==2 ){
  123929. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  123930. }
  123931. zInput = sqlite3_value_text16(apArg[0]);
  123932. if( !zInput ){
  123933. return;
  123934. }
  123935. nInput = sqlite3_value_bytes16(apArg[0]);
  123936. nOutput = nInput * 2 + 2;
  123937. zOutput = sqlite3_malloc(nOutput);
  123938. if( !zOutput ){
  123939. return;
  123940. }
  123941. if( sqlite3_user_data(p) ){
  123942. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  123943. }else{
  123944. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  123945. }
  123946. if( !U_SUCCESS(status) ){
  123947. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  123948. return;
  123949. }
  123950. sqlite3_result_text16(p, zOutput, -1, xFree);
  123951. }
  123952. /*
  123953. ** Collation sequence destructor function. The pCtx argument points to
  123954. ** a UCollator structure previously allocated using ucol_open().
  123955. */
  123956. static void icuCollationDel(void *pCtx){
  123957. UCollator *p = (UCollator *)pCtx;
  123958. ucol_close(p);
  123959. }
  123960. /*
  123961. ** Collation sequence comparison function. The pCtx argument points to
  123962. ** a UCollator structure previously allocated using ucol_open().
  123963. */
  123964. static int icuCollationColl(
  123965. void *pCtx,
  123966. int nLeft,
  123967. const void *zLeft,
  123968. int nRight,
  123969. const void *zRight
  123970. ){
  123971. UCollationResult res;
  123972. UCollator *p = (UCollator *)pCtx;
  123973. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  123974. switch( res ){
  123975. case UCOL_LESS: return -1;
  123976. case UCOL_GREATER: return +1;
  123977. case UCOL_EQUAL: return 0;
  123978. }
  123979. assert(!"Unexpected return value from ucol_strcoll()");
  123980. return 0;
  123981. }
  123982. /*
  123983. ** Implementation of the scalar function icu_load_collation().
  123984. **
  123985. ** This scalar function is used to add ICU collation based collation
  123986. ** types to an SQLite database connection. It is intended to be called
  123987. ** as follows:
  123988. **
  123989. ** SELECT icu_load_collation(<locale>, <collation-name>);
  123990. **
  123991. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  123992. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  123993. ** collation sequence to create.
  123994. */
  123995. static void icuLoadCollation(
  123996. sqlite3_context *p,
  123997. int nArg,
  123998. sqlite3_value **apArg
  123999. ){
  124000. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  124001. UErrorCode status = U_ZERO_ERROR;
  124002. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  124003. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  124004. UCollator *pUCollator; /* ICU library collation object */
  124005. int rc; /* Return code from sqlite3_create_collation_x() */
  124006. assert(nArg==2);
  124007. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  124008. zName = (const char *)sqlite3_value_text(apArg[1]);
  124009. if( !zLocale || !zName ){
  124010. return;
  124011. }
  124012. pUCollator = ucol_open(zLocale, &status);
  124013. if( !U_SUCCESS(status) ){
  124014. icuFunctionError(p, "ucol_open", status);
  124015. return;
  124016. }
  124017. assert(p);
  124018. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  124019. icuCollationColl, icuCollationDel
  124020. );
  124021. if( rc!=SQLITE_OK ){
  124022. ucol_close(pUCollator);
  124023. sqlite3_result_error(p, "Error registering collation function", -1);
  124024. }
  124025. }
  124026. /*
  124027. ** Register the ICU extension functions with database db.
  124028. */
  124029. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  124030. struct IcuScalar {
  124031. const char *zName; /* Function name */
  124032. int nArg; /* Number of arguments */
  124033. int enc; /* Optimal text encoding */
  124034. void *pContext; /* sqlite3_user_data() context */
  124035. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  124036. } scalars[] = {
  124037. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  124038. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  124039. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  124040. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  124041. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  124042. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  124043. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  124044. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  124045. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  124046. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  124047. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  124048. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  124049. };
  124050. int rc = SQLITE_OK;
  124051. int i;
  124052. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  124053. struct IcuScalar *p = &scalars[i];
  124054. rc = sqlite3_create_function(
  124055. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  124056. );
  124057. }
  124058. return rc;
  124059. }
  124060. #if !SQLITE_CORE
  124061. #ifdef _WIN32
  124062. __declspec(dllexport)
  124063. #endif
  124064. SQLITE_API int sqlite3_icu_init(
  124065. sqlite3 *db,
  124066. char **pzErrMsg,
  124067. const sqlite3_api_routines *pApi
  124068. ){
  124069. SQLITE_EXTENSION_INIT2(pApi)
  124070. return sqlite3IcuInit(db);
  124071. }
  124072. #endif
  124073. #endif
  124074. /************** End of icu.c *************************************************/
  124075. /************** Begin file fts3_icu.c ****************************************/
  124076. /*
  124077. ** 2007 June 22
  124078. **
  124079. ** The author disclaims copyright to this source code. In place of
  124080. ** a legal notice, here is a blessing:
  124081. **
  124082. ** May you do good and not evil.
  124083. ** May you find forgiveness for yourself and forgive others.
  124084. ** May you share freely, never taking more than you give.
  124085. **
  124086. *************************************************************************
  124087. ** This file implements a tokenizer for fts3 based on the ICU library.
  124088. */
  124089. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124090. #ifdef SQLITE_ENABLE_ICU
  124091. /* #include <assert.h> */
  124092. /* #include <string.h> */
  124093. #include <unicode/ubrk.h>
  124094. /* #include <unicode/ucol.h> */
  124095. /* #include <unicode/ustring.h> */
  124096. #include <unicode/utf16.h>
  124097. typedef struct IcuTokenizer IcuTokenizer;
  124098. typedef struct IcuCursor IcuCursor;
  124099. struct IcuTokenizer {
  124100. sqlite3_tokenizer base;
  124101. char *zLocale;
  124102. };
  124103. struct IcuCursor {
  124104. sqlite3_tokenizer_cursor base;
  124105. UBreakIterator *pIter; /* ICU break-iterator object */
  124106. int nChar; /* Number of UChar elements in pInput */
  124107. UChar *aChar; /* Copy of input using utf-16 encoding */
  124108. int *aOffset; /* Offsets of each character in utf-8 input */
  124109. int nBuffer;
  124110. char *zBuffer;
  124111. int iToken;
  124112. };
  124113. /*
  124114. ** Create a new tokenizer instance.
  124115. */
  124116. static int icuCreate(
  124117. int argc, /* Number of entries in argv[] */
  124118. const char * const *argv, /* Tokenizer creation arguments */
  124119. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  124120. ){
  124121. IcuTokenizer *p;
  124122. int n = 0;
  124123. if( argc>0 ){
  124124. n = strlen(argv[0])+1;
  124125. }
  124126. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  124127. if( !p ){
  124128. return SQLITE_NOMEM;
  124129. }
  124130. memset(p, 0, sizeof(IcuTokenizer));
  124131. if( n ){
  124132. p->zLocale = (char *)&p[1];
  124133. memcpy(p->zLocale, argv[0], n);
  124134. }
  124135. *ppTokenizer = (sqlite3_tokenizer *)p;
  124136. return SQLITE_OK;
  124137. }
  124138. /*
  124139. ** Destroy a tokenizer
  124140. */
  124141. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  124142. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  124143. sqlite3_free(p);
  124144. return SQLITE_OK;
  124145. }
  124146. /*
  124147. ** Prepare to begin tokenizing a particular string. The input
  124148. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  124149. ** used to incrementally tokenize this string is returned in
  124150. ** *ppCursor.
  124151. */
  124152. static int icuOpen(
  124153. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  124154. const char *zInput, /* Input string */
  124155. int nInput, /* Length of zInput in bytes */
  124156. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  124157. ){
  124158. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  124159. IcuCursor *pCsr;
  124160. const int32_t opt = U_FOLD_CASE_DEFAULT;
  124161. UErrorCode status = U_ZERO_ERROR;
  124162. int nChar;
  124163. UChar32 c;
  124164. int iInput = 0;
  124165. int iOut = 0;
  124166. *ppCursor = 0;
  124167. if( zInput==0 ){
  124168. nInput = 0;
  124169. zInput = "";
  124170. }else if( nInput<0 ){
  124171. nInput = strlen(zInput);
  124172. }
  124173. nChar = nInput+1;
  124174. pCsr = (IcuCursor *)sqlite3_malloc(
  124175. sizeof(IcuCursor) + /* IcuCursor */
  124176. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  124177. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  124178. );
  124179. if( !pCsr ){
  124180. return SQLITE_NOMEM;
  124181. }
  124182. memset(pCsr, 0, sizeof(IcuCursor));
  124183. pCsr->aChar = (UChar *)&pCsr[1];
  124184. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  124185. pCsr->aOffset[iOut] = iInput;
  124186. U8_NEXT(zInput, iInput, nInput, c);
  124187. while( c>0 ){
  124188. int isError = 0;
  124189. c = u_foldCase(c, opt);
  124190. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  124191. if( isError ){
  124192. sqlite3_free(pCsr);
  124193. return SQLITE_ERROR;
  124194. }
  124195. pCsr->aOffset[iOut] = iInput;
  124196. if( iInput<nInput ){
  124197. U8_NEXT(zInput, iInput, nInput, c);
  124198. }else{
  124199. c = 0;
  124200. }
  124201. }
  124202. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  124203. if( !U_SUCCESS(status) ){
  124204. sqlite3_free(pCsr);
  124205. return SQLITE_ERROR;
  124206. }
  124207. pCsr->nChar = iOut;
  124208. ubrk_first(pCsr->pIter);
  124209. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  124210. return SQLITE_OK;
  124211. }
  124212. /*
  124213. ** Close a tokenization cursor previously opened by a call to icuOpen().
  124214. */
  124215. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  124216. IcuCursor *pCsr = (IcuCursor *)pCursor;
  124217. ubrk_close(pCsr->pIter);
  124218. sqlite3_free(pCsr->zBuffer);
  124219. sqlite3_free(pCsr);
  124220. return SQLITE_OK;
  124221. }
  124222. /*
  124223. ** Extract the next token from a tokenization cursor.
  124224. */
  124225. static int icuNext(
  124226. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  124227. const char **ppToken, /* OUT: *ppToken is the token text */
  124228. int *pnBytes, /* OUT: Number of bytes in token */
  124229. int *piStartOffset, /* OUT: Starting offset of token */
  124230. int *piEndOffset, /* OUT: Ending offset of token */
  124231. int *piPosition /* OUT: Position integer of token */
  124232. ){
  124233. IcuCursor *pCsr = (IcuCursor *)pCursor;
  124234. int iStart = 0;
  124235. int iEnd = 0;
  124236. int nByte = 0;
  124237. while( iStart==iEnd ){
  124238. UChar32 c;
  124239. iStart = ubrk_current(pCsr->pIter);
  124240. iEnd = ubrk_next(pCsr->pIter);
  124241. if( iEnd==UBRK_DONE ){
  124242. return SQLITE_DONE;
  124243. }
  124244. while( iStart<iEnd ){
  124245. int iWhite = iStart;
  124246. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  124247. if( u_isspace(c) ){
  124248. iStart = iWhite;
  124249. }else{
  124250. break;
  124251. }
  124252. }
  124253. assert(iStart<=iEnd);
  124254. }
  124255. do {
  124256. UErrorCode status = U_ZERO_ERROR;
  124257. if( nByte ){
  124258. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  124259. if( !zNew ){
  124260. return SQLITE_NOMEM;
  124261. }
  124262. pCsr->zBuffer = zNew;
  124263. pCsr->nBuffer = nByte;
  124264. }
  124265. u_strToUTF8(
  124266. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  124267. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  124268. &status /* Output success/failure */
  124269. );
  124270. } while( nByte>pCsr->nBuffer );
  124271. *ppToken = pCsr->zBuffer;
  124272. *pnBytes = nByte;
  124273. *piStartOffset = pCsr->aOffset[iStart];
  124274. *piEndOffset = pCsr->aOffset[iEnd];
  124275. *piPosition = pCsr->iToken++;
  124276. return SQLITE_OK;
  124277. }
  124278. /*
  124279. ** The set of routines that implement the simple tokenizer
  124280. */
  124281. static const sqlite3_tokenizer_module icuTokenizerModule = {
  124282. 0, /* iVersion */
  124283. icuCreate, /* xCreate */
  124284. icuDestroy, /* xCreate */
  124285. icuOpen, /* xOpen */
  124286. icuClose, /* xClose */
  124287. icuNext, /* xNext */
  124288. };
  124289. /*
  124290. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  124291. */
  124292. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  124293. sqlite3_tokenizer_module const**ppModule
  124294. ){
  124295. *ppModule = &icuTokenizerModule;
  124296. }
  124297. #endif /* defined(SQLITE_ENABLE_ICU) */
  124298. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124299. /************** End of fts3_icu.c ********************************************/